Json data return invalid label error

I am using Ajax file upload using javascript / jQuery .

While downloading the file, I keep getting this error message: SyntaxError: invalid label

This is my JS script:

  jQuery('.uploadImage').live('click',function() { ajaxFileUpload(); }); (...) function ajaxFileUpload(){ jQuery.ajaxFileUpload({ url:'../wp-content/plugins/wp-filebrowser/uploader.php', secureuri:false, fileElementId:'uploadFile', dataType: 'json', success: function (data, status){ if(typeof(data.error) != 'undefined'){ if(data.error != ''){ alert(data.error); }else{ alert(data.msg); } } }, error: function (data, status, e){ alert(data + ' - ' + status + ' - ' + e); } } ) return false; } 

My PHP script works (checked before using json / jquery), but there should be something wrong with my json output from my PHP file. I tried two approaches.

I use json_encode to format the output. This is part of my PHP code:

  (...) // Error message is at this stage empty. move_uploaded_file($_FILES["file"]["tmp_name"], $uploadfile); $respons = $_FILES["file"]["name"]._e(' successfully uploaded'); $data = array( "error"=> $error, "msg"=> $respons ); echo json_encode($data); 

UPDATE
Turns out I used Worpdress _e() to support multilingualism. The problem is that _e() echoes the content and therefore drowns out the JSON response. When I switched to __() , it worked.

Thank you for helping mebearbore to these guys.

+4
source share
2 answers

The first approach does not give valid JSON. Take a look at the output of the json_encode() function, which generates it correctly. The main problem is that keys and values ​​are not enclosed in double quotes.

Have you tried using firebug to determine the exact source of the error? Each JSON key must be a string. This obviously does not apply to your faulty line.

+2
source

json tags must be enclosed in quotation marks:

 "'error':" . $error . "'\n"; 

etc. In addition, if $error contains any quotation marks / colons, this will also break the syntax. You are basically wide open for the JSON equivalent of SQL injection with what you are doing. You better not create JSON strings yourself and just use json_encode() for regular PHP arrays / objects. If you somehow save the output of both versions ( error_log() ?), You can pass them through http://jsonlint.com/ to see what is wrong with them ..

-1
source

All Articles