Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
45
rated 0 times [  46] [ 1]  / answers: 1 / hits: 87327  / 11 Years ago, thu, december 26, 2013, 12:00:00

I the following PHP code:



echo <img src='../images/edit.png' onclick='showEditDiv( . json_encode($row) . );'>;


Here is the HTML result:



<img src='../images/edit.png' onclick='showEditDiv({ID:2,NAME:John Smith,EMAIL:[email protected]});'>


And here is the Javascript code:



function showEditDiv(data) {
alert(data);
data = JSON.parse(data);
alert(data);
for (i=0; i< data.length; i++){
alert(data[i]);
};
}


The problem is I'm not getting the desired array in the JS parameter.
The first alert shows [object Object] and that's all, no more alerts.
Where is the problem? My code is based on the examples I found here. All I want is to pass an array to JS function, which is in a separated .js file. I don't want to use JQuery, prefer native JS.


More From » php

 Answers
6

You aren't passing JSON to the function (JSON would be a string, hence ending/beginning with quotes). What you're passing is a JavaScript object literal. See the difference:


Object literal


{"ID":"2","NAME":"John Smith","EMAIL":"[email protected]"}

JSON string


"{"ID":"2","NAME":"John Smith","EMAIL":"[email protected]"}"
// or, easier than escaping all those quotes..
'{"ID":"2","NAME":"John Smith","EMAIL":"[email protected]"}'

Of course, for your purposes, the object literal may be easier to work with. In that case you just need to remove the JSON.parse from your JavaScript code:


function showEditDiv(data) {
// The below won't work unless you change your input data to a
// JS array literal..
/* for (i=0; i< data.length; i++){
alert(data[i]);
}; */

// ..but you can do this (though it's risky to iterate through keys
// on an object without at least using HasOwnProperty)
for (var key in data) {
alert(data[key]);
}
}

[#73546] Monday, December 23, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jennie

Total Points: 593
Total Questions: 102
Total Answers: 106

Location: Federated States of Micronesia
Member since Fri, Sep 16, 2022
2 Years ago
jennie questions
;