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?
Try using
data: "testscore=" + testscore,
The data needs to be formatted as a query string.In your php code you get the $testscore value form $_POST['testscore']. $_POST is a super global array and testscore is the index here. This $_POST array's indexes come from the field names of a form you post. In your case you are using ajax to pass data to the php page. You can pass by either GET method or POST method. Since you are passing by POST as you have specified type:POST in your ajax code, you will be able to use $_POST varibale in your php file. But you are not specifying the array indexes in your ajax code which will hold the values.
You need to provide the key value pair. You can do it in wither way:
You can also send the key value pair to PHP file in JSON format as below:
If you have multiple values(e.g. two) to send you can do as below:
And in your PHP code you can get this as below, if using post as type in ajax:
You're not telling the JS how to send your POST parameters. Change your JS to:
This is the equivalent of
"testscore=" + testcore
inkey=value
form. It tells JS and PHP that you want the variabletestscore
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"