pJeffJones
pJeffJones

Reputation: 65

How do I make my PHP API return JSON to a Javascript HTTP POST/GET request?

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

Upvotes: 0

Views: 1502

Answers (3)

pJeffJones
pJeffJones

Reputation: 65

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

Upvotes: 0

Allloush
Allloush

Reputation: 1168

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.

Upvotes: 1

thecodeparadox
thecodeparadox

Reputation: 87073

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.

Upvotes: 1

Related Questions