Populate a div with ajax response from server

Viewed 154

I am trying to populate five div's with the content of an Ajax response.

Some far I have tried the following:

On the line marked "POPULATION LINE" I have tried just on the first div, if I can get that to work the rest of the div's will be the same:

$("#time").val(result[0]);
$("#time").html(result[0]);
$("#time").innerHTML(result[0]);
$("#time").html(result['Time']);

the div's

<div class="fixed" id="time"></div>
<div class="fixed" id="operator"></div>
<div class="fixed" id="destination"></div>
<div class="fixed" id="platform"></div>
<div class="fixed" id="estimated"></div>

The script that produces the ajax response:

$numberOfLine = 10;
$numberOfLRecords = 100;
$timeOffset = 60;
$timeWindow = 120;

require("OpenLDBWS.php");
$OpenLDBWS = new OpenLDBWS("TOKEN");
$response = $OpenLDBWS->GetDepartureBoard($numberOfLRecords,"GLC",0,"from",$timeOffset,$timeWindow); 
header("Content-Type: text/plain");

$data = array();

if (isset($response->GetStationBoardResult->trainServices->service))
  {
   
    foreach($response->GetStationBoardResult->trainServices->service as $service)
    {
     
      $destinations = array();
      foreach($service->destination->location as $location)
      {
        $destinations[] = $location->locationName;
        $desticrs[] = $location->crs;
      }
      
      $recordtime = substr($response->GetStationBoardResult->generatedAt, 0, 16);
      $origin_location = $response->GetStationBoardResult->locationName;
      $origin_crs= $response->GetStationBoardResult->crs;
      $time = $service->std;
      $serviceID = $service->serviceID;
      $operator = $service->operator;
      $dest = implode($destinations);
      $dest_crs = implode($desticrs);
      $plat = $service->platform;
      $est= $service->etd;
      $datetime = substr($recordtime, 0, 16);
      $recordtime = str_replace('T',' ',$recordtime); 
      $recordtime = date("Y-m-d H:i",strtotime($recordtime));
     
     $data[] = array(
                "Time"          => $time ,
                "Operator"      => $operator,
                "Destination"   => $dest,
                "Platform"      => $plat,
                "Estimated"     => $est); 
    }
}
echo json_encode($data);

The response:

0: {Time: "15:04", Operator: "ScotRail", Destination: "Ayr", Platform: null, Estimated: "On time"}
1: {Time: "15:04", Operator: "ScotRail", Destination: "Dalmuir", Platform: "17", Estimated: "On time"}
2: {Time: "15:04", Operator: "ScotRail", Destination: "Whifflet", Platform: "16", Estimated: "On time"}
3: {Time: "15:05", Operator: "ScotRail", Destination: "Neilston", Platform: null, Estimated: "On time"}
4: {Time: "15:06", Operator: "ScotRail", Destination: "Gourock", Platform: null, Estimated: "On time"}

The Ajax call

$(document).ready(function(){
$.ajax({
    url: 'test2.php',
    type: 'POST',
    dataType: 'JSON',
    success: function(data){
        var result = JSON.stringify(data); 
        result = JSON.parse(result);
        console.log("RESULT", result);
        $("#time").html(result[0]); //POPULATION LINE
        $("#operator").val(result[1]);
        $("#destination").val(result[2]);
        $("#platform").val(result[3]);
        $("#estimated").val(result[4]);
    }
 });
});
1 Answers

It's strange that you provide an Array as response with n Objects but you only use one of them.
If you only need the first one than you should go for the index 0 like const item = data[0]:

$.ajax({
    url: 'test2.php',
    type: 'POST',
    dataType: 'JSON',
    success: function(data){

        const item = data[0];
        console.log(item); // [object, Object]

        $("#time").html(item.Time);
        $("#operator").val(item.Operator);
        $("#destination").val(item.Destination);
        $("#platform").val(item.Platform);
        $("#estimated").val(item.Estimated);
    }
 });

If you have multiple sets than don't use elements with ID, and iterate over your Array, i.e:

  // (inside the success callback)

  // Use classes instead of ID
  const ELs_operator = document.querySelectorAll(".Operator");

  data.forEach((item, index) => {
    console.log(item); // [object, Object]
    ELs_operator[index].textContent = item.Operator;
  });

Or if you want to generate your elements dynamically:

// Emulating the data response
// For this DEMO ONLY!!!! you don't need this.
const data = [
  {Time: "15:04", Operator: "ScotRail", Destination: "Ayr", Platform: null, Estimated: "On time"},
  {Time: "15:04", Operator: "ScotRail", Destination: "Dalmuir", Platform: "17", Estimated: "On time"},
  {Time: "15:04", Operator: "ScotRail", Destination: "Whifflet", Platform: "16", Estimated: "On time"},
  {Time: "15:05", Operator: "ScotRail", Destination: "Neilston", Platform: null, Estimated: "On time"},
  {Time: "15:06", Operator: "ScotRail", Destination: "Gourock", Platform: null, Estimated: "On time"},
];


// This goes inside the success callback:

const HTML_row = (item) => `
  <div>${item.Time}</div>
  <div>${item.Operator}</div>
  <div>${item.Destination}</div>
  <div>${item.Platform || ""}</div>
  <div>${item.Estimated}</div>
`;

const HTML = data.reduce((h, item) => h += HTML_row(item), "");
document.querySelector("#arrivals").innerHTML = HTML;
#arrivals {
  display: flex;
  flex-flow: wrap;
}

#arrivals div {
  flex: 1 0 20%;
}
<div id="arrivals"></div>

Related