Trying to send a variable with ajax to php.
The js:
var test1 = "test"
$.ajax({
type : "POST",
url : "getid.php",
data: {test1 : test1},
success: function() {
console.log("message sent!");
}
});
"message sent!" comes up in the console
The php:
<?php
$test1 = $_POST['test1'];
echo $test1;
?>
Error message:
Notice: Undefined index: test1...
I don't really see what i have done wrong here... Any ideas?
UPDATE* when doing `
$.ajax({
type : "POST",
url : "getid.php",
data: {"test1" : test1},
success: function(msg) {
console.log("message sent!");
console.log(msg);
}
});
This logs "test"
Still getting the same error in the php though..
Alter you jQuery code:
var test1 = "test"
$.ajax({
type : "post",
url : "getid.php",
data: {"test1" : test1}, // this is the row that was causing the problem
success: function(msg) {
console.log(msg);
}
});
You had to put test1
in quotes because it was a defined variable containing "test" which resulted in data being {"test":"test"}
Its becouse the response is given to the callback functions as arguments. try somthing like this
var test1 = "test"
$.ajax({
type : "POST",
url : "getid.php",
data: {"test1" : test1},
success: function(data) { // data argument here
console.log("message sent!");
console.log("data:",data); // log it out here
}
});