4

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>';
        }
    }
});
}
shieldcy
  • 592
  • 2
  • 11
  • 35

4 Answers4

4

Well each loop of your foreach will erase the data defined in the preview loop, so when your foreach is done iterating you end up with the last set of data.

You don't need to iterate through the array, because your query already returns an array

$sql = "SELECT ......";
$results = Db::getInstance()->ExecuteS($sql);
echo json_encode($results);

Now if you want to access you data from the success function you just need call them the same name as your rows. for instance if you rows are product_id, date, and name you will call them that way:

function getData(id){    
$.ajax({
    url: 'ajax_info.php',
    type: 'POST',
    dataType:'json',
    data: {id: id},
    success: function(response) {
        response = JSON.parse(response);

        console.log("Product id is: " + response[0].product_id);
        console.log("Product name is: " + response[0].name);
        console.log("Product date: " + response[0].date);
    }
});
}

You also need to understand the following: say for some reason you want to have different variable name for your json without changing your database then you will have to do the following:

$sql = "SELECT ......";
$results = Db::getInstance()->ExecuteS($sql);
$newResults = array();

foreach ($results as $row)
{
    $newResults[] = array('newId' => $row['product_id'], 'newName' => $row['name'], 'newDate' => $row['date']);
}

echo json_encode($newResults);

Which will result of changing the variables in JSON:

function getData(id){    
$.ajax({
    url: 'ajax_info.php',
    type: 'POST',
    dataType:'json',
    data: {id: id},
    success: function(response) {
        response = JSON.parse(response);

        console.log("Product id is: " + response[0].newId);
        console.log("Product name is: " + response[0].newName);
        console.log("Product date: " + response[0].newDate);
    }
});
}
Vulkhan
  • 438
  • 5
  • 15
  • 1
    Hello @john-doh , thanks for the reply. What I mostly meant is how I can deal with the array in the jquery code. Here: success: function(response) { }. I get array of objects in 'response' – shieldcy Jun 02 '17 at 00:00
  • 1
    thanks for your help @john-doh. I think I managed to iterate through the array. Just one question, do you know how I can add those array values back to php in a table? The only way is to do something like: document.getElementById('table') and then add data in innerHTML? or is there another solution? – shieldcy Jun 02 '17 at 00:27
  • 1
    Hey @shieldcy if i understand you well, you want to dupplicate this data to your database? or you just want to send a new set of data from an ajax query to your php page so it saves it on your sql table? – Vulkhan Jun 02 '17 at 00:35
  • Hello @john-doh, what I mean is, now that I manage to go through the array in jquery success return function... is it possible somehow to add these values in the main.php file? I updated my first post with the new jquery modificartions. Main.php contains the jquery and also html content. I want to populate a table in html using the results in jquery callback. Not sure if what I say is correct though. Thanks for your help anw :) – shieldcy Jun 02 '17 at 00:43
  • 1
    never mind, i think i can do it by appending the table and adding . Thanks for the help – shieldcy Jun 02 '17 at 00:50
2

the first step you have to do is parse the response into json, then you have to create table tag with the id.

example here's your JS

function getData(id){    
$.ajax({
    url: 'ajax_info.php',
type: 'POST',
dataType:'json',
data: {id: id},
success: function(response) {
    var data = JSON.parse(response);
    var st = "";
    $.each(data, function(index){
       st += "<tr><td>"+data[index].product_id+"</td>";
       st += "<td>"+data[index].date+"</td>";
       st += "<td>"+data[index].name+"</td></tr>";
    });
    $("#table_id").html(st);
}
});
}

then here's html

<table border="1" id="table_id">
</table>
Adzimzf
  • 181
  • 2
  • 11
  • nice suggestion, thank you. I was appending it by using InnerHTML which was quite ugly. Your way seems better. – shieldcy Jun 02 '17 at 01:02
  • i think you want to always update the content of the table, so it's better using html then append. if the answer is helped you please give it green – Adzimzf Jun 02 '17 at 01:04
0

The problem here is that javascript does not allow associative arrays, so you would have to use regular numeric arrays, or an object.

Here is an example of using numeric arrays:

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

    $array_info[0] = $product_id;
    $array_info[1] = $date;
    $array_info[2] = $name;
}

echo json_encode($array_info);

And then you can get the output like this:

function getData(id){    
$.ajax({
    url: 'ajax_info.php',
    type: 'POST',
    dataType:'json',
    data: {id: id},
    success: function(response) {

      var product_id = response[0];
      var date = response[1];
      var name = response[2];

    });
    }
dshukertjr
  • 15,244
  • 11
  • 57
  • 94
0

You can use JSON.parse() function on response to make it usable by JavaScript.