Reputation: 3346
If i have this json response
{"error":"repeated"}
Why the alert is not showed? It is needed put somewhere dataType: "json"
?
$(function () {
$("#box a").click(function () {
var selectedId = $(this).attr("class");
$.post("new_list.php", {
id_user: <?php echo $id;?>,
id_list: selectedId
}, function (data) {
if(data.error == 'repeated') {
alert("error");
}
});
});
});
thanks
Upvotes: 1
Views: 156
Reputation: 94499
$(function () {
$("#box a").click(function () {
var selectedId = $(this).attr("class");
$.post("new_list.php", {
id_user: <?php echo $id;?>,
id_list: selectedId
}, function (data) {
if(data.error == 'repeated') {
alert("error");
}
},dataType: "json" );
});
});
The following snippet will let jquery know your expecting json.
Upvotes: 0
Reputation: 5100
Check if your reply is a string instead of an object. Then you must call
var obj = jQuery.parseJSON(data);
And use obj.error to check if it is 'repeated'
Upvotes: 0
Reputation: 59403
It would be a matter of converting the response string into a Javascript object:
function (data) {
// Parse the JSON
data = JSON.parse(data);
if(data.error == 'repeated') {
alert("error");
}
}
Although you could just use the jQuery.getJSON
function instead, saving yourself some trouble
Upvotes: 1
Reputation: 47776
It's not going to automatically parse it as JSON unless you tell it to.
$(function () {
$("#box a").click(function () {
var selectedId = $(this).attr("class");
$.post("new_list.php", {
id_user: <?php echo $id;?>,
id_list: selectedId
}, function (data) {
if(data.error == 'repeated') {
alert("error");
}
},
"json"); //Here, add this as last parameter
});
});
Upvotes: 2