How can I fix this undefined index error Jquery Ajax to PHP

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

I m using Jquery, Ajax and PHP to try and send a variable to be written in a mysql database. The Ajax request is being made but the variable is not being picked up by the php. I don t know why this is the case.

Using firebug and console.log() I can see that a POST has been made to write_results.php

If I check the Response it says

  Notice   :  Undefined index: testscore in    E:write_results.php    on line    2   

Here is my PHP

<?php 
  $testscore=$_POST[ testscore ];  //get testscore from Ajax 
  include  DB.php ;
  $con = mysql_connect($host,$user,$pass);
  $dbs = mysql_select_db($databaseName, $con); 
     if (isset($_POST[ testscore ])) {  
       $addClient  = "INSERT INTO variables (`id` ,`name`) VALUES (NULL, $testscore )";  
       mysql_query($addClient) or die(mysql_error());  
       }

?>  

Here is my ajax script

<script type="text/javascript">
$(document).ready(function() {  
testscore ="tryagain"; //testvalue to enter into the mysql database
  $.ajax({  
    type: "POST",  
    url: "write_results.php",  
    data: testscore,      
    success: function(){  
      $( #box2 ).html("success");
    } 
  })
}); 
</script>
  My questions   
    • Why isn t $testscore receiving a value from the ajax script?
    • How can I fix this?

Answers

You re not telling the JS how to send your POST parameters. Change your JS to:

data: {  testscore :testscore },

This is the equivalent of "testscore=" + testcore in key=value form. It tells JS and PHP that you want the variable testscore to be mapped to the key "testscore", which you ll then pick up with $_POST[ testscore ]

http://api.jquery.com/jQuery.ajax/ http://api.jquery.com/jQuery.ajax/

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/8046482/how-can-i-fix-this-undefined-index-error-jquery-ajax-to-php

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils