I'm an iPhone Developer whose quite new to web development so please forgive me if I'm making silly mistakes here:
What I'm trying to accomplish is when the user selects an item from a drop-down, it calls some javascript, which sets off an AJAX request to a PHP file I have which returns some JSON. - That JSON includes a thumbnail image filename, and a caption for the image. These need to be passed in to an image, and textfield respectively in my document.
The problem is, it fails after trying to eval the json. - The same happens with eval(json);
and JSON.parse(json);
I worked this out by calling document.write('something'); periodically in my response method. - It will always be able to write up to the point where it parses the json.
I am sure my PHP is valid and my request is good (I can output the response from the JS fine).
Here is the function I call when a new item is selected in the drop-down:
function changeImage(id){
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var res=xmlhttp.responseText;
var responseObject = eval(res);
var caption = responseObject.caption;
var textField = document.getElementById('caption');
textField.value = caption;
var imagePreview = document.getElementById('imgPreview');
imagePreview.src = responseObject.filename;
}
}
xmlhttp.open("GET","getCaption.php?id="+id,true);
xmlhttp.send();
}
When I output res (or access the php file manually) the JSON looks like this:
{"caption":"A caption","filename":"myimage_thumb.jpg"}
why is the JSON eval failing?
UPDATE:
This error is logged: SyntaxError: Parse error