I am trying to pass a single variable from javascript to PHP using jQuery AJAX.
Javascript:
$(document).ready(function() {
$('.ok').on('click', function(e){
var value = 5;
$.ajax({
url: 'tabulka.php',
type: "POST",
data: {x : value},
success: function(){
alert(value);
}
});
});
});
PHP:
if($_SERVER['REQUEST_METHOD']){
$value = $_POST['x'];
echo $value;
}
I get the alert from ajax with the expected value but in PHP I get this error: Notice: Undefined index: value in C:\xampp\htdocs\test\tabulka.php on line 71
When I uncomment the dataType: 'json' I don't even get the alert from AJAX.
3 Answers 3
Instead of this
data: ({value : value}),
Try using this,
data: "value="+value,
And you are not at all passing "OK" but you are receiving it. If you want to pass OK also as a parameter try this.
data: "value="+value+"&OK=Somevalue",
That should work.
6 Comments
data: "value="+value, but then you might not have got the error but a blank response. But when you tried this data: ({value : value}), you got an error. Am I right ?&& isset($_POST['OK'])if condition with AND. If you don't pass any values for "OK" it will not go inside the if. Do you have any .htaccess file used ?Your JavaScript
data: {'value' : value}
notice the single quote and no parenthesis
Your PHP:
If(isset($_POST['value'])){
$val = $_POST['value'];
}
Your JavaScript was formatted incorrectly. data is an object, or an associative array in other words.
Your PHP code has unnecessary string comparison. Whenever a post is made to a PHP script, you will access them using $_POST array.
For instance, if you posted this via AJAX
data:{ 'name' : 'jake', 'age' : 1024}
You would access them in PHP by
$name = $_POST['name']
$age = $_POST['age']
Also, it is wise to use PHP isset to verify that a post variable exists before trying to access them. That way you will not have an exception if expected post data is not.
1 Comment
check following line
var value = $(this).find('td:first').html();
set some hard coded value for 'value' variable like below
var value='some value';
if above works then check the value you assigned using $(this).find('td:first').html()
['value']is being used as an array index.