Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html form enctype on ajax

Tags:

html

jquery

ajax

i have this jquery code that submits my form data:

<script type="text/javascript">
$(document).ready(function(){
$("#message").hide();
$("#please_wait_box").hide();
$("#viewreseller").submit(function(e){
    e.preventDefault();
    dataString=$("#viewreseller").serialize();
    $.ajax({
        type: "POST",
        url: "view_reseller-go.php",
        cache: false,
        data: dataString,
        success: function(res){
            //$("#message").show();
            $("#please_wait_box").hide();
            $("#message").html(res);
            $('#message').fadeIn('slow');
            if(res.indexOf("success")!=-1)
            {
                window.location.href = res.substr(8);
            }
        }
    });
});
});
</script>

i need to set the enctype on the form to multipart/form-data - is this possible with my above code?

like image 816
charlie Avatar asked Oct 02 '22 22:10

charlie


1 Answers

Since you are using Ajax to submit the form data, setting the enctype will have no effect. You are completely bypassing the form submission process that would use it.

So, let's ask if you can adapt that code to have the same effect as setting the enctype. The attribute has three effects on a form submission.

  1. It sets the content-type of the HTTP post request. You can do this easily. headers: { "Content-Type": "multipart/form-data" }
  2. It encodes the data in the form using multipart/form-data instead of application/x-www-form-urlencoded" - serialize will never do this
  3. It will include files from file inputs - serialize will never do this

jQuery has nothing built in to handle file uploads via Ajax. MDN has a pretty detailed description of the process for using built in browser APIs (note that you need a modern browser to support some of those APIs).

Since you are using jQuery, you should probably look at using a pre-written library which supports Ajax file uploads. There are plenty of them available, but I can't recommend a specific one.

like image 122
Quentin Avatar answered Oct 16 '22 23:10

Quentin