ElPiter
ElPiter

Reputation: 4324

Upload file using jQuery and Ajax

I have a form that I am sending to the server using jQuery $.post method. I am sending several fields with something like:

var myName = "Pedro";
var myDescription = "Description of Pedro";

$.post("~/insert_user", { name: myName, description: myDescription }, function(data){
    alert("Successfully inserted " + data.name + " in DB");
}, "json");

This works great, as I take the values in insert_user.php and treat and insert the in the data base.

What if I need to add a field to my form to let the user upload an image?

How would I do that in my $.post call and how would I get it in the PHP?

I am using Symfony2.0, by the way, just in case it changes something. But the important part is how to add a file typed field to the ajax call.

Thanks in advance.

Pedro

Upvotes: 0

Views: 1449

Answers (4)

ElPiter
ElPiter

Reputation: 4324

I finally used this:

http://malsup.com/jquery/form/#faq

It just works great for what I need.

Thank you guys for your help.

Upvotes: 0

Ryan
Ryan

Reputation: 1119

You will find it would be a lot easier to use a pre built jquery plugin. My favourite is uploadify http://uploadify.com.

Its simple and easy to use and it will save you a lot of time trying to figure out a method of your own <>

$.post is the same as the code block bellow. In order for you to do what you need to you need to change it to use this atleast and then things will become simpler. So start by changing the $.post to this

$.ajax({
  type: 'POST',
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

Then add a parameter in the ajax block contentType : "multipart/form-data" or try mimeType (cant remember so clearly) and in the data : $("#form").serialize(), that should work.

please tell me if it didn't work

--NEW EDIT LOL-- Excuse my blind coding, you may need to test this

I did a bit more research and came across this. You need to build this array and add it to the data in your ajax block

var files = new FormData($('#fileinputid'));     
jQuery.each($('#fileinputid')[0].files, function(i, file) {
    files.append(i, file);
});

If what i read was accurate you should be able to pass that array with the rest of the ajax data. Although i am not completely sure how to add it to the serialized data.

Please test this and let me know. if it doesn't work ill do a full javascript script test for you and then post it here

Upvotes: 1

S3Mi
S3Mi

Reputation: 488

Make iframe and put form in it, submit the form and voila. Or you can use one of these AJAX File upload scripts

Upvotes: 0

Zerium
Zerium

Reputation: 17333

This tutorial might help: Nettuts+: Uploading Files With AJAX

Upvotes: 0

Related Questions