Reputation: 641
I have the html page below:
<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$("#b1").click(function(event) {
$.ajax({
type : "POST",
url : "index.php",
data : "valx=2",
contentType : "application/x-www-form-urlencoded",
dataType : "text",
complete : function() {
alert('post completed');
},
error : function() {
alert('error condition');
},
success : function(data) {
$('.result').html(data);
alert('data is returned');
},
statusCode : {
200 : function() {
alert("page was found");
}
}
});
event.preventDefault();
});
});
</script>
</head>
<body>
<div>
<button id="b1">
Click Me!
</button>
</div>
<div class="result"></div>
</body>
</html>
And then I have the following php page:
<?php
$my_string = $_REQUEST["valx"];
$my_string = $my_string +9;
echo $my_string;
?>
Everything works perfectly as is, but I was trying to figure out how to change the post data to the form:
data: '{ valx:"2"}'
And this is where it breaks. I tried many forms of data: '{ valx:"2"}' and still no luck. It seems as if the php script is not getting the data correctly. Also note that using this format it seems that contentType : "application/x-www-form-urlencoded",
needs to be changed as well.
So the question is how do you pass data of the form data: '{ valx:"2"}'
and get back a response of 11?
Thanks, Jim
Upvotes: 0
Views: 588
Reputation: 171700
Use an object not a string. jQuery will parse the object into form encoded format. Also remove your contentType
option completely since this is not the type of data being sent, rather it is for data received and you will be receiving text/html
data : { valx:"2"},
Upvotes: 0
Reputation: 239521
The data parameter accepts a var=value&var1=value1
form, or a JavaScript object with keys/values. You've given it this, which is a string...
data: '{ valx:"2"}`
... when you should have given it this, which is a real JS object:
data: { valx:"2"}
Upvotes: 3