-1

I wrote an AJAX request for uploading a file and add it's details to MySql database (by a form).

The code works great, but breaks when I add preventDefault() to the submit event (to not be directed to the external PHP file).

 $("#upload-form").submit(function(event){

            // TODO: check why breaks PHP code
            // event.preventDefault();

The same structure works great with other AJAX requests on the same file (for example AJAX request for editing MySql database).

I know the AJAX request is submitted because a new folder is created on my server (as part of the PHP code) but the file isn't uploaded.

I will be happy for an answer for one of these questions:

  1. What preventDefault() doe's that can interfere otherwise working AJAX request?
  2. How can I debug the external PHP code? as I'm not directed to it (because of the preventDefault())?

If my question is not clear enough - please help me make it clearer.

Asaf Moshe
  • 41
  • 5
  • Are you trying to upload a file with ajax? `event.preventDefault()` will stop the form from submitting so I am guessing you are sending form data with ajax. – Ozan Aug 11 '16 at 15:54
  • We need to see more code. If `preventDefault()` is supposedly stopping your ajax requests, how are you supposed to view them? – Blue Aug 11 '16 at 15:54
  • can you set the target of the form to the name a hidden iframe? I believe that is how many other sites have accomplished asynchronous file uploads (e.g. gmail) – Sᴀᴍ Onᴇᴌᴀ Aug 11 '16 at 16:00
  • @Aelliott1485, that works, but that is an ancient method that is no longer preferred. Using ajax to upload files is much more cleaner. – Ozan Aug 11 '16 at 16:02

2 Answers2

-1

Since you are calling event.preventDefault() I am assuming you are sending form data with ajax.

If you want to upload files with ajax, you need to set processData: false and contentType: false on your ajax request.

See jQuery Ajax File Upload.

Graham
  • 7,431
  • 18
  • 59
  • 84
Ozan
  • 3,709
  • 2
  • 18
  • 23
  • So i'm using this method :http://www.w3schools.com/php/php_file_upload.asp. Which means I use the $_FILES variable to retrive files - on the server side, instead of the .files method on the client side. Is it valid? It works without preventDefault(), can I adjust it to work with it? – Asaf Moshe Aug 11 '16 at 17:14
  • The client side files and server side $_FILES are two completely different things. If you upload the files properly on the Ajax side you will be able to access them from the server side as you would on a normal form submit. – Ozan Aug 11 '16 at 17:55
-1

So I think I got my answer.

I'm using this method: http://www.w3schools.com/php/php_file_upload.asp, which apparently doesn't work with preventDefault: https://stackoverflow.com/a/19217726/6617991.

I will try to switch to the method Ozan sugested: jQuery Ajax File Upload

Hope I got it right.

Graham
  • 7,431
  • 18
  • 59
  • 84
Asaf Moshe
  • 41
  • 5