Help changing content on the page using both php and javascript - php

So I am trying to have a dynamic tabs kind of thing using both php and javascript. To make it much easier to understand, remember the two choices on facebook (Recent news and most recent) or something like that, when you click on one of them it just changes the content that you see in the middle without updating the page. i know how to delete the content in a div for example, but after deleting the content in the div (innerHTML = "") I want to populate it with the option chosen from the database.
So let's say I have an option (all) and an option (only this)
The default is all so when I run the page, I will just get all. However, if I click on only this, it will clear the div "my header" and will replace the content with the latest content from the database (database) and display it.
For that I need both php and javascript, is there a sample or an easy way to do this before i start digging around.
((Sorry if is not clear but the facebook example should be clear enough))

Whatyou are looking for a is AJAX/PHP approach.
Clicking on the tab
The current content gets removed. This is possible because it has a unique "id" attribute in the HTML code
The server is asked for the new content. This is the AJAX request that will be triggered after/while/... the content is removed.
The server sends back the code. This can be HTML, JSON, XML or similar.
You script recieves the answer, may "do" something with it (like some parsing or similar)
The content will be placed on the page (again, this is possible due to an unique "id"
This is basically the way it is done.
Check out the different JavaScript frameworks. They all come with nice AJAX support:
jQuery
MooTools
dojo
Prototype
And of course, SO is also a nice place to look at: https://stackoverflow.com/questions/tagged/ajax+php

What you're talking about is ajax.
I would suggest a javascript library to help leverage this, like jquery.
It can be as cool as
$.post('serverScript.php',
function(data) {
$('#idOfDivToUpdate').html(data); //shove script data into div
},'html' );
tutorial.

Related

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).

Can't post data to self because of design

i have a website that uses a number of containers (div's). In this scenario, we have three boxes down the left side and one bigger box on the right of these boxes. The bigger box on the right is the only thing that changes when a link is pressed, this is done with Javascript.
SO i have the index which is the main layout of the website and i also have the "pages" of the site, so when a link is pressed the main box (on the right) loads the new data.
On one of my pages i want to collect data and then run it through a PHP script that is in the head of the file, but when i click the button i realise it refreshes the whole page and it doesn't run the script on the page with the form.
Anyone had a problem like this, or know of something i could do to work around it?
I'm not really sure what code would be useful for helping me but if you need something just ask.
Thanks for the help
Since you are loading all your content via JS already, you could just POST the form data via AJAX to a PHP script to process, then read the output and either provide an error message or remove the form from the page and show your success message.
How to approach your AJAX call is dependant on what you've used as a basis for the rest of your JS.
Personally I like to use the JQuery library, as it makes AJAX calls (and much more) very simple.
How about you make the page design able to do it. Have the backend be able to spit out the state of the page when it posted.
Or use Ajax to post the data back and set the new state like you do already.

PHP - Allow users to vote without loading another page/reloading the current page

I want to put Thumbs up/Thumbs down buttons on my website.
There will be quite a few of them displayed at once, so I don't want to have to do a POST and reload the page every time the user clicks on one.
I thought of using re-skinned radio buttons to choose Thumbs up/Thumbs down, but that would require the user to click a submit button.
So how do I do this? I am open to using JavaScript or some other form of Client-Side scripting, so long as it is built in to most/all web browsers.
Thanks!
YM
I would take a look at using jQuery, http://jquery.com/ It is a WIDELY used library and there is tons of support for it both here and # jQuery's website.
You could easily assign all those thumbs to do an ajax post to a save page with the correct id and the user would not know the difference
You're definitely going to need to use JavaScript on this. Well, there are other client-side languages that could technically do the job (ActionScript, for example), but JavaScript is definitely the best way to go.
Look into AJAX (Asynchronous JavaScript And XML). This is just a buzzwordy way of saying use the XMLHttpRequest() object to make page requests with JavaScript without reloading the page. Here's a good tutorial: http://www.w3schools.com/ajax/default.asp . Note that, despite the word "XML" being in the title, you don't have to use XML at all, and in many cases you won't.
What you'll basically do is this:
Have your thumbs-up and thumbs-down buttons linked to a JavaScript function (passing in whether it's a like or dislike via a function argument).
In that function, send a request to another page you create (a PHP script) which records the like/dislike. Optionally, you can have the PHP script echo out the new vote totals.
(optional) If you decided to have your PHP script output the new results, you can read that into JavaScript. You'll get the exact text of the PHP script's page output, so plan ahead according to that -- you can have the PHP script output the new vote totals in a user-friendly way and then just have your JavaScript replace a particular div with that output, for example.

Best way for a dynamic box

Hello guys I newbie question :) - I am currently using PHP/Zend and now I need to display a form and other content in one of my pages. I do not want the page to reload and I cant use a pop-up window so the best option is to sort of dynamic display a "square" in the middle of the current page with this form being load on the go... this way i could have my pages (forms, text, whatever) being pulled in this square.
In order to keep compatibility with older/new and different browsers, what would be the best choice? DOJO - that is already in Zend, JQuery, or just HTML5/CSS3? Besides, if anyone could point me to some references of where can I find this info it would be great!
AJAX is the most common means (Asynchronous Javascript And Xml) to do this- which uses Javascript to poll other scripts (can be .php pages) which then return predefined output based on the request- this output can be content to inject into a page, or data which can then be interpreted by your page for another action (i.e. the output from another page etc..).
In this instance, your .php page could include JS (javascript) in the head, whether linked or inline, which would contain details for launching an AJAX request- namely, how often or on what trigger (button press etc), by what means (POST or GET), what is sent (any other variables you wish), what the target script is (the script which will handle the request and output your required content/data), and what to do when the response is recieved (i.e. which element on the page should be updated with the response).
A little about AJAX:
http://webdesign.about.com/od/ajax/a/aa101705.htm
http://webtrends.about.com/od/web20/a/what-is-ajax.htm
Likely the simplest way to begin is to use a pre-existing Javascript library like the ubiquitous jQuery (jquery.com), there are thousands of tutorials out there for it, and though you will need to do some Javascript programming, the library has meant that you can rely on fairly simple syntax to do so (as simple as $('#myelement').load('mypage.php')):
http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/
http://www.devirtuoso.com/2009/07/beginners-guide-to-using-ajax-with-jquery/
http://www.sitepoint.com/ajax-jquery/
http://yensdesign.com/2008/12/how-to-load-content-via-ajax-in-jquery/
In simple terms:
You have your php page with the element (area) that needs updating (page A)
Build another php script which outputs the content you want 'refreshing', e.g. the latest news stories, each time it is run (page B)
Link to the jQuery library in your header section (page A)
Write a simple jquery function in the header section of page A, which says every X seconds/minutes (or on demand), run an AJAX request to fetch the content of page B and insert into an element (DIV) within page A
---updated---
If you wish to use DOJO as opposed to jQuery, there is also a wealth of resources available:
http://dojotoolkit.org/documentation/tutorials/1.6/ajax/
http://www.infernodevelopment.com/dojo-ajax-tutorial
http://startdojo.com/2010/01/02/simple-ajax-form-tutorial/
http://today.java.net/pub/a/today/2006/04/27/building-ajax-with-dojo-and-json.html
http://www.ibm.com/developerworks/web/tutorials/wa-dojotoolkit/index.html
http://www.roseindia.net/dojo/

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.

Categories