I trie to get an json in my jquery ajax successe: to worke but i dose not.......
Thats what i tried to do:
$("#addcatform").submit(function() {
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "ajax.php",
data: str,
success: function(data){
var json_x = data;
alert(json_x.firstName2);
$('#result').html(json_x.firstName2);
$('#result2').html(json_x.b);
}
});
return false;
event.preventDefault();
}); // submit end
the php echos this:
$arr = array ('firstName2'=>'hallo','b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
Whats wrong with this? Thanks for helping!!!!
You need to parse your json before using it,
You can add a dataType in your request - jQuery will parse your response json
$.ajax({
type: "POST",
url: "ajax.php",
dataType: 'json',
Or, you can parse it yourself -
success: function(data){
var json_x = $.parseJSON(data);
You could try this:
var data=$.ajax({
type: "POST",
url: 'ajax.php',
data: {
data:str
},
async: false,
dataType: 'json'
});
var msg= data.responseText;
msg=jQuery.parseJSON(msg);
I usually send either an array or the message 'error' from my php page
if(msg=='error')
{
/* do something */
}
else
// use the data
This works with jquery 1.6->1.8
EDIT: Since jquery 1.8 async is deprecated. i would recommend this format :
$.ajax({
type: "POST",
url: 'ajax.php',
data: {
data:str
},
dataType: 'json',
).done(function(data) {
// do something with the data
})
.fail(function() {
// give appropriate message
})
http://api.jquery.com/jquery.ajax/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With