jqueryajaxjsonbackbone.jsslim

Slim PHP returning JSON


So basically I have my backbone application making an ajax GET call to my slim php app. It expects JSON dataType in return.

$.ajax({
        url: './myroute',
        type: 'GET',
        dataType: "json",
        data: { username: username, password: password },
        success: function(data) {},
        error: function(data) {}
});

In my slim file I have:

$app->get('/myroute', function() use ($app) {

    // all the good stuff here (getting the data from the db and all that)

    $dataArray = array('id' => $id, 'somethingElse' => $somethingElse);

    $response = $app->response();
    $response['Content-Type'] = 'application/json';
    $response->body(json_encode($dataArray));

});

    // Tried with these in the above GET request as well:
    // $app->contentType('application/json');
    // echo json_encode($dataArray);

While my request properly goes through (200), and I properly get my JSON data, the error is because it also returns the full index.php page data as well (which my javascript dataType: "json" does not allow, which triggers the error)

I figured setting the content type to "application/json" would solve this, but it still returns the full page contents as well as the json data.

Edit for reference

I used to have it set up so that Slim would render my html like:

$app->get('/', function () use ($app) {
    // would just have my main page files in home.php instead of index.php
    $app-render('home.php');
});

So that way there, there was no html page data being returned from index.php. But the way pushState is, I have to have my javascript scripts running on index.php, otherwise my pages wont be loaded properly since when they're requested, the scripts aren't there to delegate where the route should go.

Any help is appreciated!

Thanks SO!


Solution

  • Not familiar with slim framework. looks interesting. Sounds like code keeps running after json is displayed. Maybe try exit;ing the php app after responding with your json?

    $app->get('/myroute', function() use ($app) {
        // all the good stuff here (getting the data from the db and all that)
    
        $dataArray = array('id' => $id, 'somethingElse' => $somethingElse);
    
        $response = $app->response();
        $response['Content-Type'] = 'application/json';
        $response->body(json_encode($dataArray));
        exit();
    });
    $app->run();
    

    Hope this helps