arch1ve
arch1ve

Reputation: 183

Creating JS array from JSON

I have the following AJAX function in jQuery:

$.post('../../afisare.php', {"fac_name" : facility_name }, function(response) {
            alert(response);
});

$.ajax({
    url: "../../afisare.php",
    dataType: "JSON",
    success: function(json){
        console.log(json);
    }
});

And the following encoding in a php file:

$facility_name = $_POST['fac_name'];

$facility_data = getFacilities($facility_name);
$facility_data2 = json_encode($facility_data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
print($facility_data2);

The array in the php file ($facility_data2) prints exactly as it should.

My question is: how do I create a javascript array in the succes function that contains the exact elements as the JSON?

Edit: added the $.post function also; The alert prints the JSON as it should, but the console.log(json) prints an empty array. To clarify: the JSON is generated based on what the getFacilities function returns.

Later edit: for anyone who has the same issue as I did (best advice: read the documentation thoroughly), here is the function that works:

$.post('../../afisare.php', {"fac_name" : facility_name }, function(json) {
    data = JSON.parse(json);
    console.log(data[0].facility_name);
});

The problem with my previous attempt was that I wasn't using the callback function in the $.post function as I should have (e.g. this function is directly linked to the variables that I am posting to the php file, thus being unable to be read from outside that function).

Upvotes: 0

Views: 68

Answers (2)

arch1ve
arch1ve

Reputation: 183

$.post('../../afisare.php', {"fac_name" : facility_name }, function(json) {
    data = JSON.parse(json);
    console.log(data[0].facility_name);
});

The problem with my previous attempt was that I wasn't using the callback function in the $.post function as I should have (e.g. this function is directly linked to the variables that I am posting to the php file, thus being unable to be read from outside that function).

Upvotes: 0

chaoskreator
chaoskreator

Reputation: 914

var result = [];

for(var i in json)
    result.push([i, json [i]]);

Upvotes: 1

Related Questions