3

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.

5
  • 4
    fileStatus is probably the JSON string containing {"result":"success","fileName":"cake"}. Commented Aug 2, 2011 at 18:31
  • 2
    Can you show the code where you set fileStatus? Commented Aug 2, 2011 at 18:31
  • Guess you got some scoping problems, can you show the actual code? Commented Aug 2, 2011 at 18:32
  • Are you correctly setting the document type? stackoverflow.com/questions/267546/… Commented Aug 2, 2011 at 18:33
  • Gumbo is correct. fileStatus is the JSON string. function stopUpload(fileStatus){ Commented Aug 2, 2011 at 18:34

3 Answers 3

3

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);
Sign up to request clarification or add additional context in comments.

Comments

2

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.

2 Comments

Alternatively, you could use the evil eval function.
You could, but you shouldn't want to. :)
1

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; ?>';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.