Reputation: 231
I have a PHP page that is returning a JSON object like this:
header('Content-Type:application/json');
echo <<<HERE_DOC
[ {content: '{row2[contentFull]}', bigimages: '{$row3['catalogFileID']}'}]
HERE_DOC;
In my main page I have the following jQuery code:
jQuery(function()
{
jQuery("select#rooms").change(function()
{
var options = '';
jQuery.getJSON("/admin/selection_about.php",{id:jQuery(this).val(),
ajax:isAjax}, function(j)
{
for (var i = 0; i < j.length; i++)
{
options = j[i].topImage;
document.getElementById('content1').value = j[i].bigimages;
}
})
})
})
So basically in my main page, I have a drop down. When an option is selected, it fires off an Ajax request back to the server. I get the data in JSON format and then a textarea, with ID 'content1', is updated based on that JSON object.
The JSON object looks like this:
[
{
content: '<SPAN STYLE= "" >"
this is some text"
blah blah, "
some more `text"
now some linebreaks;
<BR><BR>some more text and then another` linebreak.`<BR>`</SPAN>',
bigimages: 'cfil1069'
}
]`
But there are errors that occur here and my textarea does not get updated. However, if I hardcode plain simple text to be returned in the JSON object, then my textarea is updated.
Is there a condition for which data in the JSON object should not have HTML tags?
Edit:
As suggested, I changed my code to following in PHP code:
$arr = array ('content'=>$rest1,'bigimages'=>$row3['catalogFileID']);
echo json_encode($arr);
However now in my jQuery code:
length of j is 'undefined' ...
jQuery.getJSON("/admin/selection_about.php",{id: jQuery(this).val(),
ajax: isAjax}, function(j)
{
alert('here3: ' + j.length); // this shows undefined
for (var i = 0; i < j.length; i++)
{
document.getElementById('content1').value = j[i].content;
}
})
Upvotes: 1
Views: 556
Reputation: 43619
Put your content into a PHP array. Then convert it to JSON using json_encode()
.
That will safely encode and escape the characters, for example double quotes in your HTML attribute.
UPDATE:
The reason why j.length
does not work is because:
An PHP array with keys are not Javascript arrays. Javascript arrays have no keys. Thus when converted, the PHP array is converted into a JS object.
Instead to access your JS object, you can use j.content
, instead of looping through the object with j.length
. j.length
is undefined because there is no property in the object j
with the property name length
(that is because in your PHP array, there is no $arr['length']
)
Upvotes: 1