AdRock
AdRock

Reputation: 3096

Creating a Javascript array using JSON response from ajax

I am trying to query a database to get some rows of data that I can use in a JavaScript array. The format of the array should be like this so I can use it later.

var data = [
    {
        column1: 'Test 1',
        column2: 'Some Test'
    },
    {
        column1: 'Test 2',
        column2: 'Another Test'
    },
    {
        column1: 'Test 3',
        column2: 'Yet Another Test'
    }
];

This is how i get the rows from the database

 var data = new Array();

 $.ajax({
        url : 'util/getJSON.php',
        type : 'POST',
        dataType : 'json',
        success : function (response) {

        }        
    });

My php file that creates the JSON

$sql = "SELECT column1, column2 FROM table";

$stmt = $db->prepare($sql);
$stmt->execute();
$rows = $stmt->fetchAll();

$array = array();

foreach($rows as $key => $row) {
    $array[$key]['column1'] = $row['column1']; 
    $array[$key]['column2'] = $row['column2'];
}

echo json_encode($array);

The problem is I don't know how to create the JavaScript array using the JSON response in the ajax call.

EDIT:

I need to use the data array later like this

// Loop through the array

for(var i in data){
    if(data[i].name.match($search)){
        $suggestedUL.append($("<li><span class='suggest-name'>" + data[i].name + "</span><span class='suggest-description'>" + data[i].description + "</span></li>"));
    }
}

Upvotes: 1

Views: 2574

Answers (2)

meda
meda

Reputation: 45500

Ajax:

var data = new Array();

$.ajax({
    url : 'util/getSupplierList.php',
    type : 'POST',
    dataType : 'json',
    async: false,
    success : function (response) {
        data = JSON.stringify(response);
    }        
});

console.log(data);

Upvotes: 1

B W
B W

Reputation: 712

Within the success function, iterate through the response JSON array.

$.each(response, function(index, item) {
    data[index]["column1"] = $(item).column1;
    data[index]["column2"] = $(item).column2;
}

Upvotes: 0

Related Questions