I have a html form with a button on which there is a onclick event
<form id = "abc" action = "xyz.php" method = "post">
<input type="button" name="submitButton" value="Submit"
id="submitButton" onclick = "Function()">
</form>
In the JS code, I am trying to post a value of a textbox and trying to get the array from the PHP through json_encode.
var valueToSend = $('#textbox').val();
var imagesReturned = new Array();
$.ajax({
url: "xyz.php",
type: "POST",
data: valueToSend,
dataType:"json",
success: function(result) {
var data = jQuery.parseJSON(result);
alert(data);
}
});
And here is my PHP code,
if(isset($_POST['valueToSend']))
{
$searchValues = explode(' ',$_POST['valueToSend']);
// Some processing here
echo (json_encode($responseArray));
}
When I alert the data, I get null, What am I missing?
Thanks!
4 Answers 4
The problem is within your Ajax request, the data key expects a key/value pair, not just a value.
What you're looking for is something similar to the following:
var valueToSend = {
'valueToSend': $('#textbox').val()
}
In addition, you're setting the dataType key to json, so there is no need to pass the data variable through parseJSON. As such, the success function only needs to be declared as follows:
'success': function(result) {
alert(result);
}
2 Comments
dataType:"json", you don't need to parse the response, jQuery will do that for you such that you can work with the result object directly.var valueToSend = $('#textbox').val();
var imagesReturned = new Array();
$.ajax({
url: "xyz.php",
type: "POST",
data: {"valueToSend":valueToSend},
dataType:"json",
success: function(result) {
var data = jQuery.parseJSON(result);
alert(data);
}
});
correct the format of data in ajax
1 Comment
data field of yours look suspicious to me
$.ajax({
url: "xyz.php",
type: "POST",
data:{valueToSend:valueToSend},
dataType:"json",
success: function(result) {
alert(result);
}
});
2 Comments
The problem was in the PHP code.
I removed the check, if(isset($_POST['valueToSend'])) and its working...
$responseArraycontain?parseJSONand see ifresultis the expected value.var data = jQuery.parseJSON(result);in your callback. It's already parsed. On the other hand, your JSON response from PHP will always be empty. You'll never send the proper response because it'll contain invalid data.