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;
}
Related
How to insert a auto-incrementing id from 1 before info.name in jQuery? I use below code to get aggregated data, for example, each quessionId has many related reasons. Below is my partial code of .js code in jQuery:
function fmtQuestionsByID(id,callback){
if(!DATA.questions[id] || !$('#card_'+id) )return;
var project = DATA.projects[DATA.questions[id].projectId];
if(!project)return;
var issueQuestionLists = DATA.alltags.reduce(function(a,b){
if(a[b['quessionId']]) {
a[b['quessionId']].push({name:b['name'],color:b['color'],description:b['description'],reason:b['reason'],question:b['question'],issueId:b['issueId'],department:b['department'],_id:b['quessionId']})
} else{
a[b['quessionId']] = [{name:b['name'],color:b['color'],description:b['description'],reason:b['reason'],question:b['question'],issueId:b['issueId'],department:b['department'],_id:b['quessionId']}]
}
return a;
},{});
for(var i=0;i < DATA.questions[id].tags.length;i++){
var lid = DATA.questions[id].tags[i];
for(var l in issueQuestionLists){
var lb = issueQuestionLists[l]
for(var c=0;c< lb.length;c++){
var lc = lb[c];
if(lc._id == lid){
var info = lc;
console.log('info', info);
$('.tags_question').append('['+info.name+']' + info.description + '。' + 'Reason: '+info.reason+ '。' ||'[no data]' );
}
}
}
}
}
And I use below html to get above data
<div id="questioninfo">
<span class="tags_question"></span>
</div>
In the console, I do have those dictionaries, but why the page only get one dict?
Thanks so much for any help.
Thanks so much for Swati's help, to change .html to .append.
You can define a variable which will store the value of count and then whenever you need to print it first increment it and then add that as well with the data which you are already appending .So your code will look like below :
var count = 0; //declare this
for (var i = 0; i < DATA.questions[id].tags.length; i++) {
//..other codes
var lc = lb[c];
if (lc._id == lid) {
count++; //increment
var info = lc;
console.log('info', info);
//add with other datas
$('.tags_question').append(count + '[' + info.name + ']' + info.description + '。' + 'Reason: ' + info.reason + '。' || '[no data]');
}
}
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
function something(frm,i){
//var ch=frm.outof1.value;
for(var j=1;j<=i;j++)
{
//var b="outof" + j;
alert(frm.outof+j.value);
}
//alert("outof" + i);
return false;
}
$js='onClick="something(this.form,\''. $ii .'\')"';
echo form_button('mybutton', 'Click Me', $js);
and getting output NAN
where in html this is // echo form_input('outof'.$i,''); // the form input.
First, you will want to make sure the passed $ii is made into the correct type (not a string) by using parseInt. Then you construct the form input name by concatenating 'outof' and the number before evaluating .value.
function something(frm, i)
{
for(var j = 1; j <= parseInt(i); ++j) {
alert(frm['outof' + j].value);
}
}
alert(parseInt(frm.outof) + parseInt(j.value))
Most likely, you're trying to sum up strings, and not integers
How do I fix this unterminated string literal error. What does this error mean and how can it be fixed
Below is the full code:
<?php
session_start();
if(isset($_POST['fileImage'])){
$idx = count($_POST ['fileImage']) -1 ;
$output = isset($_POST ['fileImage'][$idx]) ? $_POST ['fileImage'][$idx]['name'] : "";
}
?>
function stopImageUpload(success) {
var imageNameArray = ['<?php echo json_encode($output); ?>'];
var result = '';
if (success == 1) {
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
for (var i = 0; i < imageNameArray.length; i++) {
$('.listImage').append(imageNameArray[i] + '<br/>');
}
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
return true;
}
It means that there's something wrong with your quotes (an extra single quote in the echo'd content, or a line feed) and it's messing up the parser. Make sure any characters that are special in JS (quotes, line breaks etc) are properly escaped.
json_encode does this for you.
A better solution might look like this:
<?php
session_start();
$results = array();
if(isset($_POST['fileImage'])){
// not entirely sure what you're trying to achieve here
// so just replicating the logic you already had
// but I'm sure there's a better way to do whatever this is trying to do
$idx = count($_POST['fileImage']) -1 ;
$results[] = isset($_POST['fileImage'][$idx]) ? $_POST ['fileImage'][$idx]['name'] : "";
}
?>
function stopImageUpload(success) {
var imageNameArray = <?php echo json_encode($results); ?>;
var result = '';
if (success == 1) {
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
for (var i = 0; i < imageNameArray.length; i++) {
$('.listImage').append(imageNameArray[i] + '<br/>');
}
} else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
// you might want to use the "result" variable before returning
return true;
}
What changed? I removed the [] around the output of json_encode and made the array in PHP instead of JS. This way, when you do post the form, $results will be an array with a single element, and when you don't, it'll be an empty array. The rest of the logic should work just like before, but do read the comments I added.
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.