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.
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);
It can be done with json_encode function: http://www.php.net/manual/en/function.json-encode.php
Related
I have a simple array from a php file (the reason for not using a json file is cause this info comes from a mysql database)
$array[0] = array('id' => 1,'price' => '325');
$array[1] = array('id' => 2,'price' => '486');
header('Content-type: application/json');
echo json_encode($array);
and it echos as:
[{"id":1,"price":"325"},{"id":2,"price":"486"}]
now what I want to do is take the id and add it to a variable called counterval so that JavaScript will read it as
counterval1 = 325;
counterval2 = 486;
but I can't seem to get it to read that way. Here is the script at the current moment.
$.getJSON('test.php',function(data) {
$.each(data, function(i) {
counterval + data[i].id = data[i].price;
console.log (counterval2);
});
$('#results').html(counterval2);
});
var counterval1 = 0;
var counterval2 = 0;
any help on this would be greatly appreciated.
you can't do that... but you can do this...
var counterval = [];
$.getJSON('test.php',function(data) {
$.each(data, function(i) {
counterval[data[i].id] = data[i].price;
console.log (counterval[2]);
});
$('#results').html(counterval[2]);
});
counterval[1] = 0;
counterval[2] = 0;
See my comment on your post. If you really want the vars to look like you explained:
eval("counterval" + data[i].id + " = data[i]..price");
alert(counterval1);
I'm trying to get a grasp on using $.getJSON with an array from PHP.
Here's a simple example where all I want to do is output the requested info. Should the alert(data) return the array object? I am not alerting anything.
PHP file (account.php):
$arr = array('items' => 5,'others' => 6);
echo $arr = json_encode($arr)
HTML file:
$("#unsubscribe").click(function() {
$.getJSON("account.php?", function(data) {
alert(data);
});
});
First of all, it's probably a good idea if you try to load account.php in your browser. You should expect to see:
{"items":5,"others":6}
However, you won't see this. You will instead see a Parse Error, expected ;. Because you forgot it on the echo line.
This is why you see no alert. A PHP error is clearly not valid JSON, and viewing the browser's error console would tell you this ;)
In my projects I am using dump function for viewing json returned array.
Here it is:
function dump(arr,level) {
var dumped_text = "";
if(!level) level = 0;
//The padding given at the beginning of the line.
var level_padding = "";
for(var j=0;j<level+1;j++) level_padding += " ";
if(typeof(arr) == 'object') { //Array/Hashes/Objects
for(var item in arr) {
var value = arr[item];
if(typeof(value) == 'object') { //If it is an array,
dumped_text += level_padding + "'" + item + "'"+"\\n";
if (level < 0)
dumped_text += dump(value,level+1);
} else {
dumped_text += level_padding + "'" + item + "' => '" + value + "'"+"\\n";
}
}
} else { //Stings/Chars/Numbers etc.
dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
}
return dumped_text;
}
in the following code , I have echoed $strXML in php file,which shows the whole $strXML but I want to show just the 'name' element values in javascript. Can anybody help me?
PHP :
$strXML = '<? xml version="1.0" ?>'."\n";
$id = $_GET['id'];
$name = $_GET['name'];
$strXML .= '<data>'."\n";
$strXML .= '<id>'.$id.'</id>'."\n";
$strXML .= '<name>'.$name.'</name>'."\n";
$strXML .= '</data>'."\n";
echo $strXML;
javascript:
var xhr = createRequest();
function getData() {
if(xhr) {
var id = document.getElementById("id").value;
var name = document.getElementById("name").value;
var url = "search.php?id=" + id + "&name=" + name;
xhr.open("GET", url, true);
xhr.onreadystatechange = show;
xhr.send(null);
}
}
function show()
{
if ((xhr.readyState == 4) &&(xhr.status == 200))
{
var strXML = xhr.responseText;
alert(strXML);
}
}
The responseText property is a string (a DOMString in the specification but that is just a String in JavaScript) so you can't call getElementsByTagName on it; you want to look at xhr.responseXML.
Also, getElementsByTagName searches beneath the element it is called on:
The subtree underneath the specified element is searched, excluding the element itself.
So you'll have to access the contents directly rather than inside a loop:
var result = xhr.responseXML;
var id = result.getElementsByTagName('id' ).childNodes[0].nodeValue;
var name = result.getElementsByTagName('name').childNodes[0].nodeValue;
If you want to return multiple <data> elements (and hence, use your for loop) then you'll have to wrap the return value from your PHP in one more element:
<results>
<data>
<id>$id</id>
<name>$name</name>
</data>
<!-- etc. -->
</results>
Not to criticize your current decision, but I've found that it's much easier to use a combination of PHP and JavaScript if you use JSON for transferring the data back and forth. PHP has excellent methods to create JSON, and JavaScript... well, it is JavaScript. I think this generally makes development a whole lot easier:
<?php
$data = array(
'data' => array(
'id' => $_GET['id'],
'name' => $_GET['name']
)
);
echo json_encode( $data );
And on the JS side:
var xhr = createRequest();
function getData() {
if(xhr) {
var id = document.getElementById("id").value;
var name = document.getElementById("name").value;
var url = "search.php?id=" + id + "&name=" + name;
xhr.open("GET", url, true);
xhr.onreadystatechange = show();
xhr.send(null);
}
}
function show()
{
if ((xhr.readyState == 4) &&(xhr.status == 200))
{
var response = eval('(' + xhr.responseText + ')');
alert( response.data.id );
}
}
Of course, if you're already using the XML elsewhere (e.g. in a webservice, or using XSLT to show the page), XML would make more sense. Just my $0,02 though.
I have a project where I've created JSON data for Project Prices/Prices I've gotten this far and pretty much ran into a wall, any help at all would help! I've checked all over the web and on jQuery.getJSON but I wound up getting super confused.
$data = mysql_query("SELECT * FROM xxx")
or die(mysql_error());
$arr = array();
$rs = mysql_query("SELECT product, price FROM products");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo '{"products":'.json_encode($arr).'}';
I need to get the product price and product name into this jquery script
$(document).ready(function() {
/*** CONSTANTS ***/
var KEY = 0;
var VALUE = 1;
/*** DEFINE DATA SETS ***/
var POINTS = [ ["$productA", $PRICE ], ["$productB", $PRICE], ["$productC", $PRICE], ["$productD", $PRICE], ["$productE", $PRICE], ["$productF", $PRICE] ];
var SHIPPING_COSTS = [ ["Pickup", 0], ["Next Day Delivery", 30], ["Same Day Print/Same Day Delivery", 65] ];
for (var i = 0; i < POINTS.length; i++) {
$("#quantity").append("<option value='" + POINTS[i][VALUE] + "'>" + POINTS[i][KEY] + "</option>");
}
for (var i = 0; i < SHIPPING_COSTS.length; i++) {
$("#shipping").append("<option value='" + SHIPPING_COSTS[i][VALUE] + "'>" + SHIPPING_COSTS[i][KEY] + "</option>");
}
$("select.autoUpdatePrice, input.autoUpdatePrice").bind("mousedown click change", function(event) {
Calculate();
});
Calculate();
});
function Calculate() {
var net = parseFloat($("#quantity").val());
/* Calculate the magical # by adding the form fields*/
var designFee = $("#abcDesignFee").attr("checked") ? $("#abcDesignFee").val() : 0.0;
var proofFee = $("#abcProofFee").attr("checked") ? $("#abcProofFee").val() : 0.0;
var MyPrice;
MyPrice = parseFloat( parseFloat(proofFee) + parseFloat(designFee) + net + parseFloat($("#shipping").val()));
$("#DumpHere").html("Your Price: $" + formatNumber(MyPrice));
$("#abcName").val($("#quantity").find(":selected").text() + " " + ProductNamePlural);
$("#abcPrice").val(MyPrice);
}
In your PHP script, can you just json_encode() your array of objects without wrapping it in the string? And instead encode the JSON object like so:
<?php
// your script ...
echo json_encode($arr);
This creates an array of JSON encoded objects:
[{"name":"item 1","price":4.99},{"name":"item 2","price":9.99}]
Make an AJAX request in your JS to query your PHP script, and use jQuery's $.each() and $.parseJSON() methods to iterate over the returned JSON data:
$.post('get_products.php', { data: foo }, function(json) {
$.each($.parseJSON(json), function(key, product) {
console.log(product.name + ' ' + product.price);
});
});
Hope this helps :)
When I was learning - I had exactly the same problem - but it got answered here
What I didn't realise at the time was that you can use object notation (which is the ON of json) to access the data you sent.
If you look at my question and the answer I selected, once you have sent the data back to javascriot you can access it easily. In my example it would be as straitforward as using data.catagory_desc in javascript to find the data that was encoded.
Hi searched through the questions here, but couldn't find anything. I'm new at writing PHP and jQuery, so bear with me.
What I'm trying to do is send an ajax request using jQuery to my script which runs a mysql query on data from my database and serializes it into the JSON format using php's json_encode. The response is then parsed with the available json2.js script. All of this works fine, but I'd also like to return more data other than just JSON from this script.
mainly, i'd like to also echo the following line before the json_encode:
echo "<h1 style='margin-left: 25px;'>$num_rows Comments for $mysql_table</h1>";
however, my jQuery is evaluating the entire response during the ajax success, making the json.parse function fail due to the script's return being in an invalid format.
success: function(data) {
//retrieve comments to display on page by parsing them to a JSON object
var obj = JSON.parse(data);
//loop through all items in the JSON array
for (var x = 0; x < obj.length; x++) {
//Create a container for the new element
var div = $("<div>").addClass("bubble").appendTo("#comments");
//Add author name and comment to container
var blockquote = $("<blockquote>").appendTo(div);
$("<p>").text(obj[x].comment).appendTo(blockquote);
var cite = $("<cite>").appendTo(div);
$("<strong>").text(obj[x].name).appendTo(cite);
$("<i>").text(obj[x].datetime).appendTo(cite);
}
$("#db").attr("value", '' + initialComments + '');
}
does anyone know how i can return the html line as well as the json_encode to use this script for more than just json population?
thankyou, this website has been wonderful in answering my noob questions.
my php:`
for ($x = 0, $numrows = mysql_num_rows($result); $x < $numrows; $x++) {
$row = mysql_fetch_assoc($result);
$comments[$x] = array("name" => stripslashes($row["name"]), "comment" => stripslashes($row["comment"]), "datetime" => date("m/d/Y g:i A", strtotime($comment['datetime'])));
}
//echo "<h1 style='margin-left: 25px;'>$num_rows Comments for $mysql_table</h1>";
$response = json_encode($comments);
echo $response;`
Don't echo the line, save it in a variable. Construct a simple array
$response = array(
'html' => $the_line_you_wanted_to_echo,
'jsobject' => $the_object_you_were_going_to_send_back
); and send that back ( via json_encode ) instead.
Also, you don't need json2.js, jQuery has an excellent JSON parser.
you can load like this $.get( 'your/url', { params : here }, success, 'JSON' );
Changed to match your newly introduced iteration.
for ($x = 0, $num_rows = mysql_num_rows($result); $x < $num_rows; $x++) {
$row = mysql_fetch_assoc($result);
$comments[$x] = array(
"name" => stripslashes($row["name"]),
"comment" => stripslashes($row["comment"]),
"datetime" => date("m/d/Y g:i A", strtotime($comment['datetime']))
);
}
$html = "<h1 style='margin-left: 25px;'>$num_rows Comments for $mysql_table</h1>";
echo json_encode(array( 'comments' => $comments, 'html' => $html ));
then, in your javascript, you have
function success( parsedObject ){
parsedObject.html; // "<h1 style..."
parsedObject.comments; // an array of objects
parsedObject.comments[0].name
+ " on " + parsedObject.comments[0].datetime
+ " said \n" + parsedObject.comments[0].comment; // for example
}
As said above just put all the data you want to get back in an array and encode that.
<?php
echo json_encode(array(
'html' => $html,
'foo' => $bar,
'bar' => $baz
));
?>
Also as said you don't need json2.js. You can parse JSON data with any of jQuery's ajax functions by specifying the data type as json.
$.ajax({
type: 'POST',
url: 'path/to/php/script.php',
dataType: 'json',
data: 'foo=bar&baz=whatever',
success: function($data) {
var html = $data.html;
var foo = $data.foo;
var bar = $data.bar;
// Do whatever.
}
});
EDIT Pretty much what Horia said. The only other variation I could see is if you wanted everything in the same array.
For example:
PHP:
<?php
// You have your comment array sent up as you want as $comments
// Then just prepend the HTML string onto the beginning of your comments array.
// So now $comments[0] is your HTML string and everything past that is your comments.
$comments = array_unshift($comments, $your_html_string);
echo json_encode($comments);
?>
jQuery:
$.ajax({
type: 'POST',
url: 'path/to/php/script.php',
dataType: 'json',
data: 'foo=bar&baz=whatever',
success: function($comments) {
// Here's your html string.
var html = $comments[0];
// Make sure to start at 1 or you're going to get your HTML string twice.
// You could also skip storing it above, start at 0, and add a bit to the for loop:
// if x == 0 then print the HTML string else print comments.
for (var x = 1; x < $comments.length; x++) {
// Do what you want with your comments.
// Accessed like so:
var name = $comments[x].name;
var comment = $comments[x].comment;
var datetime = $comments[x].datetime;
}
}
});
You might be interested in jLinq, a Javascript library that allows you to query Javascript objects. A sample query would be:
var results = jLinq.from(data.users)
.startsWith("first", "a")
.orEndsWith("y")
.orderBy("admin", "age")
.select();
jLinq supports querying nested objects and performing joins. For example:
var results = jLinq.from(data.users)
.join(data.locations, //the source array
"location", //the alias to use (when joined)
"locationId", // the location id for the user
"id" // the id for the location
)
.select(function(r) {
return {
fullname:r.first + " " + r.last,
city:r.location.city,
state:r.location.state
};
});