0

I want to know if is possible to call a PHP script passing params and uploading an image via POST at same time using AJAX

Imagine this form

Insert a title <input id="title" style="width:300px"></input> 
Attach an image <input id="immagine" type="file" name="immy" accept="image/*" size="40"/>

The title is easly transmittable writing

var ajaxReq = new XMLHttpRequest();

var params = "titolo="+$('#title').val()
var url = "registraDati.php";

ajaxReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxReq.setRequestHeader("Content-length", params.length);
ajaxReq.setRequestHeader("Connection", "close"); 

ajaxReq.send(params)  

While for the image is necessary use the FormData. Something like this (note that it don't works actually):

 var file_data = $("#immagine").files[0];    //<----PROBLEM HERE!!
 var form_data = new FormData();                  
 form_data.append("afile", file_data)             
 form_data.append("user_id", 123)                 

 var xhr = new XMLHttpRequest();
 xhr.open('POST', 'uploadImmagine.php', true);
 xhr.send(form_data);

Can i achieve both operations with one move?

Sonia
  • 253
  • 1
  • 3
  • 16
  • You forgot to describe the problem. "Does not work" is not a good description. – lqc Apr 28 '13 at 11:47
  • Just curious: why are you not using jQuery for ajax call? – rciovati Apr 28 '13 at 11:49
  • jQuery objects don't directly access the `FileList` of an input. To access the file you'd want to be sure that `#immagine` is the input (and not the form itself), and do something like: `$("#immagine").eq(0).files[0]`. – numbers1311407 Apr 28 '13 at 15:46
  • @rciovati: it isn't good to use jquery? Anyway i've to use it for other operations in the same page, for this reason i want to use it for all. – Sonia Apr 28 '13 at 20:24
  • @numbers1311407: i will try your script.. So var file_data=.eq(0).files[0]... The rest of script is ok? – Sonia Apr 28 '13 at 20:26
  • @lqc: the error is something like "the method files doesn't exists" – Sonia Apr 28 '13 at 20:27
  • @AnnaLica The rest seems fine. In regards to jQuery you could go ahead and send the data with `$.ajax` rather than your own xhr, but there are [a few options you must set](http://stackoverflow.com/questions/6974684/how-to-send-formdata-objects-with-ajax-requests-in-jquery) – numbers1311407 Apr 28 '13 at 20:56

0 Answers0