Looping through a Json array and populating a list


#1

Hi guys,

I am making an Ajax call to a PHP that get some data from a MYSQL table and out puts the result:

if ($result = mysqli_query($mysqli, $query5)) {
  $out = array();

  while ($row = $result->fetch_assoc()) {
    $out[] = $row;
  }
}
  /* encode array as json and output it for the ajax script*/
  echo json_encode($out);

I get what I believe is a JSON array returned with :

btnGetFile.onclick = function() {
     req = Ajax("ajaxGetURL.php/?urlToGet=" + txtURL.value, done);
     
     
 };

 function done() {
     if (req.status == 200) { //success
         htmResponse.innerHTML = req.responseText;
         var data = req.responseText;
       // loop through the array
       for(var i in data)
    {
      
      var text =data[i].InvID;
      alert(text);
      var choic=data[i].CustID;
      var output='<li>'+text+'</li>';
    }
    $('#List1').empty().append(output);
     } else { //failure
         msg = "Error: Status = " + req.status;
         if (TypeName(req.statusText) == "string") {
             msg = msg + " " + req.statusText;
         }
         if (TypeName(req.err) == "string") {
             msg = msg + " " + req.error;
         }
         NSB.MsgBox(msg);
     }
 }
List1.onclick=function(i){
    if(typeof i == "object") return;
  alert("Menu item chosen: " + i + " " + List1.getItem(i));
} 

I am getting undefined.
The app is at http://toolfolks.com/AjaxGetWebFile/
Once I have this bit working I then need to populate the list with some of the data in the array.

What am I doing wrong here please.

Cheers

Steve Warby


#2

Have you tried putting a console.log(data) just after you get it? What does that look like?


#3

I notice you have a forward slash in your request.
Maybe try taking that out.


#4

I am getting
[{“InvID”:“1”,“CustID”:“504”,“invDate”:“2017-07-17”,“quoteTitle”:null,“notes”:“quote notes”,“notesInternal”:null,“type”:null,“status”:“Live”,“delMethod”:“Test”,“CODAmount”:null,“orderNum”:“testquote23”,“invNett”:“3.00”,“invTax”:“0.60”,“invTotal”:“3.60”,“payMethod”:“Value”,“vatRate”:“20.00”,“posted”:null,“payType”:“cash”,“Cleared”:null,“Pay_date”:“0000-00-00”,“Transation_ID”:null,“Cleared_Date”:null,“Nominal”:null,“Dept”:null,“Taxcode”:null,“Printed”:“0”,“Invoice_Printed”:null},{“InvID”:“500”,“CustID”:“504”,“invDate”:null,“quoteTitle”:null,“notes”:null,“notesInternal”:null,“type”:null,“status”:“Live”,“delMethod”:“Test”,“CODAmount”:null,“orderNum”:null,“invNett”:null,“invTax”:null,“invTotal”:null,“payMethod”:“Cash”,“vatRate”:null,“posted”:null,“payType”:null,“Cleared”:null,“Pay_date”:null,“Transation_ID”:null,“Cleared_Date”:null,“Nominal”:null,“Dept”:null,“Taxcode”:null,“Printed”:“0”,“Invoice_Printed”:null},{“InvID”:“501”,“CustID”:“504”,“invDate”:null,“quoteTitle”:null,“notes”:null,“notesInternal”:null,“type”:null,“status”:“Live”,“delMethod”:“Test”,“CODAmount”:null,“orderNum”:null,“invNett”:null,“invTax”:null,“invTotal”:null,“payMethod”:“Cash”,“vatRate”:null,“posted”:null,“payType”:null,“Cleared”:null,“Pay_date”:null,“Transation_ID”:null,“Cleared_Date”:null,“Nominal”:null,“Dept”:null,“Taxcode”:null,“Printed”:“0”,“Invoice_Printed”:null}]

I am presuming I now have an array with

var data = [];
data = req.responseText; 

Not sure why my loop is not showing what I am expecting
ie 1 500 501
Do I have to convert the data ???

Cheers

Steve Warby


#5

Thanks for the reply.

I am getting the data back okay. It is looping the data I am having problems with.


#6

I have found this here

http://jsfiddle.net/8TT4p/67/

