A few weeks ago, I demonstrated how to make AJAX requests with raw JavaScript. In today’s screencast, we’ll take things a step further as we use PHP to query a database, convert it to the JSON format, and use Javascript to asynchronously request this information and display it on the page. If you’re just getting started with these sorts of concepts, this is the perfect video for you!
Video
After a bit of discussion on Twitter, I updated some of the PHP from this video.
You can view the revisions below.
Final “Load” Script
This block of code asynchronously requests a page, and then uses Douglass Crockford’s “Parse” script to create a new global object. That way, we can easily filter through the returned JSON data.
function load(url, callback) {
var xhr;
if(typeof XMLHttpRequest !== 'undefined') xhr = new XMLHttpRequest();
else {
var versions = ["Microsoft.XmlHttp",
"MSXML2.XmlHttp",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.5.0"];
for(var i = 0, len = versions.length; i < len; i++) {
try {
xhr = new ActiveXObject(versions[i]);
break;
}
catch(e){}
} // end for
}
xhr.onreadystatechange = function() {
if((xhr.readyState < 4) || xhr.status !== 200) return;
callback(xhr);
};
xhr.open('GET', url, true);
xhr.send('');
}
load('emails.php', function(xhr) {
var response = JSON.parse(xhr.responseText);
var container = document.getElementById('container');
for(var i = 0, len = response.length; i < len; i++) {
container.innerHTML += '
Final PHP
Slightly modified from the video to improve efficiency — a much more elegant solution than what I originally came up with on the spot.
<?php
/*
Step 1: query the database
Step 2: Cycle through the returned data and convert it to the JSON format.
Step 3: Echo returned data -- to be retrieved with Javascript
*/
$mysql = new mysqli('localhost','root','root','ajaxTut') or die('There was a problem');
if($result = $mysql->query('SELECT * FROM contactInfo')) {
$returnedArray = array();
while($row = $result->fetch_object()) {
$returnedArray[] = $row;
}
echo json_encode($returnedArray);
} else {
// error occurred
echo 'error: ' . $mysql->error;
}
I hope you all are enjoying this “video series that was never meant to be.” Originally, it was planned as a single tutorial; however, due to the fact that there is SO much to cover, I’d like to continue creating more videos for you — that is, if you’ll have them. Feel free to let me know what you’d like to learn next.
- Follow us on Twitter, or subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.








Ist One in !
Hey Jeff thanks for the Netbeans Twilight Theme I just finished converting it to Geany and its great!
Great! Thanks so much.
hey, Napoleon. how to create theme for geany??
Thanks for the screencast I will watch it ASAP.
many thanks jeff
wonderful nice to watch a new screen cast
Much better now! %) Good work!
Definitely. Good work to you too.
Great basic tutorials. More of this would be appreciated.
Thanks
Very useful. Thanks for a great tutorial.
Great work. Thanks.
Don’t have time right now, but i am going to watch all of these.
Thank you very much Nettuts + Jeffrey Way
Can anyone tell me what is the best way to render the data from DB? What is the best practice?
1) Using PHP to create all the DOM elements first and then just pass them to Javascript using innerHTML ?
2) Assemble whole DOM elements using Javascript with just raw data from DB ?
Which is the beast way or what are the differences? I’m more familiar with PHP so I create all the elements using PHP code and then just pas them via JS
Thank you!
Second variant probably will be faster.
It depends on how many changes to the DOM you’re making. For small DOM changes, either way is fine. For large DOM changes, innerHTML is faster than creating the same structure with DOM methods.
Another option you can consider is to use JS library to render your HTML on the browser. You can have a look at PURE http://beebole.com/pure
Great tut, and am looking forward to part 3! Would love to see you create a simple app with all this in the next one.
Another great tutorial, thanks.
I’ve not had any experience with JSON so this has been inspirational.
Do you think building the response in XML would be easier to process on the client side rather than using JSON and the parser script?
Thanks so much for these tutorials! I really learn a lot!
Excellent second part. This is a great reference to me because I don’t have any experience with JSON. Thanks.
I have the same criticism as the first part of the series. The versions array in its current form always uses Microsoft’s first version of XmlHttp. Reversing the elements allows the latest version installed on the user’s computer to be used.
You could also take it one step further and only check for versions 3 and 6, as per Microsoft’s XML team:
http://blogs.msdn.com/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx
Don’t you think that a JSONP call would be simpler?
Security is not an issue as you call the same domain and as you have the hand on the server you can wrap the response in a JS callback function.
Unfortunately I didn’t see the 1st part…. yet. I’ll check both, thanks!
Jeff thanks for great clear tut, on a slight aside I wonder if anyone can help a designer struggling with a bit of jquery syntax, basically I want jquery to look for value in a submitted input field and if that value is equal to a specified value then do something, elsee do nothing. Any advice greatly appreciated.
var value = $(‘input:submit’).val();
if(value === ’some string’) {
console.log(‘wahoo’);
}
Maybe something similar to that?
I heard you say in this movie, or in part 1: jquery will not be there for ever, what do you mean with that?
I mean that technologies will come and go. Prototype was a the huge JS framework years ago. That’s obviously not the case anymore. That’s all I meant.
IMO, its still way better to rely on jQuery instead of the raw javascript stuff. You can be sure that the .ajax() call works and use its result, instead of strugling around with code you do not need to know.
Isn’t that what a framework is originally made for? To keep you away from implementation questions…
Well, beside that, thanks for the tut!
I just wanted to post an emails.cfm and index.cfm for those who are interested in a Coldfusion version. You will have to create a db with the same fields as in Jeff’s tutorial in order for this to work.
index.cfm
INSERT INTO contactInfo (name,email)
VALUES (,)
Add New
function load(url, callback) {
var xhr;
if(typeof XMLHttpRequest !== ‘undefined’) xhr = new XMLHttpRequest();
else {
var versions = ["Microsoft.XmlHttp",
"MSXML2.XmlHttp",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.5.0"];
for(var i = 0, len = versions.length; i < len; i++) {
try {
xhr = new ActiveXObject(versions[i]);
break;
}
catch(e){}
} // end for
}
xhr.onreadystatechange = function() {
if((xhr.readyState < 4) || xhr.status !== 200) return;
callback(xhr);
};
xhr.open(‘GET’, url, true);
xhr.send(”);
}
load(‘emails.cfm’, function(xhr) {
var response = JSON.parse(xhr.responseText);
var container = document.getElementById(‘container’);
var vals = response.DATA;
var cols = response.COLUMNS;
var colMap = new Object();
for(var i = 0, len = cols.length; i < len; i++){
colMap[cols[i]] = i;
}
for(var i = 0, len = vals.length; i < len; i++){
container.innerHTML += ‘‘ + vals[i][colMap["NAME"]] + ‘ : ‘ + vals[i][colMap["EMAIL"]] + ”;
}
});
emails.cfm
SELECT * FROM contactInfo
#getEmails()#
Thanks for showing the innards! I really enjoyed both of the videos, clear and precise instruction.
<- new fan
A suggestion for this video:
in the PHP script, have the “Content-Type” header be “text/javascript”, like “header(‘Content-Type: text/javascript’);”
A suggestion for the next video:
How to use XML for the data instead if JSON.
I’ve never used JSON before, but it does seem pretty handy for returning data from the database. If there was a double quote in the data, would the json_encode function automatically escape it? I’m also wondering if there is a better way to return data. Text, CSV, XML could be used, but in the end I guess it comes down to what is parsing on the client side. Is JSON fastest/best?
What about: $result = “[ " . implode( ",", $construct ) . " ]“; ? Thats easier than the if(…) echo “,” …
Hi,
Would anyone be able to help, I want to turn Jeffrey’s example into a multi-page form. I need to build a survey with various question and answer pages.
My method would be to pass the Last ID created by the insert statement on the first (start) page into a session variable in the second page and then use that session variable to update (via an update stmt statement) that particular id’s record fields.
I have managed to create the stmt statement for the insert however, I am having trouble creating a stmt statement for the update query, which references the id stored in the session variable.
Would anyone be able to help please.
I should have commented the code, but I wanted to explain something regarding the 2 for loops at the end of the script. Coldfusion returns DATA and COLUMNS and does not return the JSON in the format the script expected. I seen an example a long time ago on Ray Camden’s website where he showed how to convert the Query into a JSON string for Javascript. I thought it was a good technique and went with it for my example.