How to make PHP pages dynamic? - php

I recently created a website where a user logs in and accesses various forms and other things. I was wondering, after login, how can I change the php code so that it automatically modifies a portion of the page making it personal? Here is a screen shot of the front end.
I would like the login form portion disappear and then have a new layout replace it. Would I use Javascript or AJAX. If either, does anyone have any guidance on how to go about doing this project?

It sounds like one of your goals is to minimize page refreshes, possibly having none at all.
Your main challenges include:
1. Managing possibly lots of unrelated DIVs, which make up your functional segments.
2. Speed issues - lots of code crammed into one page.
3. All input sent asynchronously (things get complicated very fast when you want to do EVERYTHING with AJAX!)
As far as your initial login menu, you can fade that out by wrapping it in a DIV and calling jQuery's fadeOut() function on it. To update PHP components without refresh, that's where your AJAX comes in. You're going to want to use a little of each and like therealsix said, they're all essentially Javascipt at the core.
My best advice would be to spend a big chunk of your time dedicated to this project in the planning stage. Understand how you are going to deal with DIVs crashing into each other. Develop an overall table layout that gives you flexibility concerning where content DIVs come in and out. Think about which ones are replaceable at any given time. Study up on modular coding.
That's broad advice because I don't know what exactly the project entails, so if you have any specific issues, let me know.

I would say neither. If you're going to change the whole page, just redirect to a new page.
If you needed to do this without a page reload you would need to use javascript and AJAX (ajax in some sense is javascript). Then I would recommend you look at the jquery functions (http://api.jquery.com/load/)

Related

Best way to load data from MySQL with PHP and Javascript

Looking at other questions, none seem to be specific enough for my case. I am creating a blog-like website and have created a user-authenticated page that allows me to add a title, main content, and image using a form that is sent to a php file that stores the data in the mySQL database. Then, the php redirects me to the index page where I want to load the latest blog post along with all previous posts and put them in a div with styling. I do not think I need AJAX for this. I only need the data to load per each visit, therefore, is the best thing for me to do is to call a javascript function on $(document).ready() that will access the data in the database? If so, how can I implement PHP in my javascript to work with the database and then store the info in javascript variables.
Thanks
You certainly don't need AJAX for this. Just use your index.php page to look up the blog posts in the db and then loop through and echo them out.
You could later incorporate AJAX to call a php page which would provide the blog posts to you. This way you could update the page after it is loaded when new blog posts are created.
Hope that helps.
Clearly you do not seem to have a firm grasp on the role of each language. If you're building something on your own follow the advice of someone who has built ALL of it and can show it off to boot (see my profile, my site contains a blog, forums, private messaging, chat room, CMS, etc all built entirely by myself using no one else's code).
(X)HTML - It's the noun language, an image, a paragraph, a division element used by CSS to style the page, etc.
CSS - The adjective language, describes how the (X)HTML noun language is displayed.
JavaScript - The verb language, event driven; when the user does (onmouseover, onclick, onload, etc) action execute this code (usually a function). AJAX is simply loading content after the page has finished loading. You can worry about the fancy stuff once you have your basics working.
PHP - Server side language, prepares code (mostly XHTML) to be sent to the client's computer.
Database - Where your content is stored.
"$(document).ready() " is not JavaScript, that's jQuery. If you want to learn stay as far away from JavaScript libraries and learn REAL JavaScript otherwise you're going to run in to the nightmares associated with it (crap performance versus native JavaScript, updating libraries changes how you must code to them, etc). Feel free to look at my site's source code as it's all written for XHTML as application/xhtml+xml which means it WILL work in regular HTML though the vast majority of sites do NOT work if you switch them to XHTML. In other words when you code right the first time you'll have much more confidence that it will JUST WORK end of story. People don't care about how you did it but that it works and if it ALWAYS works then they simply can't get any happier with what they have.
If you're building the main blog page you simply need a single SQL query to pull all the content. My blog I programmed to display the last eight latest blog entries though with my pagination it's exactly like a book, the first page (on the left side) starts with the first eight, so if the count isn't divisible by eight you might see six entries on the latest page.
When using SQL you want to CONSTRUCT your query, NEVER stick it inside of a loop! The fewer queries you execute the better your code is and the better your performance. I recommend downloading MySQL Workbench and setting up a MySQL query log and then use Tail for Win32 to view queries in real time to see what your code is doing.
Apache also has logs. You are building this LOCALLY at http:// localhost/ first correct? You should never test something live until you've exhausted testing it locally first. See my base element blog entry about how to best do that...
http://www.jabcreations.com/blog/streamlining-local-and-live-development-with-the-base-element
If you're talking about redirects keep the technical stuff hidden from users and take advantage of $_SESSIONS in PHP. Record what the current page URL is (relative to the base which is different for local/local network/live environments), have a second-URL to fall back to and if that too matches the redirect page then have a safe-URL that is statically defined. If you're constantly falling back to the static URL then check to make sure you haven't goofed up how your other two variables are being updated each page load (such as not updating it if you're on the redirect page obviously).
When you solidify your basic understanding you will want to ask very specific questions as your question is wildly subjective and to most programmers not really worth answering. Make sure you use correct terminology, stick to core languages and not libraries as doing so will help ensure your working code will last that much longer. The stricter your coding practices the better off you'll be. Maximize the sensitivity of your error reporting for HTTP, JavaScript, PHP and SQL errors. Getting PHP is not set errors? What if a hacker is trying to pry error messages from your code? Make sure those variables are set before you even begin to start working with them. Log your errors and fix them fanatically. Don't try to add every feature in the world, concentrate on the critical functionality first and make sure it's incontestably solid before you expand upon it. Do these things and while it may take more time up front you will be rocking harder than the vast majority of people drowning in live environments that are built on not solid code.
gizmovation is right, you don't need AJAX, but to answer the question "how can I implement PHP in my javascript to..."
You're looking to use AJAX. Use jQuery's .ajax to call the PHP page, and when it returns the result, put it into the javascript variables, or directly into the DOM. AJAX example or jQuery example

