sk786
sk786

Reputation: 414

Not getting JSON data when using AJAX, Slim and PHP

I am learning to create Rest API using Slim, but got stuck in here. I tried many things mentioned on internet but its still not getting value.

My Ajax:

$.ajax({
        type: 'POST',
        url: 'pages/search',
        dataType: "json",
        data: {'val1':value1,'val2':value2},
        success: function(data){
            alert(data.val1);
        }
    });

My PHP using Slim:

<?php

require 'Slim/Slim.php';

$app = new Slim();

$app->post('/search','getValue');
$app->run();


function getValue(){
    $request = Slim::getInstance()->request();
    $values= json_decode($request->getBody());

    $value1 = $values->val1;    // Throwing error here - Slim Application Error
    $value2 = $values->val2;

    echo "{'val1':'".$value1."'}";

}

?>

Upvotes: 0

Views: 1222

Answers (1)

Quentin
Quentin

Reputation: 944294

You are trying to read a JSON formatted request:

$values= json_decode($request->getBody());

and then outputting invalid JSON as the response (probably with the default Content-Type: text/html response header).

But you are passing jQuery's data a plain object so you are making a standard form encoded request:

data: {'val1':value1,'val2':value2},

and you are forcing jQuery to treat the response as JSON (which it isn't):

dataType: "json",

Assuming you want to make a JSON request and respond with JSON you need to:

Format the request correctly:

data: JSON.stringify( { val1: value1, val2: value2} ),
contentType: "application/json",

Output the response correctly:

header("Content-Type: application/json");
echo json_encode( array( "val1" => $value1 ) );

(NB: I have no idea what PHP framework you are using. The header function might not be the right way to deal with setting response headers in it).

Upvotes: 3

Related Questions