0

I am creating an application to upload image along with its path and have separate path for each image

data:  {name:"niks",age:"22",path:"small/data",image:new FormData(this)}

and to i want to receive data and image in php code too.

Logically i have written this code,What is the right code plz help me.

HTML Form code is

<form id="replaceimg" enctype="multipart/form-data" method="post">
<input name="fileimg" type="file" id="fileimg"  required />
<input type="submit" value="Upload Image" name="submit" />
</form>

mycode is:

$("#replaceimg").on('submit',(function(e) {
    e.preventDefault();

    $.ajax({
        url: "upload.php",      // Url to which the request is send
        type: "POST",                   // Type of request to be send, called as method
        data:  {name:"niks",age:"22",path:"small/data",image:new FormData(this)},       // Data sent to server, a set of key/value pairs representing form fields and values
        contentType: false,             // The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
        cache: false,                   // To unable request pages to be cached
        processData:false,              // To send DOMDocument or non processed data file it is set to false (i.e. data should not be in the form of string)
        success: function(data)         // A function to be called if request succeeds
        {

            console.log("data is "+data);
        }
    });
    alert("In Submit replaceimg");
}));
Nikhilesh Patve
  • 1,760
  • 3
  • 13
  • 31

2 Answers2

1

You have to pass the FormData object as the data parameter. jQuery AJAX 'multipart/form-data' Not Sending Data?

But alternatively, you may upload base64 string if the image is not that big.

Community
  • 1
  • 1
vilicvane
  • 11,625
  • 3
  • 22
  • 27
1

Try this:

var uploadFile = $('.nameOfInputClass') // <- Change the class.

var data = {};

data.name = 'Niks';
data.age = 22; // Should be a Number, not a string.
data.path = 'small/data';
data.image = new FormData();

data['image'].append('upload', uploadFile[0]);

Them:

$("#replaceimg").on('submit',(function(e) {
    e.preventDefault();

    $.ajax({
        url: "upload.php",      // Url to which the request is send
        type: "POST",                   // Type of request to be send, called as method
        data:  data,
        contentType: false,             // The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
        cache: false,                   // To unable request pages to be cached
        processData:false,              // To send DOMDocument or non processed data file it is set to false (i.e. data should not be in the form of string)
        success: function(data)         // A function to be called if request succeeds
        {

            console.log("data is "+data);
        }
    });
    alert("In Submit replaceimg");
}));