Ajax returns array of objects to jquery and php

Viewed 5108

I am not exactly sure if I'm doing it correctly but I will appreciate if someone can explain to me the process

I have a div in my main.php file with onclick function

<div class='show_products' onclick='getData(".$id.")'>

The jquery function:

function getData(id){    
$.ajax({
    url: 'ajax_info.php',
    type: 'POST',
    dataType:'json',
    data: {id: id},
    success: function(response) {
        console.log(response); //shows a list of objects (array elements)
    }
});
}

And the ajax file

$sql = "SELECT ......";
$results = Db::getInstance()->ExecuteS($sql);
foreach($results as $row) {
    $product_id = $row['product_id'];
    $date = $row['date'];
    $name = $row['name'];

    $array_info['product_id'] = $product_id;
    $array_info['date'] = $date;
    $array_info['name'] = $name;
}

echo json_encode($array_info);

The above code returns the array created in ajax file, back to jquery within the success function.

What I don't understand is: How can I go through the array and use it in the main.php file? I want to iterate through it and create a table with the values in the array. Meaning 3 columns, product id - date - name, and they will be populated by the returned array from ajax.

Is that possible or am I doing it wrong?

Would appreciate any help

EDIT: Updated jquery code

function getData(id){    
$.ajax({
    url: 'ajax_info.php',
    type: 'POST',
    dataType:'json',
    data: {id: id},
    success: function(response) {
        document.getElementById('table_'+id).style.display='block';

        for ( var i = 0; i < response.length; i++ ) {
            console.log(response[i]);                
            var div = document.getElementById('table_'+id);
            div.innerHTML = div.innerHTML + '<tr><td>'+response[i].product_id+'</td><td></td><td></td><td></td><td></td></tr>';
        }
    }
});
}
4 Answers
Related