How to send a file to php via jQuery?

I am trying to send a file through jQuery to a PHP file for processing.

<form action="help-uploader.php" method="POST" class="signup" id="upform" enctype="multipart/form-data">

   <input type="text" id="title" name="title" tabindex="1" value="">
   <input id="file" type='file'" />
   <button class="submitbtn" id="submit">submit</button>
</form>

and jQuery:

$(document).ready(function(){
        $('#submit').click(function (e) {
        // custom handling here
            e.preventDefault();
            var ititle = $("#title").val();
            var ifile = $("#file").val();

            $.post("help-uploader.php",
                {
                    title: ititle,
                    file: ifile
                },function(data, status){alert("Data: " + data + "\nStatus: " + status);});
        });
    });

and **help-uploader.php**

<?php
echo $_POST['file'];
echo basename($_FILES["file"]["name"]);
?>

ECHO first prints the file path on the client.

The second ECHO does not print anything.

How can I send a file to PHP via jQuery correctly?

+4
source share
2 answers

You need to use formdata. I provide an example of a function that takes arguments, such as refrence, and a callback function to execute stuff. This function binds an event in your submit form. Try below

function sendAjaxForm(frm,callbackbefore,callbackdone)
    {
        var form = frm;
        form.submit(function(event){
            event.preventDefault();
            var formData = new FormData(this);
            var ajaxReq=$.ajax({
                url: $(this).attr('action'),
                type: $(this).attr('method'),
                data: formData,
                async: false,
                cache: false,
                contentType: false,
                processData: false,
                beforeSend: callbackbefore
                });
            ajaxReq.done(callbackdone);
        }); // submit done
    }

Now call this function as in your example

sendAjaxForm($('#upform'),function(){alert('sending');},function(data){alert("Data: " + data);})
+3
source

FormData() xmlhttprequest. $.post() ajax, xmlhttprequest, $.ajax() js xmlhttprequest.

jQuery, submit:

$(document).ready(function(){
    $('#upform').submit(function(e){
      e.preventDefault();
      var fd = new FormData(document.querySelector(this));
      $.ajax({
         url: "help-uploader.php",
         type: "POST",
         data: fd,
         cache:false, // do not cache 
         processData: false,  // required
         contentType: false   // required
         success:function(data){
           console.log(data);
         },
         error:function(err){
           console.log(err);
         }
     });
   });
});
+1

Source: https://habr.com/ru/post/1609246/


All Articles