Why use AJAX for dynamic web pages when you can do it only with php?
-
1For instance, the index.php page of the site, can just switch the content of the body via only php? So why even bother with AJAX?dave– dave2011-04-02 20:43:42 +00:00Commented Apr 2, 2011 at 20:43
-
2It can't, though. PHP can certainly deliver a different page on refresh, but the browser will have to load the whole page again. And how do you propose to do something like Facebook Chat without AJAX?Christian Mann– Christian Mann2011-04-02 20:47:47 +00:00Commented Apr 2, 2011 at 20:47
-
You can't do it only with PHP, that's why AJAX exists.Pekka– Pekka2011-04-02 20:48:52 +00:00Commented Apr 2, 2011 at 20:48
-
5The term dynamic is used in two different contexts here. PHP is creating the content dynamically whereas one can say that Ajax is loading the content dynamically. E.g. you can use Ajax to load content created by PHP. They work together, they are not exclusive.Felix Kling– Felix Kling2011-04-02 20:53:29 +00:00Commented Apr 2, 2011 at 20:53
3 Answers
The main reason to bother with AJAX is User Experience (UX).
Now AJAX won't necessarily improve UX in every single instance so in a lot of places sticking with pure PHP is perfectly okay.
But imagine the case where you have a text field on the site and a link to vote on something. Kinda like this site. When you add AJAX your users won't loose the text they entered in the textfield when they decide to vote on the link! How incredibly useful!
So if you care about your user's experience it is a good idea to use AJAX in situations like that.
6 Comments
PHP creates and outputs the Content to the Client Browser as it's a Server-Side Language and that's what it was built for, so on a request your code will access database, files etc. and then output the constructed html/text to the client.
Ajax just gives the User a more Desktop like feel. For example deleting a record and instead of the entire page reloading just letting the one element disappear from say a list and letting the server know that the record is to be deleted. But Remember to let the User know when you are busy sending data to the server (With a progress bar in .gif format for example). As lot's of user feel that if nothing happens on the screen to notify them, that the application is frozen which means they will either reload the page or just try to click the button again.
But you will need to provide some sort of compatibility with browsers that have Javascript disable and thus cannot use your AJAX functions, just something to keep in mind.
2 Comments
AJAX stands for Asynchronus Javascript and XML, meaning that a page can get new data, without having to reload a page.
PHP cannot send data without reloading the whole page. A user has to press a button, to send data.
An example of AJAX is for example google suggestions or the tag suggestions on this website.