0

I am using CodeIgniter. I am trying to upload the image using AJAX after jquery validation but it's not working. Jquery validation is working in case field is empty. After filling all the fields and clicked on submit button then my page refreshed. It's not calling the controller.

Would you help me out?

$("#primary").validate({
    errorElement: 'div',
    rules: {
        first_name: {
            required: true,
            alphabets: true,
            minlength: 3
        },
        last_name: {
            alphabets: true            
        },
        profile_pic: {
            extension: "png|jpeg|jpg|gif"                      
        },
    },

    messages: {
        profile_pic: {
            extension: "Only PNG , JPEG , JPG, GIF File Allowed",
        },  
    },

    submitHandler: function(form)
    {
      var formData = new FormData(this);

            $.ajax({
                url: baseUrl + "/AddMember/addMembers",
                type: 'POST',
                //data: $('#primary').serialize(),
                data:formData,
                dataType: 'json',
                success: function(data) 
         {                  
            if (data.error == "true")
            {           
             //success message
            } 
          else {
               //error message
               }
          }

            });
    }

});

Controller code

    $config=['upload_path'   =>'./uploads/images',
             'allowed_types' =>'gif|jpg|png|jpeg',
             'file_name'     =>uniqid().time().date("dmy")
             ]; 
            if ($this->upload->do_upload('profile_pic'))
            {
            $profile_pic_set = $this->upload->data('file_name');
            }
            else{$profile_pic_set = "";//set empty value if user not uploading any image
 }
                $this->load->library('upload', $config);
                $data = array(
                  'first_name'  =>  trim($this->input->post('first_name')),
                  'last_name'   =>  trim($this->input->post('last_name')),
                  'profile_pic' =>  $profile_pic_set
                   );   
                    print_r($data); //here I am getting profile_pic empty.

html

    <?php echo form_open_multipart('','id="primary"'); ?>
              <input type="text" name="first_name" id="first_name" class="form-control"  placeholder="First Name">
              <input type="text" name="last_name" id="last_name" class="form-control"  placeholder="Last Name">
<input type="file" name="profile_pic" id="file_upload">
              <button type="submit" class="btn btn-primary btn_new">Submit</button>
              <?php echo form_close(); ?>
Sparky
  • 98,165
  • 25
  • 199
  • 285
user9437856
  • 2,360
  • 2
  • 33
  • 92
  • There are no such rules in the jQuery Validate plugin called `filesize` or `alphabets`. If these are custom rules, then you should let us know and show the code. – Sparky Aug 27 '18 at 15:41
  • Oh!. Sorry for my bad. I will remove it – user9437856 Aug 27 '18 at 15:42
  • If the page is refreshing then your JavaScript is likely not working due to an error. Check your browser's JavaScript console for errors. Check the setting that saves console error messages between screen refreshes. – Sparky Aug 27 '18 at 15:43
  • You have not shown enough code to reproduce anything. You tagged the question with `HTML5` but it has nothing to do with HTML. Where is the relevant HTML markup of the form? For uploading files, you need `enctype="multipart/form-data"` attribute on the `form`. – Sparky Aug 27 '18 at 15:45
  • @Sparky, Yes that's correct,I am using enctype="multipart/form-data" in my form tag. I am getting the error TypeError: Argument 1 of FormData.constructor does not implement interface HTMLFormElement.[Learn More] I am getting the error in var formData = new FormData(this); this line – user9437856 Aug 27 '18 at 15:48
  • Your problem is inside `FormData(this)`. The `this` is the validator itself, not the form object. The form object is the `form` argument that is passed into the `submitHandler`. – Sparky Aug 27 '18 at 15:52
  • Should be `FormData(form)`. See answer here: https://stackoverflow.com/q/35322901/594235 – Sparky Aug 27 '18 at 15:54
  • @Sparky, Yes, before I tried form but I was getting an error in console TypeError: 'append' called on an object that does not implement interface FormData.[Learn More] – user9437856 Aug 27 '18 at 15:57
  • So why not google that instead? https://stackoverflow.com/a/25390646/594235 – Sparky Aug 27 '18 at 16:05

1 Answers1

2

TypeError: Argument 1 of FormData.constructor does not implement interface HTMLFormElement

Your problem is inside FormData(this). The this represents the validator itself, not the form object. The form object is represented by the form argument that is passed into the submitHandler.

So FormData() should contain the form argument.

Also, need to set the Ajax processData and contentType parameters to false...

submitHandler: function(form){
    var formData = new FormData(form);
    $.ajax({
        url: baseUrl + "/AddMember/addMembers",
        type: 'POST',
        data: formData, 
        dataType: 'json',
        processData: false,
        contentType: false,
        ....

References:

Send image with ajax , using jquery validator on submitHandler

TypeError: 'append' called on an object that does not implement interface FormData

Solution: https://stackoverflow.com/a/25390646/594235

Sparky
  • 98,165
  • 25
  • 199
  • 285