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"); })); 
2
  • what is this in the context? Commented Jan 25, 2015 at 16:49
  • @MrBearAndBeer what do you think it is or isn't? You only bind submit to a form Commented Jan 25, 2015 at 16:53

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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"); })); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.