//This sample must be run from the same server that ajaxGetURL.php is on.
btnGetFile.onclick = function() {
req = Ajax(“ajaxGetURL.php?urlToGet=” + txtURL.value, done);
//req = Ajax("http://www.toolfolks.com/techy/someData.php/, done);

};

function done() {
 if (req.status == 200) { //success
     htmResponse.innerHTML = req.responseText;
     o = htmResponse.innerHTML;
    var arr = Object.keys(o).map(function(k) { return o[k] });
     console.log(arr);
   // loop through the array
   for (var i = 0; i < arr.length; i++){
  var text = arr[i].InvID;
  console.log('InvId ='+ text);
  var choic=arr[i].CustID;
  var output='<li>'+text+'</li>';
}

}
}

Button1.onclick=function(){
var o =  [{"InvID":"1","CustID":"504","invDate":"2017-07-17","quoteTitle":null,"notes":"quote notes","notesInternal":null,"type":null,"status":"Live","delMethod":"Test","CODAmount":null,"orderNum":"testquote23","invNett":"3.00","invTax":"0.60","invTotal":"3.60","payMethod":"Value","vatRate":"20.00","posted":null,"payType":"cash","Cleared":null,"Pay_date":"0000-00-00","Transation_ID":null,"Cleared_Date":null,"Nominal":null,"Dept":null,"Taxcode":null,"Printed":"0","Invoice_Printed":null},{"InvID":"500","CustID":"504","invDate":null,"quoteTitle":null,"notes":null,"notesInternal":null,"type":null,"status":"Live","delMethod":"Test","CODAmount":null,"orderNum":null,"invNett":null,"invTax":null,"invTotal":null,"payMethod":"Cash","vatRate":null,"posted":null,"payType":null,"Cleared":null,"Pay_date":null,"Transation_ID":null,"Cleared_Date":null,"Nominal":null,"Dept":null,"Taxcode":null,"Printed":"0","Invoice_Printed":null},{"InvID":"501","CustID":"504","invDate":null,"quoteTitle":null,"notes":null,"notesInternal":null,"type":null,"status":"Live","delMethod":"Test","CODAmount":null,"orderNum":null,"invNett":null,"invTax":null,"invTotal":null,"payMethod":"Cash","vatRate":null,"posted":null,"payType":null,"Cleared":null,"Pay_date":null,"Transation_ID":null,"Cleared_Date":null,"Nominal":null,"Dept":null,"Taxcode":null,"Printed":"0","Invoice_Printed":null}];

var arr2 = Object.keys(o).map(function(k) { return o[k] });

console.log(arr2);
   for (var i = 0; i < arr2.length; i++){

  
  var text = arr2[i].InvID;
  console.log('InvId ='+ text);
  //var choic=arr2[i].CustID;
  //var output='<li>'+text+'</li>';
}

}

So when adding the ‘text’ manually it works but not when the data is returned from the ajax call.

Cheers

Steve Warby


#7

The data coming back is probably one long string. You need to convert the string to JSON by using JSON.parse.

http://wiki.nsbasic.com/JSON.Parse


#8

Thanks for the info.

the key was data = JSON.parse(req.responseText);

For anyone looking to populate the list from a database I have the following:

    //This sample must be run from the same server that ajaxGetURL.php is on.
      btnGetFile.onclick = function() {
      req = Ajax("ajaxGetURL.php?urlToGet=" + txtURL.value, done);
     //req = Ajax("http://www.toolfolks.com/techy/someData.php/, done);
     
    };

    function done() {
     if (req.status == 200) { //success
          data = JSON.parse(req.responseText);
          htmResponse.innerHTML = req.responseText;
          var quoteResults = data;
         console.log(quoteResults);
       // loop through the array
       List1.deleteItem('all');
       for (var i = 0; i < quoteResults.length; i++){
      //Text = quoteResults[i].InvID;
      Text = quoteResults[i].InvID + "<span class='ui-li-aside'><p>" + quoteResults[i].quoteTitle + "</p></span>" + "<span class='ui-li-count'>"+quoteResults[i].CustID+"</span>";
      ImgSrc = quoteResults[i].quoteTitle;
      List1.addItem(Text,ImgSrc) 
     
    }
   }
 }

#9

Thanks for posting the result!