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.
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.
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.
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.