Falcata
Falcata

Reputation: 707

JSON object "undefined" error in Javascript

I am uploading a file using PHP and want to return the file name and the file status to javascript. In PHP I create the json object by:

$value = array('result' => $result, 'fileName' => $_FILES['myfile']['name']);   
print_r ($value);
$uploadData = json_encode($value);

This creates the json object. I then send it to a function in javascript and recieve it as a variable called fileStatus.

alert (fileStatus);

It displays

{"result":"success","fileName":"cake"}

which should be good. But when I try and do

fileStatus.result or fileStatus.fileName 

I get an error saying that they are undefined. Please help I'm really stuck on this. Thanks.

Upvotes: 3

Views: 3821

Answers (3)

gen_Eric
gen_Eric

Reputation: 227260

When you are setting the variable, do not put quotes around it. Just set the variable like this:

var fileStatus = <?php echo $uploadData; ?>;

or:

var fileStatus = <?=$uploadData?>;

Do not do this:

var fileStatus = '<?php echo $uploadData; ?>';

Upvotes: 1

Chris Shouts
Chris Shouts

Reputation: 5427

The fileStatus is just a string at this point, so it does not have properties such as result and fileName. You need to parse the string into a JSON object, using a method such as Firefox's native JSON.parse or jQuery's jQuery.parseJSON.

Example:

var fileStatusObj = jQuery.parseJSON(fileStatus);

Upvotes: 3

Dan
Dan

Reputation: 1888

If the alert displays {"result":"success","fileName":"cake"} then you probably still have to turn the string into a JSON object. Depending on the browsers you are developing for you can use the native JSON support or the JSON.org implementation to turn your string into an object. From there on it should work as expected.

Upvotes: 2

Related Questions