0

I am new to the RESTful concept, learning Backbone now and I am having some problems.

Right now I am running a single page application on http://localhost using backbone.js and the API is at http://phalconapi (another vhost).

At http://phalconapi I have this jsontest.php script returning JSON:

<?php
header("HTTP/1.1 200 OK");
echo json_encode( ['test'=>1] );

At http://localhost, this is my app.js enabling backbone.

var FlightsList = Backbone.Model.extend({
    //urlRoot: '/jsontest.php'
    urlRoot: 'http://phalconapi/jsontest.php'
});

var DashboardController = BackboneMVC.Controller.extend({
    name: 'dashboard',

    home: function() {
        var flights = new FlightsList();

        flights.fetch({
            success: function(flights) {
                alert(flights.toJSON());
                console.log(flights.toJSON());
            },
            error: function(model, xhr, options) {
                console.log('Fetch error');
            }
        });
    }
});

var router = new BackboneMVC.Router();

Backbone.history.start({pushState: true});

So the problem is, whenever I set the urlRoot in backbone to /jsontest.php and I place that file in the same directory (in localhost), it works just fine.

But when I change it to http://phalconapi/jsontest.php, then it doesn't work. Using Google Chrome Developer Tools I noticed the message "This request has no response data available." and that didn't show up on the other test using /jsontest.php as urlRoot. Right there it's supposed to show {"test":1}.

mignz
  • 3,648
  • 2
  • 20
  • 21

1 Answers1

0

Fixed it by setting access control headers on the api:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: X-Requested-With');
header('Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS');

It was a CORS issue. Thank you Half Crazed!

If someone's also using Phalcon, use $response->setHeader().

mignz
  • 3,648
  • 2
  • 20
  • 21