How do you handle the back button in jQuery?

I just can't find a satisfying way to handle the Browser's History. Sure there are lovely plugins like History.js, which works fine for smaller things. But let me give you an example:
I have a multi-paged form that asks the user for different things. After every submit to the next page (actually the same, it just changes the view depending on HTTP-POST variables), there are some animations and changes on the page:
the main content changes to the next form (with a slideUp/slideDown)
the progress bar changes it's state with an animation
below this bar, some information about some of the input fades in
So that's pretty basic right now, but I'm already struggling, because all the animations (the last 2 parts) are different on every state (different div, different input-sources) and I have no idea how to make them so generic, that I have not to specify them separatly.
I could live with that though, but when a user hits the back button I have to redefine all those animations again (in reverse). The content-load sure is no problem, it basically just reloads the file with an ajax-load:
I execute a pushstate with the input data as the stateObj on submit
so I can execute the content-load in the bound 'statechange' event
As said though, the rest drives me insane.
I would highly recommend grabbing and learning Backbone.js. It plays great with jQuery and sets up your website in a modified MVC pattern. It also has a great system for handling URL changes and executing the appropriate code.
As for sliding, if you want to reverse animations, that could be a bit of a pain to keep track of. What I did with my app when I was sliding between screens is instead of sometimes sliding up and sometimes sliding down, I would always move the element in the DOM that I was sliding to so that it was after the element I was sliding from. That way the slide was always going in the same direction and my animations wouldn't get all goofy.
You could try JavaScriptMVC, which includes jQuery. Not sure if it meets your exact requirements but it is JavaScript and MVC...
Although not quite strictly MVC (of which there are several for JavaScript) I think backbone js is a great framework, that is based around the concepts of MVC, but re-worked to better suit the JavaScript language and environment.
Well after a lot of punching around and stuff, I decided to degrade to the simplest and best solution for my problem: Using the basics.
Instead of animating everything backwards/forwards when the user hits the back/forward buttons, I just reloaded the whole site with ajax so I can use the HTML/PHP fallback with the stateObj of the selected site.
Problem with History.js though is that it can't distinguish between pushState and back/forward button in the onstatechange-event. So I degraded from History.js to the standard W3C behaviour with pushstate. There will be an update with 1.8.0 that allows to distinguish between internal and external statechanges.
Thanks for all the answers, but I guess this is the most accurate way of dealing with it, while using MVC alone doesn't solve the problem - why I didn't accept any other answer!

