Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload a file using a simple jquery-ajax call

I am searching for a simple client-side script to upload a file using ajax. Searching for the web for this script only brought up a lot of plugins with multi-features. I don't need multi-feautres - just to be able to upload it as simple as possible using ajax

Is it possible to write something simple as:

$.get('server/upload.php?file = ' + $('#uploadInput').val(), function(data) {
   $('.result').html(data);    
 });

If it is possible - how should I write it right ($('#uploadInput').val() won't give me the right directory path - so what do I need to do to pass the location using Ajax).

aside from that - in order to get drag&drop for files - Is there a simple script for that or do I need to use plugin (and is there a really tiny and simple one without multi-features)

like image 801
Alon Avatar asked Jan 17 '23 08:01

Alon


2 Answers

You can't use AJAX to upload files (unless the clients browsers supports the HTML 5 element, which allows access to the file object.).

Your solution is to fake it

create a form element

<form id="myForm" action="upload.php" method="POST" target="results_frame">
  <input name="fileUpload" type="file" />
  <input type="submit" value="Submit" />
</form>

We set the target of the frame for 'results_frame', we'll define it after the form in the HTML as an empty iframe.

<iframe id="results_frame" name="results_frame" style="display:none;"></iframe>

Then, in the backend in your php file you can capture the file as -

$_FILE['file']['param']; //where param accepts multiple values
//such as name, type, size, error, and tmp_name

Once you've done your manipulating with the file, you can make an echo whatever information you want, including refreshing the initial form at this point.

like image 74
Ohgodwhy Avatar answered Jan 19 '23 23:01

Ohgodwhy


You could achieve this using some HTML5 features such as the File API (take a look at the Example: Uploading a user-selected file section in this article).

But if you want cross browser solution I would recommend you using a client side upload plugin. For example the jQuery form plugin is quite easy to setup. Valums Ajax upload is also very nice. It provides many functionalities such as drag and drop and upload progress but if you don't care about them, they can be easily turned off.

like image 34
Darin Dimitrov Avatar answered Jan 19 '23 23:01

Darin Dimitrov