views:

46

answers:

1

I'm totally new to ajax, but pretty good with PHP. I have a PHP page which currently refreshes every 2 minutes because it has to check for new data in the sql database. It's pretty annoying if you're using it and it keeps refreshing. The database is updated about 3 times a day, but what is shown on that page needs to be kept current with what's in the database. I'm trying to find a way to have ajax or something check the database every 30 seconds or so, and if there is something new, then refresh, but if there isn't anything new don't refresh. Does anyone know of any tutorials out there, or something that can get me started? I have the concept down I think... I just can't figure out the code. I'm sure if I get it to check the database I can figure out the rest.

Thanks in advance!

+2  A: 

Check out jQuery. It makes it super easy to retrieve a remote resource in the background: $.get(url, callback). The contents of the page should be in either XML or JSON. I suppose you already know how to generate these using PHP.

Once you've retrieved your updates (or lack thereof), you can decide what to do with it. Again, with jQuery it's very easy to append to or replace the contents of any part of the page, without ever refreshing anything. $("#id").html(new_html)

And that's just the beginning. You can do a lot more than that. Welcome to the world of AJAX!

Of course, you can do AJAX with vanilla JavaScript. But then you have to account for all the different browser perks, so I highly recommend using a framework such as jQuery. It also comes with a pretty comprehensive online documentation and some examples, so try them out.

kijin
Hmm ok... jquery could be a possibility. I was looking up tutorials, and I can only find stuff about how to ping the database to find if a user exists... do you have any suggestions on where to look?
Phil
@Phil Write a page in PHP that checks the database and returns new results via XML or JSON. Then just use jquery.load() to replace the HTML in your container with the new data.
scottm
@Phil scottm's suggestion nails it. I should have suggested `$.load()` too. No need to do anything fancy on the server side. Just return the new contents of the `<div>` that you want to update, as if it were a regular HTML page, but without the header/footer/other stuff. `$.load()` will automatically update the div with the new contents.
kijin
ok thanks... I'll have to work on that.
Phil
The only problem I see with that though, is that I'm also using the google maps api on the page, and that will change with new content so I will have to do a full page refresh, rather than just individual pieces
Phil
@Phil You can update the map separately, or at the same time as you update your other content. A rule of thumb: if what you're trying to update is anything less than the whole page, you can update it without refreshing the whole page.
kijin