Skip to content Skip to sidebar Skip to footer

Upload Image Using Ajax And Form Submitting

I want to upload an image to the server using Ajax, but there is a problem. Would somebody please help me what is wrong here. I could submit the image using submit form but not aja

Solution 1:

The first thing I notice is that you're missing a comma after the data parameter declaration. That might be your only issue.

$.ajax({
    url: 'url',
    data: data,
    enctype: 'multipart/form-data',
    //etc...

Solution 2:

What's the name of your PHP script? That's what you should specify as 'url':

url:'script_name.php',

Solution 3:

Maybe this plugin could help you

Jquery Form

I had a lot of problem making from myself and with this plugin everething works, just try, this

$('form').ajaxForm(function() { 
    alert("Thank you for your comment!"); 
}); 

Solution 4:

I would guess that without using preventDefault() method in your script, you submit the form to the same page using action="" and method="post", thus never entering your $.ajax();

I've done something like this

$('#query_projects').submit(function(event){
    event.preventDefault();
    var formData = newFormData($(this)[0]);            

    var request = $.ajax({
        type: 'POST',
        url: 'query_tab_projets.php',
        mimeType:'application/json',
        dataType:'json',
        data: formData,
        contentType: false,
        processData: false,
        success: function(data){                            
            alert(JSON.stringify(data,null,4));
        },
        error: function(msg){
            alert(JSON.stringify(msg,null,4));
        }
    });             
});

where #query_projects is my form id

Solution 5:

Finally I found where the problem is. Maybe it is useful for others struggling with ajax uploading a file.Now it is working perfectly. The solution is:

In the php code, all the ["avatar"] should be replaced with ["file"] as we are sending the file specified as file in ajax.

Post a Comment for "Upload Image Using Ajax And Form Submitting"