Search code examples
htmlajaxcodeignitercodeigniter-4

Ajax is not working in codeigniter 4 when call the controller


I just want to make sure this ajax is working to call my controller. But when i click the button nothing happened. Thank you

My view :

<input type="text" id="phonenumber" name="phonenumber" class="form-control" placeholder="Phone number">
<button type="button" id="sendotp" name="sendotp" class="btn btn-primary btn-block">Sign Up</button>

My AJAX :

$(document).ready(function() {
  $('#sendotp').click(function(e) {
    e.preventDefault();

          var phonenumber = $("input[name='phonenumber']").val();

          $.ajax({
                url: '<?php echo base_url();?>/register',
                type:'post',
              dataType:'json',
                data: {
                  phonenumber:phonenumber
                },
                success: function(data) {
                }
            });
  });   
});

My Controller :

public function register()
    {   
        if($this->request->getMethod() == 'post'){

            $phonenumber = $this->request->getPost('phonenumber');
            echo $phonenumber;
        }
        return view('register/register');
    }

My Routes :

$routes->match(['get', 'post'],'/register', 'Home::register');

Solution

  • In your javascript you have you success event empty. So nothing happening is the expected behavior. If you're returning a view in your controller, you must do something with it in your javascript.