I am trying to upload a picture to uploads.im which then sends back it's URL (and other info). The ajax post to the api is successful but I can't post the response to another file (saveImgURL.php) which would then get the URL from the sent 'data' variable and save it in the database.
HTML:
<form id="postfile" method="POST" action="http://uploads.im/api?upload" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="SEND FILE">
</form>
<div id="result"></div>
Correct API response:
({"status_code":200,"status_txt":"OK","data":{"img_name":"abcde.png","img_url":"http:\/\/s1.uploads.im\/abcde.png","img_view":"http:\/\/uploads.im\/abcde.png","img_width":167,"img_height":288,"img_attr":"width=\"167\" height=\"288\"","img_size":"36.1 KB","img_bytes":37002,"thumb_url":"http:\/\/s1.uploads.im\/t\/abcde.png","thumb_width":100,"thumb_height":90,"source":"http:\/\/www.google.com\/images\/srpr\/nav_logo66.png","resized":"0"}});
jQuery:
$( "#postfile" ).submit(function( event ) {
var data1;
var formObj = $(this);
var formURL = formObj.attr("action");
var formData = new FormData(this);
$.ajax({
url: formURL,
type: 'POST',
data: formData,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
success: function(data, textStatus, jqXHR)
{
//document.write(data); // displays the correct API response in current doc
$.post( "saveImgURL.php", { 'data': data } ); //DOES NOT WORK
},
error: function(jqXHR, textStatus, errorThrown)
{
}
})
event.preventDefault();
});
The response you are getting is a JSON string.
Most likely you need to parse the returned data to a JSON object sometimes in the process, depending on how your PHP script (saveImgURL.php) will handle the data.
Either parse it before sending it:
var json = JSON.parse(data);
$.post( "saveImgURL.php", { 'data': json } );
or keep it as is but be aware you are sending a string, and parse it in the PHP script using:
$json_data = json_decode($_POST['data'], true)
;
I am assuming, of course, that 'saveImgURL.php' is in the same folder as your original file, otherwise the $.post will obviously fail.
Also - it seems as the string itself contains 3 invalid characters at the begining and end, which will cause you problems parsing it - the '(' and ')' and ';'; You can use a 3rd party website like jsonvalidatoronline.org to validate the response.
Hope this helps!