1

I am creating a simple rest API in Codeigniter using the chriskacerguis/codeigniter-restserver.I have successfully created a login method and tested it using the postman and it works but i have created a simple login page to consume the API using the Jquery AJAX but when i try to send the through it , but $this->post() cannot read it but it works with postman.

Controller

<?php
defined('BASEPATH') or exit('No direct script access allowed');
require APPPATH . 'libraries/REST_Controller.php';
require APPPATH . 'libraries/Format.php';

use Restserver\Libraries\REST_Controller;

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");

    class Api extends REST_Controller
    {


        public function user_login_post()
        {
            $req = $this->post(); // always empty

            if (empty($req)) {
                $status = parent::HTTP_EXPECTATION_FAILED;
                $response = ['status' => $status, 'msg' => 'Missing data!'];

                $this->response($response, $status);

                exit();
            }

            $user = $this->User_model->get($req['email']);

            if (empty($user)) {
                $status = parent::HTTP_NOT_FOUND;
                $response = ['status' => $status, 'msg' => 'Email does not exist!'];

                $this->response($response, $status);

                exit();
            }

            if (md5($req['password']) != $user->password) {
                $status = parent::HTTP_FORBIDDEN;
                $response = ['status' => $status, 'msg' => 'Invalid email or password!'];

                $this->response($response, $status);

                exit();
            }

            // Generate token
            $tokenData['id'] = $user->user_id;
            $tokenData['email'] = $user->email;
            $tokenData['type'] = 'user';

            $token = AUTHORIZATION::generateToken($tokenData);

            $status = parent::HTTP_OK;

            $response = ['status' => $status, 'token' => $token, 'logged_in' => true];

            $this->response($response, $status);

        }
    }

Here is the JS code which I used to send a request to the above method

$('#submit').click(function (e) {
    e.preventDefault();

    const url = "<?= base_url() ?>" + 'api/user_login';

    $.ajax({
        type: 'POST',
        url: url,
        data: {
            "email": "test@gmail.com",
            "password": "password"
        },
        dataType: 'json',
        cache : false,
        processData: false,
        success: function (res) {
            console.log(res);

        },
        error: function (err) {
            console.log(err);

        }
    })

});

I am not able to get the data at server side. Any help would be appreciated.

Ropali Munshi
  • 2,757
  • 4
  • 22
  • 45

0 Answers0