Gusti Erlangga
Gusti Erlangga

Reputation: 69

how to upload file in codeigniter using ajax, the error in ajax

I would like to upload pdf by codeigniter using ajax, on my form I added an attribute enctype="multipart/form-data" I'm sure that the error is in ajax script :

$("#form").submit(function(){
        $.ajax({
            type:"POST",
            url: base_url+"car/save_car",
            data:$(this).serialize(),
            dataType:"json",
            beforeSend:function()
            {
                $("#loading-box").show();
                $("#btn-save").addClass("disabled");
                //$("#btn-save").prop("disabled", true);
            },
            success: function(res)
            {
                $("#loading-box").hide();
                var msg="";
                if(res.error)
                {
                    $("#btn-save").addClass("disabled");
                    msg =\'<span class="callout callout-danger"><i class="icon fa fa-warning"></i> \'+res.message+\'</span>\';
                }
                else
                {
                    msg =\'<span class="callout callout-success"><i class="icon fa fa-check"></i> \'+res.message+\'</span>\';
                    setInterval(function(){window.location=\''.base_url('car').'\'},1500);
                }

        });            
        return false;
    });

Upvotes: 0

Views: 40

Answers (1)

Owais Aslam
Owais Aslam

Reputation: 1589

Use formData to send your data including your file in your submit function

formData = new FormData();
  if($(this).prop('files').length > 0)
   {
    file =$(this).prop('files')[0];
    formData.append("yourFileName", file);
   }

And in your ajax send formData.

data: formData,

You can see the reference here

Upvotes: 1

Related Questions