randomwhiteguy randomwhiteguy - 1 year ago 72
PHP Question

How to get data from a server side script with ajax/jquery

I'd like to create a function where i could fill a table with data accessed from a url. For example "urlexample.php" which contains an array like

[{"id":"247547","business":"some business","address":"some address","rating":"3","date":"2016,01,01","postcode":"242 3ad"}]

.Im relatively new to ajax and jquery and find hard to get the grips of it, im just not sure where to start with. I dont have any code which is worth of noting down as its some basic page css and not related to the actual function.

Answer Source

You can use the jquery $.getJSON() function to return JSON data from a remote location. Here is an example using dummy data from here: http://jsonplaceholder.typicode.com/photos

const tableBody = $('#tblExample>tbody');

$.getJSON('http://jsonplaceholder.typicode.com/photos', function(data) {
  //iterate over each json object in the json collection returned from the server
  //value represents each individual object
  //you can access the properties on the 'value' object using dot notation
  $.each(data, function(key, value) {
    //create a <tr/> object for your table
    let row = $('<tr/>');
//set row values
    $('<td/>', {html: value.title}).appendTo(row);
    $('<td/>', {html: value.url}).appendTo(row);

And the HTML:

<table id="tblExample">

You can see a working example here: http://codepen.io/anon/pen/WoZVG

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download