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

TryHarder picture TryHarder · Nov 8, 2011 · Viewed 15.6k times · Source

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

  1. Why isn't $testscore receiving a value from the ajax script?
  2. How can I fix this?

Answer

nickb picture nickb · Nov 8, 2011

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']

Edit: See http://api.jquery.com/jQuery.ajax/, "Sending Data to the Server"