Jamie Fearon
Jamie Fearon

Reputation: 2634

PHP GET server response

I'm currently reading the great book JavaScript the Definitive Guide - 6th Edition by David Flanagan in the book he shows a function to receive some data from the servor as described here:

Pass the user's input to a server-side script which can (in theory) return a list of links to local lenders interested in making loans. This example does not actually include a working implementation of such a lender-findingservice. But if the service existed, this function would work with it.

function getLenders(amount, apr, years, zipcode) {
    if (!window.XMLHttpRequest) return;

    var ad = document.getElementById("lenders");
    if (!ad) return; 

    var url = "getLenders.php" + 
        "?amt=" + encodeURIComponent(amount) + 
        "&apr=" + encodeURIComponent(apr) +
        "&yrs=" + encodeURIComponent(years) +
        "&zip=" + encodeURIComponent(zipcode);

    var req = new XMLHttpRequest(); 
    req.open("GET", url); 
    req.send(null);

    req.onreadystatechange = function() {
        if (req.readyState == 4 && req.status == 200) {
            var response = req.responseText;
            var lenders = JSON.parse(response);

            var list = "";
            for(var i = 0; i < lenders.length; i++) {
                list += "<li><a href='" + lenders[i].url + "'>" +
                    lenders[i].name + "</a>";
            }
            ad.innerHTML = "<ul>" + list + "</ul>"; 
        } 
    }
}

He does not provide any PHP script to do this. I'm trying to write getLanders.php script to handle this response and would appreciate any advice.

Here is what I have so far:

<?php
  if( $_GET["amount"] || $_GET["apr"] || $_GET["years"] || $_GET["zipcode"] )
  {
      echo // What format should I make the list of lenders so that is it correctly 
           // broken up and handled by the JSON.parse() function?
  }
?>

So, my question would be what is the correct way to echo a list of information to the client so that David Flanagens function above can handle the request correctly?

Thanks for any advise.

Upvotes: 2

Views: 817

Answers (2)

juco
juco

Reputation: 6342

It looks like it's expecting a multi-dimensional array consisting of URL and name properties. You can echo JSON data with json_encode(), so something similar to:

$data = array(
   array('name' => 'foo', 'url' => 'url'),
   array('name' => 'bar', 'url' => 'url2'),
);
echo json_encode($data);

Upvotes: 2

Alexey
Alexey

Reputation: 3484

It can be done with json_encode function: http://www.php.net/manual/en/function.json-encode.php

Upvotes: 1

Related Questions