Form submission using Ajax/Jquery

When I first started web development with php, when using POST I would have the page with the form that contained the information and then another php page which the “action” attribute pointed to and hence where the all the processing i.e. database work was done. After making a website with many forms I found that I was building up lots of pages and it was getting quite messy.
Then I started to look for a way to avoid this. I then found that I could post a page to itself and hence halving the amount of pages that I needed to use to submit a form. I did this using the isset() function in php. The problem with this is that the whole page needed to be refreshed.
Even more towards the future I discovered jquery and its use of ajax to submit forms etc. This led me back to me original problem of having too many pages and getting confused with what did what. So now I am wondering (although I’m not quite sure I can make sense of it) if there is a way to combine the two? Can jquery use ajax to process a form which points to itself?
The other options that I was thinking of would be to have one page that I send all forms and actions to, which has all my processing in and determine which section to use based on a switch. I’m not sure of the effects that this would have on performance though.
What views do you have on each of the methods?
What are the pros/cons?
Are any of the methods I mentioned frowned upon/bad practice?
This question has been baffling me for a while now, and so I thought it best to get the thoughts of the experts.
Thanks in advance.
Adam Holmes.
Well the answer is quite simple. Jquery uses AJAX to request pages the same way as you would with a regular form. Thus you can use jquery to post information from the form on the page itself, and then as you would normally with isset() do whatever you want.
The obvious advantage is that you don't need to refresh the page, and everything seems more seamless. However sometimes you will need to refresh anyway, for instance during logging in. The disadvantage is that users with javascript off will not be able to use that form, however from my experience this now mostly applies on mobile devices, and in limited manner even then.
I would say that using jquery/ajax to submit your forms is the way to go, just be sure to provide javascript-less alternative if it is something essential and if you receive a lot of traffic from mobile devices.
Somebody else will probably provide more elaborate answer, so take this just as a little summary.
jQuery can process it, and send anywhere you want :-)
Don't you thinked about using some kind of classes and autoload ( PHP 5 ) ? - it makes choosing in your second option much simpler ( somepage.php?class=Foo&.... )

rating system without reloading a page

i have a page on which i have some rating function like people who like the post can rate up or who don't can rate down.
on that link im calling a php file with some parameters passed in the anchor tag. Then in that php file im saving that rating with +1 or -1 (whichever is the case) in the database and after doing that im redirecting to that first page from where we have rated.
Now this whole function is reloading my whole page which i dont want.Is there any way with which i can do this rating without reloading the page,i want that when a person clicks on rate then just after click the rating should be shown according to what the user just did(+ or -) and that too without reloading the whole page.Is there any way to do that in php???????
Yes, it's called "Ajax". However, you don't do this on the server-side with PHP, you do it on the client-side with JavaScript. There are plenty of tutorials around, I suggest you take a look.
Note that there are many JavaScript libraries out there to make this extremely easy. I'd recommend taking a look at jQuery because I've personally found it to be the easiest to learn and use.
It seems a few answers have already been posted recommending different libraries. If you would like the avoid the (admittedly minimal) overhead of an included library, the following tutorial shows how to use a simple XMLHttpRequest object.
http://www.xul.fr/en-xml-ajax.html
The "xhr.responseText" is what you would receive back from the php processing (which would typically be done in a small, single-purpose script seperate from the primary page).
You can do this using Javascript or AJAX. There are plenty of free scripts online that can help you to do this without building the whole thing from scratch.
This page (http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=364) has a good list of different star rating scripts you can choose from. You can Google for more.
Here's another relevant tutorial I came across when answering some other question:
http://docs.jquery.com/Tutorials:Getting%5FStarted%5Fwith%5FjQuery#Rate%5Fme:%5FUsing%5FAjax

When is it appropriate to use AJAX?

