0

I'm trying to get the value of textbox that has been submitted through ajax, but when i try to get its value inside controller method it return nothing.

Here is my AJAX function and controller method:

  jQuery("#frm_xyz").validate({
      rules: {
          otp: {
              required: true
          },
      ....
      ....
      submitHandler: function(form,event) {
          event.preventDefault();
          var from_url=jQuery(form).attr('action');
          jQuery.ajax({
              url: from_url, 
              type: "POST",             
              data: new FormData(document.getElementById("frm_xyz")),
              cache: false,             
              processData: false,      
              success: function(data) {
              }
          });
      }
  });

HTML:

 <?php echo form_open('verify-verification-otp',array('id'=>"frm_xyz")); ?> 
     <input type="text" name="otp" placeholder="OTP" class="form-control" />
     <br />  
     <input type="submit" name="submit" id="btn_verify_contact" class="btn btn-info" value="Verify OTP" />  
 <?php echo form_close(); ?>

but when i try to get value of textbox in controller i don't get the value!

PHP:

public function verify_otp()
{
    $otp = $this->input->post('otp');
    print_r($otp);
    die();
}
turivishal
  • 34,368
  • 7
  • 36
  • 59
user3653474
  • 3,393
  • 6
  • 49
  • 135
  • You have to pass form serialize data in your ajax post data like `data: form.serialize()`. Please structure your code properly.. – turivishal Jun 04 '20 at 05:38
  • after this line - `var from_url=jQuery(form).attr('action');`, please print `from_url` what's value in it. I think it is blank because you didn't define it. – Alok Mali Jun 04 '20 at 05:50
  • Also on submit, you can check the network tab if dev tools. It will show you the URL where the request is submitting with the value of inputs. – Alok Mali Jun 04 '20 at 05:52

1 Answers1

0

This could be due to a number of reasons -

  1. Set the form method to POST -

    <?php 
       echo form_open('verify-verification-otp',array('id'=>"frm_xyz", 'method'=>"POST"));
    ?>
    
  2. Set contentType to false while sending formData or jquery default will overwrite it. Reference

     jQuery.ajax({
            url: from_url,
            type: "POST",
            data: new FormData(document.getElementById("frm_xyz")),
            cache: false,
            processData: false,
            contentType: false, 
            success: function(data) {
                     }
        })
    
  3. You don't need formData as you are not sending any file, just use serialize and you should be good to go. Reference

    jQuery.ajax({
        url: from_url,
        type: "POST",
        data: $('#frm_xyz').serialize(),
        cache: false,
        dataType: 'JSON',
        success: function(data) {
                 }
    })
    

See if it helps you.

sauhardnc
  • 1,961
  • 2
  • 6
  • 16