Reputation: 1425
i have the problem that jquery do not want my json.
here is my jquery code:
$.ajax({
type: "POST",
url: "js/resize.php",
data: data,
success: function(data) {
/* works
var data = [
{"og_src":"img\/base\/logo.png","src":"img\/base\/das-logo.png"},
{"og_src":"\/img\/studio\/lounge-2.JPG","src":"\/img\/studio\/lounge-2.JPG"},
{"og_src":"\/img\/studio\/desk.JPG","src":"\/img\/studio\/desk.JPG"}
];
*/
// console.log(data);
$.each(data, function(key, image){
console.log(image);
var el = $("img[rel='"+image.og_src+"']");
...
If I copy the sent data to my script and make a var data = ... it works fine.
The php data are made by a simple echo json_encode($stack);
If I make a php-echo like
echo '[{"og_src":"img\/base\/logo.png","src":"img\/base\/das-logo.png"}, {"og_src":"\/img\/studio\/lounge-2.JPG","src":"\/img\/studio\/lounge-2.JPG"}, {"og_src":"\/img\/studio\/desk.JPG","src":"\/img\/studio\/desk.JPG"}]';
it do not work ether.
All files are on UTF-8.
Console.log shows the result of console.log(image); as a single letter; Whats wrong, I'am trying this for hours now and I'am very desperated. Thanks for an help in advance.
Upvotes: 0
Views: 230
Reputation: 529
You should tell jQuery that the returned data is expected to be 'json' using the dataType property:
$.ajax({
type: "POST",
url: "js/resize.php",
data: data,
dataType: 'json',
success: function(data) {
}
});
Upvotes: 1
Reputation: 943163
It looks like your JSON is being interpreted as HTML (so when you run each
of it, it loops over each character of the HTML source).
Make sure that your PHP script says that it is outputting JSON (PHP defaults to HTML).
header("Content-Type: application/json");
You could also pass the dataType: "json"
option to ajax
so that the jQuery library will try to parse the result of the HTTP request as JSON, no matter what the server says it is. Having correct information in the HTTP response is a much cleaner solution though.
Upvotes: 2