James Rodrigues
James Rodrigues

Reputation: 107

Upload file by ajax to the server

I'm trying to upload image to the server by this simple code:

 <form enctype="multipart/form-data">
    <input name="file" type="file" />
    <input type="button" value="Upload" />
</form>
<progress></progress>

<script>
$(':button').click(function(){
    var formData = new FormData($('form')[0]);
    $.ajax({
        url: 'http://cs418417.vkontakte.ru//upload.php?act=do_add&mid=219171498&aid=179524586&gid=0&hash=154ebcc2f733f318a20b77e296f285c5&rhash=e7df1f0c685b918ffa58ff10937dc7cd&swfupload=1&api=1',  //Server script to process data
        type: 'POST',
        dataType: "jsonp",
        xhr: function() {  
            var myXhr = $.ajaxSettings.xhr();
            if(myXhr.upload){ 
                myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
            }
            return myXhr;
        },
        data: formData,
        cache: false,
        contentType: false,
        processData: false
    });
});
function progressHandlingFunction(e){
    if(e.lengthComputable){
        $('progress').attr({value:e.loaded,max:e.total});
    }
}
</script>

This code doesn't work. Console shows me error like that: enter image description here

Where is the problem? Thanks in advance and sorry for my English!

Upvotes: 0

Views: 140

Answers (1)

Derek 朕會功夫
Derek 朕會功夫

Reputation: 94309

The server is returning with a JSON string, but your code chose to receive it as JSONP. Executing a JSON string will cause that error.

enter image description here

Upvotes: 1

Related Questions