phpjquerycodeigniter

Calling REST API from controller codeigniter


I am new to code igniter and for my project I have to create a REST API.

I have a working REST API.

What is the correct way to call the API from ajax calls?

View -> Controller -> REST

or

View ->REST

If it is View -> Controller -> REST, how to call REST API from controller?

This is my class which extends the rest_controller for users

 <?php
defined('BASEPATH') OR exit('No direct script access allowed');

require APPPATH . '/libraries/REST_Controller.php';

class User extends REST_Controller {

    function _construct(){
        parent::_construct();
        $this->load->database();
        $this->load->model('usermodel');

    }

    public function user_get(){
        $this->load->model('usermodel');
        $requestType = $this->get('req');//get method request
        switch ($requestType) {
            case 'login':
                $username = $this->get('un');
                $password = $this->get('pw');
                $user =  $this->usermodel->getUser($username, $password);
                if ($user){
                    $this->response($user, REST_Controller::HTTP_OK);
                }else{
                    $this->response([
                        'status' => FALSE,
                        'message' => 'No users were found'
                    ], REST_Controller::HTTP_NOT_FOUND); 
                }
                break;
            default:
                break;
        }
    }
}

This is the ajex call from my login page for login user

    function signIn(){
    var username = $('#signInUn').val();
    var password = $('#signInPw').val();
    $.ajax({
        method: "GET",
        url : "/infoshare/index.php/user/user/req/login/un/"+username+"/pw/"+password,
        dataType: 'JSON',
        success: function(data){
            var response = data.response;
            var status = data.status;
            if(status == 200){
                var userId = response[0].user_id;
                //success of user 
            }else{
                console.log(data);
            }
        },
        error: function(status){
            console.log("Error occured");
        }
    });
}

Solution

  • Yes you can call rest apil through ajax.

    $.ajax({ 
    type: "GET",
    data: {id:1123},
    url: "http://localhost:8080/restws/json/user/get",
    success: function(data){        
     alert(data);
    
      }
       });
    

    Pass the data which you need for the method. Also check you request type if POST or GET.