When to use AJAX - php

Let's say we have a page written in PHP. This page loads by it self a template with header, body and footer and print this out. Now let's say that in the body of this page we would like to start a loop and load some posts (messages taken from a database).
We also need the page to load new posts every 10 seconds, if any, without refreshing the page (classic AJAX). This ajax call will use JSON and AJAX and micro templates.
Now i'm just wondering:
Do we really need PHP to load posts the first time the page is loaded? Can't we just start that Ajax call and load posts with Ajax instead? (Notice that the existing ajax call would be kept as it is, since it loads posts starting from the latest loaded (in case of no posts, that would mean all posts).
If you did not understand my question don't hesitate to let me know.

In this situation I think the simpler approach is the let AJAX handle it, if you do let php load the initial messages, you'll have two places in code, that you'll need to maintain to perform identical jobs.

I think you are asking how you should load the posts the first time the page is accessed. If so: When the page firsts loads, have some PHP that prints out the existing posts. Then, add some JavaScript to update the page with new posts every 10 seconds. This is a matter of preference. You might want there to be no posts when the page first loads, and then use Ajax to get the existing posts once your page has loaded.
Edit:
I agree with jondavidjohn that you might be better off using pure Ajax. However, you could always isolate the code that fetches the pages into a separate function. That way, the script that generates the page calls the same function as the script that is called via Ajax.

The drawback with that technique is that it doesn't downgrade gracefully. So people with javascript disabled will not see any posts.

I'd recommend outputting some data with php - AJAX requires JavaScript which many people don't have activated.

Why not, instead of having the browser poll the server for new posts, have the browser push new content to the browser when it is available using the likes of node.js?

I designed my site with AJAX exclusively, and it works perfectly except for one rather major issue: Using AJAX requires JS to be enabled. Of course, if users trust your site, this is not a problem, but if they don't, then an AJAX solution won't work unless you put the entire page in a noscript tag.

Related

Refresh a DIV with AJAX that requires MySQL queries + PHP

