Not really looking for code examples here, just concepts.
I have three sections on a page now that are being updated via three separate AJAX calls to PHP scripts, which return JSON. What would be the easiest way to condense these three calls into one larger call and receive the responses back on the client in JSON? How would I separate the responses on the client so I can manipulate the response data based on what information is sent back?
I like Cris' method, but think I can provide a little improvement. As you already have 3 seperate entities, to reduce the need for recoding everything, you could do something along the lines of combining you PHP into one file via include 'page.php' and sending an object back via JSON with properties named for what each of them do (lets say "names", "dates", and "fuzzyThings"). Your client code to send the request would then simply have all the arguments your 3 functions sent individually being sent in one request. The returned JSON would then look something like this (put your objects/arrays/whatever in the commented areas):
{
"names" : {/*stuff needed for names goes in here*/},
"dates" : {/*stuff needed for dates goes in here*/},
"fuzzyThings" : {/*all fuzzy things goes in here*/}
}
Once you get this to the client side, as I assume each may already have a function (or set of functions) to deal with it's return data, you should be able to call them in this manner:
function handler(retText) {
var returnedObject = eval(retText);
doStuffWithNames(returnedObject.names);
doStuffWithDates(returnedObject.dates);
playWithFuzzyThings(returnedObject.fuzzyThings);
}
Also, on the PHP end you can make a unified PHP page (without recoding anything hopefully) via:
<?php
echo '{';
echo '"names":{';
include 'names.php';
echo '},';
echo '"dates":{';
include 'dates.php';
echo '},';
echo '"fuzzyThings":{';
include 'fuzzyThings.php';
echo '}';
echo '}';
?>
Note: You may need to edit the 3 php pages so that they will check the $_POST correctly and without interfering with the functionality of the other pages if you have not already, I prefer the method of if(isset($_POST['whatever'])) { ... } to check that everything was sent correctly, this way, you can include as many as you want, and if there is nothing to do with a php file (i.e. you are not using that section on that page), then it will return a blank property, and you simply will not use it (basically making it a "one-size-fits-all" type of thing).
Hope it works for ya!
You can format your JSON like this:
"user" : [ {
"name" : "Harry",
"hobby" : "Skating"
}, {
"name" : "Dave",
"hobby" : "Scuba Diving"
} ],
"news" : [ {
"date" : "3/13/05",
"title" : "Blah",
"postedby" : "Mike",
} ]
And now in your AJAX response:
var data = eval('('+ xhr.responseText +')'); // Ajax response
var user = data.user[0].name; // Harry
var user2 = data.user[1].name; // Dave
var title = data.news[0].title;
You can use a for loop to traverse the data. In the example above you should now see how you can use PHP to format your JSON with multiple categories (user, news, ect.) and return back everything with only one call. If you would like a more elaborate example please refer to this article as well as this.
I think you have to make a JSON format according to those 3 sections on the page, ID them so that after response you can populate them to those sections.
I personally like the json method but if you're new to json or don't feel comfortable working with it for any reasons there's a jQuery plugin designed specifically for this purpose called jQuery Taconite Plugin
In Rails community there's a third way called RJS which is not that much hot nowadays and feels a little obsolete but still has its own fans. I'm curious if anybody has ported RJS to PHP or not?
this is workimg for me
php code:
//for test
$categoryName = "category";
$idcategory = "1";
$json = "{'productcategory':[{'categoryname':'".$categoryName."','idcategory':'".$idcategory."'}]}";
echo $json;
javascript:
var str = xmlhttp.responseText.trim();
var json = JSON.stringify(eval("(" + str + ")"));
var obj = JSON.parse(json);
alert(obj.productcategory[0].idcategory);
alert(obj.productcategory[0].categoryname);
Related
My questions keep getting abandoned even though I am replying, so I am going to remake my question in the hopes that someone can see my error and help me out. I will try to be as thorough as possible.
Step 1: I have an array named divisionsLarge in the following form:
divisionsLarge = [{ "car":"Toyota", "color":"blue", "numberTires":"four" }, { "car":"Honda", "color":"red", "numberTires":"four"}, etc. etc. ... ]
(This data is fictional, but it's the process that is wrong somewhere (also ignore the fact that numberTires is being stored as a string instead of a int, it's fictional folks :P)
Anyway, I have 92 of the above entries, all with the same keys: car, color, and numberTires.
Now, I go through the array with the following function loop in order to build an array with just car & numberTires key:
var divisions = [];
for (var i = 0; i < divisionsLarge.length; i++) {
if(divisionsLarge[i].numberTires != "two"){
var obj = { "car": divisionsLarge[i].car,
"numberTires": divisionsLarge[i].numberTires};
divisions.push(obj);}
}
Ok, at this point, I THINK everything is good to go. If I use the console in FireBug and type in divisions[0] I get a beautiful object that consists of, for example,
Object { car = "Toyota", numberTires = "four"}
(I think there are still "" around the car & numberTires entries, this is just how FireBug displays the object, I could be wrong)
Now here's what I need help with. I've created more .ajax queries than I can count. I've used JSON.stringified, I've not used JSON.stringified, I've used json_decode(), I've just done print_r($_POST)...I've done so many things that I am completely unable to analyze what is affecting what in order to diagnose what the problem might be. It seems my .ajax POSTS might be wrong, it seems my PHP might be wrong. So here are the questions I would GREATLY appreciate being answered:
1) Is the divisions array being created by the javascript considered JSON, or in a format easily converted to JSON?
2) What does my AJAX call need to be? I have tried so many AJAX calls that I have NO idea what is considered right/wrong. Also, please use divisions and not the snippet of the array I provided above, as the divisions array is dynamically generated by what's contained in divisionsLarge.
3) What does my divisions.php PHP file need to look like? Right now it has an HTML skeleton around it with <script></script> tags that reference divisionsLarge.js and divisions.js [do these need to be in one .js file?] I have seen blank pages and Array() for so long that I'm even doubting the rest of the PHP file now.
4) How do I get, for example, the color value of the first index? This seems rudimentary but most examples that I see are just querying an array of just one object, e.g. echo $_POST["color"], but I have multiple entries of color, so I'm not sure how to just ask for the first one. I would like to know this mostly because I have had such bad success with testing whether the array is working or not - I have lost all faith in print_r($_POST) and var_dump($json).
Okay, First your questions. Then the code:
1.- Divisions is not considered JSON, it is just an object array. All javascript objects can easily be turned into JSON using JSON.stringify(); Look at the code below.
2.- Look at the code below.
3.- I am not sure what kind of processing you need in your PHP. The code below assumes you are posting this to another page, where you will do some processing and output something, that you can use in the complete function.
4.- Look at the code below.
I think this is what you want to do:
Javascript
divisionsLarge = [{ "car":"Toyota", "color":"blue", "numberTires":"four" }, { "car":"Honda", "color":"red", "numberTires":"four"}];
var divisions = [];
for (var i = 0; i < divisionsLarge.length; i++) {
if(divisionsLarge[i].numberTires != "two"){
var obj = { "car": divisionsLarge[i].car,
"numberTires": divisionsLarge[i].numberTires};
divisions.push(obj);}
}
//I am just going to send one of your array elements as a JSON object.
var postData = JSON.stringify(divisions[0]);
var url = "url where you want to post your data";
$.ajax(url, {
type: "POST",
data: { "jsonBeingSent" : postData },
success: function(data) {
//Do whatever you need to do with your PHP output here.
//If you are using something like my php sample then you will be receiving a JSON object(s)
}
});
Now, on your PHP you probably want something like this:
<?php
//You may want to do some checking about the sender, and so on.
$receivedData = json_decode($_POST['jsonBeingSent']);
//You should see something like this if you print_r $receivedData
// object(stdClass) {
// [car] => ...
// [numberTires] => ...
// }
//So you could access the car value like this
echo $receivedData->{'car'};
//Do your processing and then, if you are using an array or object you can use `json_encode()` to output your data.
?>
Hope that helps.
I have an AJAX request that fetches some info from a SQL database in PHP.
The problem is, I need to send it back to AJAX in variables. Not to just echo it all out on screen.
Is this possible? If so, how would I go about doing something like this?
Thanks.
Yes, you could json_encode the variable you want to send back to client.
echo json_encode( array('variable' => 'your value' ) );
The client will receive the data through a callback when the request is completed. Without more clarification on specifics that's all i can offer, with some more details i can provide code samples depending on whether you're using a JavaScript library such as jQuery or doing a raw XHR request.
Edit: so in jquery to retrieve the variable above you would do the following.
$.getJSON('yourfile.php', function(data){
console.log( data.variable );
});
If I understand you right, you'll want to build a php array and use json_encode to dump the array out as your response. Then in JS you can use the resutling JSON text to form an object.
ajaxpage.php
$resultArray = buildArrayOfItems('Select * from products order by price');
//I usually have my sql records returned directly as an array.
//that's all buildArrayOfItems does
die(json_encode($resultArray));
The PHP should yield something like this
results
{[
{
"id" : "2643",
"name" : "Leather Jacket",
"price" : "249.99"
},
{
"id" : "2645",
"name" : "Suede Jacket",
"price" : "289.99"
},
...
]}
and your JS will look like this (if you're using jQuery)
JS
$.getJSON('ajaxPage.php', {'someVariable':'someValue'}, function(obj){
console.log(obj.count); //will show number of resulting items
console.log(obj[0].id); //will show id of first item (2643)
});
//If you do not use jQuery, you'll need to use eval() or something evil like that
//to convert the string to an object
This site has a great example regarding what you're trying to achieve. http://ditio.net/2008/07/17/php-json-and-javascript-usage/
In short you'll want to use php's json_encode() to convert an array into a json compatible string and each that back to the client.
If you're using jQuery then you'll need to dataType property of $.ajax() to "json", from there you can interact directly with the response as a json object.
If you're using the standard XmlHttp.
var json = JSON.parse(xmlHttp.responseText);
You can always return something like:
echo "code you need to send back to AJAX &&& response text"
Then you can subdivide it into 2 variables with text.split("&&&").
I want to update the web page based on ajax response received from a php script.
code inside php page :
// based on the logic either of the following three will be returned using ajax repsonse.
echo "<div align='center>Yahoo</div>";
echo "<div align='center>Rediff</div>";
echo "<div align='center>Google</div>";
The page which calls the ajax and receive the repsonse needs to perform some actions based on the returned response text.
Like , when the reponse includes "Yahoo" i need to execute some javascript functions....
when the reponse includes "Rediff" i need to perform some other javascript functions....
Currently i am using the javascript .indexOf function to search for "Yahoo" or "Rediff" in the ajax response and based on the return status of .indexOf() i am calling the functions i wish to execute.....
I feel i am not doing it in the right way ..... so thats why this question !!!
Can JSON be used in this case ??? [ just a tech thought :-) ]
i use json quite a lot for ajax apps, you could simply have a response such as
{
"response":"rediff",
}
then eval that, and get the .response value. works perfectly for me
the response from the php script would be the same as above, then (the way i interpret json) use
var resp = eval("("+req.responseText+")");
resp = resp.response;
resp will now return "rediff"
I'm trying to create a very simple message board (author, text, and date written) that will auto-update every few moments to see if a new message has arrived, and if it has, auto load the latest message(s).
I'm proficient in PHP, but my knowledge in AJAX is lacking.
The way I see it, I would have to create a PHP file called get_messages.php that would connect to a database and get through a $_GET variable return all posts beyond date X, and then I would somehow through jquery call this PHP file every few minutes with $_GET=current time?
Does this sound correct?
How would I got about requesting and returning the data to the web page asynchronously?
You're pretty close, you'll need a PHP script that can query the database for your results. Next, you'll want to transfigure those results into an array, and json_encode() them:
$results = getMyResults();
/* Assume this produce the following Array:
Array(
"id" => "128","authorid" => "12","posttime" => "12:53pm",
"comment" => "I completely agree! Stackoverflow FTW!"
);
*/
print json_encode($results);
/* We'll end up with the following JSON:
{
{"id":"128"},{"authorid":"12"},{"posttime":"12:53pm"},
{"comment":"I completely agree! Stackoverflow FTW!"}
}
*/
Once these results are in JSON format, you can better handle them with javascript. Using jQuery's ajax functionality, we can do the following:
setInterval("update()", 10000); /* Call server every 10 seconds */
function update() {
$.get("serverScript.php", {}, function (response) {
/* 'response' is our JSON */
alert(response.comment);
}, "json");
}
Now that you've got your data within javascript ('response'), you are free to use the information from the server.
Ignore the ASP.NET stuff, this link is a good start:
http://www.aspcode.net/Timed-Ajax-calls-with-JQuery-and-ASPNET.aspx
What you're going to use is a javascript function called setTimeout, which asynchronously calls a javascript function on an interval. From there, jQuery has a fancy function called "load" that will load the results of an AJAX call into a DIV or whatever element you're looking for. There are also numerous other ways to get jQuery to do alter the DOM the way you'd like.
There are a hundred ways to do this, but I'd say avoid writing plain Javascript to save yourself the headache of cross-browser functionality when you can.
I suggest you go for the Simple AJAX Code-Kit (SACK) available on Google code.
I've been using it since before it was on Google code. It's very light and straightforward. It's one js file that you have to include. I've seen it being used in online browser games as well.
http://code.google.com/p/tw-sack/
Example for loading page contents from get_messages.php in a div (if you don't care about the page contents from get_messages.php, and simply want to call the php file, simple remove the ajax.element line):
<script type="text/javascript" src="tw-sack.js"></script>
<script>
var ajax = new sack();
ajax.method = "GET"; // Can also be set to POST
ajax.element = 'my_messages'; // Remove to make a simple "ping" type of request
ajax.requestFile = "get_messages.php";
ajax.setVar("user_name","bobby");
ajax.setVar("other_variables","hello world");
ajax.setVar("time",dateObject.getTime());
ajax.onCompleted = whenCompleted;
ajax.runAJAX();
function whenCompleted(){
alert('completed');
}
</script>
<div id="my_messages">Loading...</div>
You don't need to specify an "ajax.element" if you want to do a simple "ping" type of request and ignore the output of the php file. All you have to do to implement your requirements now is to use a "setTimeout" making the ajax calls.
There are also many other options like:
//ajax.onLoading = whenLoading;
//ajax.onLoaded = whenLoaded;
//ajax.onInteractive = whenInteractive;
No need to learn or include huge frameworks. And you'll get started in no time with tw-sack.
I have a form in a PHP sending variables to a PHP file which duly inserts them into a MySQL table.
I currently have a div displaying the response from the PHP (which is anything that is printed by the PHP).
All works fine. The problem is I want to use variables that are created/updated during the PHP MySQL insert process. I.e. not only show what is printed in that PHP file, but USE those variables.
I have seen complicated use of the JSON Encoding to possibly cross this divide, but I'd love to know if that's the simplest approach. And if anyone has any good links or examples on the subject.
I assume that you want to be able to have multiple pieces of data sent back via AJAX to your page and manipulate those.
JSON is indeed the simplest way to do this. If you use PHP5, you can use json_encode() from the PHP side to send a complicated data type (such as an object or an array) back to the browser page. Then in the javascript, you use eval() on the data that is sent back (ex: var data = eval(response);) to parse it back into a usable complicated type in javascript.
There are tons of tutorials out there that will show you how to do this and explain it in further detail than a response here ever could.
Use PrototypeJS and do it like this:
Have some PHP like this
$jsonHeader = array();
if($_REQUEST['param1'])
{
echo '<p>You passed ' . $_REQUEST['param1'] . '</p>';
$jsonHeader['status'] = 'Success';
}else
{
$jsonHeader['status'] = 'Failed because the request was invalid';
}
if(is_array($jsonHeader) and sizeof($jsonHeader) > 0)
{
header('X-JSON: (' . json_encode($jsonHeader) . ')');
}
Then make your Ajax call like this
new Ajax.Request('dostuff.php', {
method: 'get',
parameters: {'param1': 'this is param 1'},
onSuccess: function(response, jsonHeader){
if(jsonHeader['status'] == 'Success'){
//Everything is OK, do stuff
}else{
alert(jsonHeader['status']);
}
},
onFailure: function(){
alert('Fail!');
}
});
Prototype grabs the X-JSON header returned by PHP and automatically sets the jsonHeader argument of the onSuccess function to a Javascript array of the values that were originally set in PHP.
The above scenario is good as long as the amount of data you're returning to Javascript fits in the HTTP header.
If you need to pass back lots of data, just have PHP output the JSON encoded result rather than making it part of the header. Then you can use the evalJSON() method of the response object in your Ajax call.
You do not have to just show what's 'printed in that PHP file', your PHP file could print JavaScript commends back to your page. You could then, upon receiving the response, execute those commands. I like to use the eval function for this, but many people here will discourage you from doing so :)
Just use the "echo" function to put put PHP variables to the standard output put.
echo $myVarName;
Or, I prefer the printf(), be sure to check for HTML in the input BEFORE you output to avoid XSS issues.
Use something like this:
printf("Your input was: %s", strip_tags(%myInputVar));
Also, remember to use the %d or %f formatters when outputting number for best security.