Reading JSON response from Silex REST API

55 Views Asked by At

I have some javascript that used to call a PHP file to get a list of countries, using jquery.

The PHP returned a json encoded array that looked like this:

[ { "CountryID": "11", "CountryName": "Argentina" }, { "CountryID": "14", "CountryName": "Australia" }, { "CountryID": "15", "CountryName": "Austria" }, { "CountryID": "20", "CountryName": "Barbados" }, etc

My javascript read this OK and popped all the names into a list, like this:

var queryString = "api/countries.php";

$.get(queryString, function(data){

    var obj = JSON.parse(data); 
    var thisGet = obj.length;
    var countryList = document.getElementById('country_list');

    var opt = document.createElement('option');
    for (i = 0; i < thisGet; i++)
    {
        var opt = document.createElement('option');
        opt.value = obj[i].CountryID;
        opt.innerHTML = obj[i].CountryName;
        countryList.appendChild(opt);
    }
});

This worked fine, but I started using Silex (Symfony) for something else, so I created a route to get my countries. This works fine when you just type the URL into a browser or Postman, but it has to return a Response. This is the new code:

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

    $result = getCountries();
    $response = new JsonResponse();
    $response->setData($result);
    return $response;
});

When my javascript gets the data now, it can't read it, and if I display it in an alert, I just get this:

[object Object],[object Object],... etc

Can anyone please explain what I need to do to get the data from the Response? I've looked at all the other questions on here that SO recommended, but none of them help.

(getCountries just does a call into a database, like this:

function getCountries() {
    global $DBH;

    $q = 'SELECT * FROM country_summary ORDER BY CountryName';
    $stmt = $DBH->prepare($q);
    $stmt->execute();
    $stmt->setFetchMode(PDO::FETCH_ASSOC);
    $rows = $stmt->fetchAll();
    return $rows;
}

TIA.

0

There are 0 best solutions below