I am currently working on a website that is coded primarily with PHP/MySQL and HTML5 as a means to learn the code and become better. I used to work for a forum that used AJAX to reload the latest posts as if the user had just refreshed the webpage, except it just changed the content dynamically without a full reload.
My webpage: http://vgrnews.com
My specific situation is as follows: The homepage loads the four latest announcements and (soon to be) comments from the MySQL DB and displays them soonest -> latest. It is inside of a div called maincontent.
What I want to do: Have the announcements show up dynamically with AJAX regardless of the user refreshing or not. It would probably poll the server roughly every 5-10 seconds.
I don't plan to keep the homepage refreshing like that, but once I add more content it would be good to know how to refresh a div at regular intervals. I have read up on AJAX, but I don't quite understand all of the logistics, they just give you the code and expect you to pick it up. It is hard to morph the code to be applicable for my website if I don't understand it.
Sorry for the long read and thanks for all the replies!
function reload_content() {
$('#latest_post').load('ajax/get_latest.php');
}
window.setInterval(reload_content, 10000);
I will clarify on Alexander's answer for you. What the load() function is doing is performing an AJAX request to the given URL, and then setting the HTML of the selected div(s) to be the returned content. This means that your server should return proper HTML (and only the HTML you want in that div).
You can see http://api.jquery.com/load/ for more information on load().
If you plan on having your server return an JSON (or XML) representation of the information, you will have to use a jQuery get() (http://api.jquery.com/get/), and then process the returned data with a callback.
Note that both get() and load() are simply implicit applications of the jQuery ajax() method (http://api.jquery.com/jQuery.ajax/)
EDIT:
The setTimeout is just making the browser call the function ever x milliseconds. This is what will have it check every x seconds.

Using Ajax to flush obflush

Ok so I have created a wizard and everything works great. But I have one little piece that seems to 'bother' me if you will.
In the last step of the wizard I build, it uses obflush to process data onto the screen
to show some actions happening. But the problem with that is, that the 'entire' page doesn't load until the obflush process is done, and then the page all lines up nicely and such.
Im wondering if there is such a way that maybe ajax can flush the obflush process?
Maybe this is completely wrong but this is how I can envision it happening.
User goes thru the wizard and gets to the final page
The entire page loads
At the end of the page is some ajax code to apply to a tag maybe
The ajax is refreshing itself every second to check against the update of the obflush and then outputting what the obflush has outputted to the screen.
Does that make sense?
Any insight is greatly appreciated.
Thanks
This question is about how to load part of a web page with Ajax. In particular, how to load the structure of a page, and then fill in the details with Ajax calls.
I assume the intention is for the structure to be loaded quickly because it does actually have some content, and then load parts of the page that take a long time to process. Otherwise the effect on screen will be that loading is actually slower.
I would use the JavaScript library jQuery to help with this, although it can be done without any libraries as shown in this question.
The browser makes a web page request and the server responds like it would normally, but just with the structure of the page
Within the basically empty page that was loaded, jQuery will then make an Ajax call with load() that will load the response from a URL into the specified HTML section.
The code would look like this, where my-intro-div is the id of a regular HTML div tag:
$(function() {
var myIntroDiv = $('#my-intro-div');
myIntroDiv.load('/my_intro_div.php');
});
The PHP script my_intro_div.php returns the HTML that is meant to be displayed inside the my-intro-div tag
There are some good examples in the jQuery documentation here:
http://api.jquery.com/load/
jQuery can help with a tonne of other things too. It has a tiny learning curve that can be a little steep, but after that I've found that it is the most intuitive "language" I work with.

OnHover run php script

Okay I'm not really sure how to approach this. I have a user-generated post board where people post, it drops down onto a list of a bunch of posts. When you click on the ID number of the post it will bring you to a separate page with just that post and the comments on the post. I want it so when you hover over the href it drops down something that tells the user there are x amount of comments on this post. This way people know if there is comments without switching pages and also being able to be able to click the href still and go to the postid page.
I assume some ajax/jquery/javascript would be used to accomplish this but since I'm fairly new to ajax and jquery I'm not certain how this would be done. Thank you!
For a hover effect, it would be better if that information was already stored on the page and just hidden. Then when the user does hover, you can just un-hide it and have it positioned where you want, and then hide it again when their mouse leaves the area. Using AJAX requests for this purpose would waste away a lot of HTTP requests for such a tiny amount of information.
Really, you could do the hover effect using pure CSS if you wanted too (I would).
Since a hover happens fairly often, I wouldn't use it as the default event to fire an AJAX-request. This would increase the HTTP-traffic enormous. See if you can fetch this information when the page is build (and put it in then) or use something else like a "preview"-button for the event.
Anyways, this would be the basic workflow if you want/need to use AJAX:
Write a PHP-script (or any other language you use) which fetches the number of comments (and what else you want to display) from the database (or where your data is stored).
This script should then be called via AJAX (with $.ajax() from jQuery for example). As the expected return-type you would then use json.
The script which fetches your data would then create an object, use PHP's json_encode()-function to encode this object to JSON and echo it out.
This JSON-object will then be available in the success-method of the ajax()-method from jQuery. Then, you can access its members (e.g. the comment-count).

Send a post with PHP + AJAX

Context
I'm working on a project that I'd like to make more dynamic with PHP + AJAX.
I'm using jQuery for the AJAX part because I totally suck in Javascript, and anyway it seems to be worth something.
I reached a point where my application needs to use a form to send a post, and I want to use an ajax call to perform this action. In the page I'd like to send the post, there is also a list of the most recent 15 posts submitted.
First question: Should I just forget about it and use just PHP?
The action
The user writes something in the <textarea></textarea> and clicks on a <a id="myPostSubmit">Submit</a> that is the handler that I'll manage on the jQuery script with something like $("#myPostSubmit").live('click', function() { /* here i make the ajax call */ });. If the post is successfully submitted we are going to do something (I'll talk about it in the next section), either we will alert the user using my showAlert(text) function, that shows a black box for 4 seconds with the text in it.
Second question: Should I manage the click event in any other ways? Should I create a function, such as sendpost(post) and attach it into the HTML onclick="" event?
If the post is successfully sent
I'd open a discussion about 2 options:
We refresh the page [not actually
loading the entire page but making
another ajax call that retrieves the
posts lists and makes disappear the
old one, load the PHP file to
retrieve the new posts (including
the one we just sent), and then make
the post list appear]. Pro: 1) We are sure that what the user is reading after the post list is loaded is the real post sent. So it actually double checks the action. 2) We load also some possible posts sent in the mean while. Cons: 1) We have to create a PHP file that gets the post list template, slicing the template of that page in 2 files. 2) It doesn't really seems that smooth to me.
We just use Javascript to get the post template, add it to the list. Pro: 1) We make it really smooth, without reloading the entire page. 2) We don't need of any PHP file to reload the page. We just use Javascript (jQuery). Cons: 1) How do we get the post html template to add it to the list? 2) How do we get the user (logged) informations without PHP?
Third question: Is it better the 1st or the 2nd solution? Would you provide a even better 3rd solution?
The PHP page
The PHP page that will receive this AJAX call is : ?p=action&a=sendpost. The page require $_POST['myMessage'] to be set and not empty and nothing else. The page itself will get all the user infos from the cookies and will manage to perform the needed query.
The application
It is divided in 3 parts: App, Template, Library. Basically each page of the application has its own .app.php and .tpl.php file.
The .app.php file manages the building
of the basis of the page, using classes
and other stuff from the library. In
our case it retrieves datas from the
database and put them into
variable.
The Template is called at the end of the .app.php file. The .app.php file send to the template the retrieved data and the .tpl.php file outputs them.
The library is used to contain the classes and functions we need in the application file.
Fourth question: Is this a good way of manage my web application?
Edit: What about returning the alert message to the user?
I read about an option, inside $.ajax() that will manage the response on success or in error. The documentation about it is very simple and I didn't get it.
Fifth question: How should I return (from the PHP file) the error
or the success?
First question: Should i just forget about it and use just PHP?
Well, you application will relay on JavaScript if you use ajax, this days i think it just fine ;)
Second question: Should i manage the click event in any other ways? Should i create a function, such as sendpost(post) and attach it into the HTML onclick="" event?
Create a function and bind onclick. Code will be more readable ;)
Third question: Is it better the 1st or the 2nd solution? Would you provide a even better 3rd solution?
My solution: ajax submit the form and on callback insert new comment in to the list or display error message if user can't comment.
Check jQuery serilize() for submitting forms data with ajax.
Fourth question: Is this a good way of manage my web application?
It's just fine ;) When you application get's bigger you will have to redesign it, but don't do it know, do it when current solution becomes to hard to work with.
Read some good book on building MVC framework. And on programming patterns in general.
You seem to be on the right track with everything. There are lot of opinions called "best practices" about how to exactly attach event handlers, how to reload the data on the page and how to organize your application, etc, but I personally would rather build more software instead of worrying about details like that. The details will come to you eventually.
I personally find that updating whole chunks of server-side-rendered HTML on the page is more robust solution, but I have seen people getting excellent results with templates.

Refresh PHP include()

What is the best way to refresh the content of a var that is included? For example, I have this code:
<marquee>
<?php
include('note.php');
?>
</marquee>
This is great, as I can show on the page the contents of note.php. Say I change note.php but I don't want users refreshing to see the changes...is there any way to refresh the included file every 3 minutes for example?
To refresh only a portion of a page, you'll have to use some kind of Ajax Request : once the page has been sent to the browser, the server has done it's job, and cannot modify is anymore : the request of fetching a new portion of the page as to come from the browser.
You could do some Ajax requesting "by hand", it's not that hard ; but I'd rather suggest that you take a look at some of the great javascript frameworks that exists out there -- that might be helpful in the future, when adding more functionnalities to your application.
For instance :
With prototype, you can use Ajax.PeriodicalUpdater
Or, with jQuery, you could use something based on $.load
Only by using an ajax like call.. take a look at prototype or jquery for decent JS libraries to help with this..
Unless you just want to put some javascript in to refresh the page every three minutes, you'll need to look into another technology, namely AJAX. As far as I know, PHP can not do this alone.

Categories