When is it appropriate to use AJAX?
what are the pros and cons of using AJAX?
In response to my last question: some people seemed very adamant that I should only use AJAX if the situation was appropriate:
Should I add AJAX logic to my PHP classes/scripts?
In response to Chad Birch's answer:
Yes, I'm referring to when developing a "standard" site that would employ AJAX for its benefits, and wouldn't be crippled by its application. Using AJAX in a way that would kill search rankings would not be acceptable. So if "keeping the site intact" requires more work, than that would be a "con".
It's a pretty large subject, but you should be using AJAX to enhance the user experience, without making the site totally dependent on it. Remember that search engines and some other visitors won't be able to execute the AJAX, so if you rely on it to load your content, that will not work in your favor.
For example, you might think that it would be nice to have users visit your blog, and then have the page dynamically load the newest article(s) with AJAX once they're already there. However, when Google tries to index your blog, it's just going to get the blank site.
A good search term to find resources related to this subject is "progressive enhancement". There's plenty of good stuff out there, spend some time following the links around. Here's one to start you off:
http://www.alistapart.com/articles/progressiveenhancementwithjavascript/
When you are only updating part of a page or perhaps performing an action that doesn't update the page at all AJAX can be a very good tool. It's much more lightweight than an entire page refresh for something like this. Conversely, if your entire page reloads or you change to a different view, you really should just link (or post) to the new page rather than download it via AJAX and replace the entire contents.
One downside to using AJAX is that it requires javascript to be working OR you to construct your view in such a way that the UI still works without it. This is more complicated than doing it just via normal links/posts.
AJAX is usually used to perform an HTTP request while the page is already loaded (without loading another page).
The most common use is to update part of the view. Note that this does not include refreshing the whole view since you could just navigate to a new page.
Another common use is to submit forms. In all cases, but especially for forms, it is important to have good ways of handling browsers that do not have javascript or where it is disabled.
I think the advantage of using ajax technologies isn't only for creating better user-experiences, the ability to make server calls for only specific data is a huge performance benefit.
Imagine having a huge bandwidth eater site (like stackoverflow), most of the navigation done by users is done through page reloads, and data that is continuously sent over HTTP.
Of course caching and other techniques help this bandwidth over-head problem, but personally I think that sending huge chunks of HTML everytime is really a waste.
Cons are SEO (which doesn't work with highly based ajax sites) and people that have JavaScript disabled.
When your application (or your users) demand a richer user experience than a traditional webpage is able to provide.
Ajax gives you two big things:
Responsiveness - you can update only parts of a web page at a time if need be (saving the time to re-load a page). It also makes it easier to page data that is presented in a table for instance.
User Experience - This goes along with responsiveness. With AJAX you can add animations, cooler popups and special effects to give your web pages a newer, cleaner and cooler look and feel. If no one thinks this is important then look to the iPhone. User Experience draws people into an application and make them want to use it, one of the key steps in ensuring an application's success.
For a good case study, look at this site. AJAX effects like animating your new Answer when posted, popups to tell you you can't do certain things and hints that new answers have been posted since you started your own answer are all part of drawing people into this site and making it successful.
Javascript should always just be an addition to the functionality of your website. You should be able to use and navigate the site without any Javascript involved. You can use Javascript as an addition to existing functionality, for example to avoid full-page reloads. This is an important factor for accessibility. Javascript should never be used as the only possibility to reach or complete a request on your site.
As AJAX makes use of Javascript, the same applies here.
Ajax is primarily used when you want to reload part of a page without reposting all the information to the server.
Cons:
More complicated than doing a normal post (working with different browsers, writing server side code to hadle partial postbacks)
Introduces potential security vulnerabilities (
You are introducing additional code that interacts with the server. This can be a problem on both the client and server.
On the client, you need ways of sending and receiving responses. It's another way of interacting with the browser which means there is another point of entry that has to be guarded. Executing arbritary code, posting data to a non-intended source etc. There are several exploits for Ajax apps that have been plugged over time, but there will always be more.
)
Pros:
It looks flashier to end users
Allows a lot of information to be displayed on the page without having to load all at the same time
Page is more interactive.

Categories