jQuery $.post processing JSON response
Ok then..the data object you're getting back from the post is: {"id":"abc","images":[{"color123":"somelink.com\/123","color223":"somelink.com\/223"}]};
If you change your alert, you'll find the values you're looking for:
$.post(
"test.php",
{ id: product_id, "images[]": jQuery.makeArray(image_links) },
function(data) {
var response = jQuery.parseJSON(data);
var images = response.images[0];
for (var i in images){
alert(images[i]);
}
}
);
jQuery post with JSON response
Try this in another page and show in console.
<?php
if($_POST){
header('Content-type:application/json');
$data = Array(
'status' => '1',
'msg' => '',
'progress' => '0.24',
'time' =>'<span class="text-white">06:51</span> left (at 21KB/sec)',
'size' => '<span class="text-white">26KB</span> / 10.91MB (0.24%)');
echo json_encode($data);
exit();
}
?>
<input type="button" onclick="senddata()" value="send" />
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
function senddata(){
var upload_id=1
$.post('test.php' , { upload_id: upload_id },
function (response) {
console.log(response.status);
}, "json");
}
</script>
Parse JSON response using jQuery
Give this a try:
success: function(json) {
console.log(JSON.stringify(json.topics));
$.each(json.topics, function(idx, topic){
$("#nav").html('<a href="' + topic.link_src + '">' + topic.link_text + "</a>");
});
},
Returning JSON data using jQuery POST function from server
It seems you just have to parse the JSON data into an object using parseJSON()
:
$.post("order.php", { product: product_id, coupon: coupon },
function(data) {
data = $.parseJSON( data );
$("#price").html("$" + data.price);
$("#discount").html("$" + data.discount);
$("#total").html("$" + data.total);
});
Send JSON data via POST (ajax) and receive json response from Controller (MVC)
Create a model
public class Person
{
public string Name { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
}
Controllers Like Below
public ActionResult PersonTest()
{
return View();
}
[HttpPost]
public ActionResult PersonSubmit(Vh.Web.Models.Person person)
{
System.Threading.Thread.Sleep(2000); /*simulating slow connection*/
/*Do something with object person*/
return Json(new {msg="Successfully added "+person.Name });
}
Javascript
<script type="text/javascript">
function send() {
var person = {
name: $("#id-name").val(),
address:$("#id-address").val(),
phone:$("#id-phone").val()
}
$('#target').html('sending..');
$.ajax({
url: '/test/PersonSubmit',
type: 'post',
dataType: 'json',
contentType: 'application/json',
success: function (data) {
$('#target').html(data.msg);
},
data: JSON.stringify(person)
});
}
</script>
jQuery ajax request with json response, how to?
You need to call the
$.parseJSON();
For example:
...
success: function(data){
var json = $.parseJSON(data); // create an object with the key of the array
alert(json.html); // where html is the key of array that you want, $response['html'] = "<a>something..</a>";
},
error: function(data){
var json = $.parseJSON(data);
alert(json.error);
} ...
see this in
http://api.jquery.com/jQuery.parseJSON/
if you still have the problem of slashes:
search for security.magicquotes.disabling.php
or:
function.stripslashes.php
Note:
This answer here is for those who try to use $.ajax
with the dataType
property set to json
and even that got the wrong response type. Defining the header('Content-type: application/json');
in the server may correct the problem, but if you are returning text/html
or any other type, the $.ajax
method should convert it to json
. I make a test with older versions of jQuery and only after version 1.4.4
the $.ajax
force to convert any content-type to the dataType
passed. So if you have this problem, try to update your jQuery version.
How to parse JSON data with jQuery / JavaScript?
Assuming your server side script doesn't set the proper Content-Type: application/json
response header you will need to indicate to jQuery that this is JSON by using the dataType: 'json'
parameter.
Then you could use the $.each()
function to loop through the data:
$.ajax({
type: 'GET',
url: 'http://example/functions.php',
data: { get_param: 'value' },
dataType: 'json',
success: function (data) {
$.each(data, function(index, element) {
$('body').append($('<div>', {
text: element.name
}));
});
}
});
or use the $.getJSON
method:
$.getJSON('/functions.php', { get_param: 'value' }, function(data) {
$.each(data, function(index, element) {
$('body').append($('<div>', {
text: element.name
}));
});
});
Parse JSON from JQuery.ajax success data
The data is coming back as the string representation of the JSON and you aren't converting it back to a JavaScript object. Set the dataType
to just 'json'
to have it converted automatically.
Related Topics
How to Use MySQLi Bind_Param Dynamically
How to Solve This "Warning: MySQLi_Connect(): (Hy000/1049): Unknown Database" Problem
How to Dynamically Set Table Name in Eloquent Model
PHP Fopen() Error: Failed to Open Stream: Permission Denied
Using a Variable as an Operator
Php.Ini Production VS Development
Php's Simplexml: How to Use Colons in Names
Google Recaptcha - Keep Getting 'Incorrect-Captcha-Sol'
What Is the Rfc Compliant and Working Regular Expression to Check If a String Is a Valid Url
Variable Variables in PHP - What Is Their Purpose
Access JSON Object Name in PHP
Add X Days to Date, Excluding Weekends
Mysqli Query to Loop Through Array and Update Multiple Rows
Call to Undefined Function Oci_Connect, PHP_Oci8_12C.Dll, Windows 8.1, PHP5.6.6