0

I have been following the tutorial here http://code.tutsplus.com/tutorials/creating-an-api-centric-web-application--net-23417 to create an "api eccentric web application" however the application only covers making requests from PHP.

Halfway through the tutorial you get to a point in which you can make requests by url in the browser e.g http://localhost/simpletodo_api/?controller=todo&action=create&title=test%20title&description=test%20description&due_date=12/08/2011&username=nikko&userpass=test1234

Here is the code of the front controller that receives the requests

<?php
// Define path to data folder
define('DATA_PATH', realpath(dirname(__FILE__).'/data'));

//include our models
include_once 'models/TodoItem.php';

//wrap the whole thing in a try-catch block to catch any wayward exceptions!
try {
    //get all of the parameters in the POST/GET request
    $params = $_REQUEST;

    //get the controller and format it correctly so the first
    //letter is always capitalized
    $controller = ucfirst(strtolower($params['controller']));

    //get the action and format it correctly so all the
    //letters are not capitalized, and append 'Action'
    $action = strtolower($params['action']).'Action';

    //check if the controller exists. if not, throw an exception
    if( file_exists("controllers/{$controller}.php") ) {
        include_once "controllers/{$controller}.php";
    } else {
        throw new Exception('Controller is invalid.');
    }

    //create a new instance of the controller, and pass
    //it the parameters from the request
    $controller = new $controller($params);

    //check if the action exists in the controller. if not, throw an exception.
    if( method_exists($controller, $action) === false ) {
        throw new Exception('Action is invalid.');
    }

    //execute the action
    $result['data'] = $controller->$action();
    $result['success'] = true;

} catch( Exception $e ) {
    //catch any exceptions and report the problem
    $result = array();
    $result['success'] = false;
    $result['errormsg'] = $e->getMessage();
}

//echo the result of the API call
echo json_encode($result);
exit();

So my question is, how would I make a request using Javascript in which it will return a JSON result?

EDIT: It appears I forgot to mention that this request will be made cross domain

2
  • 1
    have a look at json_encode in php . here is the link php.net/manual/en/function.json-encode.php Commented Sep 7, 2015 at 20:36
  • 1
    @georoot The code already uses json_encode. The question seems to be about how to make the appropriate request from JavaScript .. Commented Sep 7, 2015 at 20:46

3 Answers 3

1

To call the API you need to make an AJAX request using JavaScript. Please read HERE. This page have step by step guideline.

As you're sending JSON from your API so, after AJAX success you might need to JSON.parse() the received content from API.

Sign up to request clarification or add additional context in comments.

Comments

1

Here is a simple example

<?php
session_start();
if(!isset($_SESSION['user'])) {
    echo -1;
    die;
}
$email=$_SESSION['user'];
$arr= array();
$con=mysqli_connect("localhost","usrname","password","databasename");
if (mysqli_connect_errno()) 
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="select * from user where email = '$email'";
$result = mysqli_query($con,$sql);

while ( $row = mysqli_fetch_array($result)) {
        $arr[] = $row['u_id'];
        $arr[] = $row['f_name'];
        $arr[] = $row['l_name'];
        $arr[] = $row['email'];
        $arr[] = $row['telephone'];
        $arr[] = $row['address'];
}
echo json_encode($arr);
mysqli_close($con);?>

the above is a simple php script which get user's info from simple database. You can call the above php script from javascript using ajax call as below:

function Get_User_Info(URL) {
    $.ajax(
            {
                type: "GET",
                url: URL,
                dataType: "text",
                success: function (response) {
                    var JSONArray = $.parseJSON(response);
                    connsole.log(JSONArray);
            });
        }

here the response contains the information from the database. and URL argument is the URL of you php page. I hope that gonna help you.

1 Comment

I am sorry for not mentioning this before but the request will be made cross domain, am I right thinking this way will not work?
0

So I got it to work, what I had attempted was a regular XMLHttpRequest in Javascript. The process was working as data was being saved but nothing was being returned. What I was missing was this line from the top of my index.php

header('Access-Control-Allow-Origin: *');

I undertand that the * means all websites may access the API

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.