Dynamically load PHP within a main page - php

I'm pretty new when it comes to PHP and AJAX, so I keep running into issues, and after scouring the web for ideas, I've come up short. I'm looking for a method to dynamically load content (PHP/HTML mixture) on one main page. The main page would include navigation, and once a link within this navigation is clicked, the content in the main content div would change. Pretty simple, right, but I've been a big struggle bus on this topic.
The method I've liked the best so far is CSS-Tricks Rethinking Dynamic Page Replacing Content which uses the HTML5 History API. I liked that it allowed the use of the back and forward browser buttons, but I could not get it to work in Chrome.
This isn't your typical "help me figure out what's wrong with my code" question, so I apologize in advance. Mostly I'm looking for a bit of advice on how best to find a solution to this problem.

Go with Ajax... I was in a similar situation a couple of weeks ago. I didn't know much about it, but this site is quite helpful:
http://www.w3schools.com/ajax/ajax_example.asp
It has simple examples that will help you to understand how the calls work.
I hope it helps. It is difficult to give more specific advice since you don't explain much about your application.

This can be done with AJAX, you will need a content/view/page anchor to determine what content is loaded, then you can use that to load content from your php,
Heres a snippet of jQuery code that uses #hash to determine content, so http://example.com/#home will do an ajax request for $_POST['view']='home'
$(function(){
// Detect hashchange (browser back/forward buttons)
$(window).bind('hashchange', function() {
load_content();
});
// Init content
load_content();
});
function load_content(){
//get the hash
var page = window.location.hash;
page = page.substring(1);
if(page == ''){
page='home';
}
//get the content, replace any - with / so php can route to sub actions ect
$.post("./", { 'view': page.replace("-","/") },
function(data) {
//load the content into the load container
$("#load").html(data).fadeIn('slow');
});
}
<div id="load"></div>
Then you can simply find the route to your script within php with:
$route = explode('/',$_POST['view']);
$controller = (!empty($route[0])) ? $route[0] : null;
$action = (!empty($route[1])) ? $route[1] : null;

Here is a simple example to make you understand :
Make an ajax call on click of the navigation links,
<p id="test">CLICK ME</p>
<p id="result">Your result</p>
Ajax code within the script tags is as follows :
$(document).ready(function() {
$("#test").click(function(){
$.ajax({
url : 'testing.php',
type : 'GET',
async : 'true',
cache : 'false',
success : function(data, textStatus, xhr)
{
$('#result').empty().html(data);
},
});
});
});
Note : the ajax call url can be php or html page or even text file where you have the result to be shown on the main page division.

Related

Insert dynamic content into php page and change the URL

My goal: I have a form that is in parts, 1-4, when the user clicks on the "Next" button I would like the content to animate out then part 2 slides, and so on until the form is complete. The tricky part is I would am trying to use a different php page in a different subfolder to insert as the other 3 parts. This would also change the URL subfolder the user sees.
The working example is actually WordPress. When you click through the multi-part form you will see the content and the URL act as I have described.
I did a bit of digging and it seems like they used React.js on the content but I couldn't really find any documentation on how to do this with React.js so it made me think that maybe it was custom Ajax/jQuery or what.
My Trees of Folders -
Main
Subfolder-1
index.php
Subfolder-2
index.php
And so on. The only thing I could think of would to use jQuery:
$(document).ready(function() {
$('#form-container').on('click', '.insert', function() {
var directory = $(this).attr('name');
$('#form-container').load('../' + directory);
return false;
});
});
I add the class of "insert" on the "Next" button and give it a name="Subfolder-2" $('#form-container').load('../Subfolder-2);' will actually load the content into the div without the page refreshing BUT it does not change the subfolder in the URL.
Am I on the wrong track? Maybe I am just not searching for the right thing?
Ok, so I ended up figuring out how to get the content to act like I wanted with the information John S. provided me. After doing some research and a few hours of trial and error I came up with the JavaScript below:
var data = 'start',
url = '../' + data + '/';
history.pushState(data, null, url);
Above I set the variables and immediately run a history.pushState on page load to capture the first div that is loaded into the content div. This is important because it is the only way I could load the content that happens on initial load back into the page when hitting the browsers back button.
$('body').on('click', '.insert', function(e) {
data = $(this).attr('data-name'),
url = '../' + data + '/';
history.pushState(data, null, url);
request_content(data);
return false;
});
Then I add a click listener to the button with the class .insert reset the variables so instead of grabbing the page that initially loaded it grabs the page that will be loaded, then use history.pushState again to change the url that is determined by the variables.
The request_content function is a simple .load function. So when the button is clicked the variables are set, the url changes and the new content get loaded into the page while the old content disappears.
The final piece to the puzzle which took me the longest to figure out is actually the popstate function. I am still not 100% sure why it works but after hours of messing with it and finally getting it to work I am not going to question it.
window.addEventListener('popstate', function(e){
var data = e.state;
if(data === null) {
} else {
request_content(data);
}
});
This popstate function is what allows the content to come back when hitting the browsers back or forward navigation.
CSSTricks < this article at CSSTricks helped a TON when learning this method.
Thanks again to John S. for pointing me in the right direction!

Javascript not executing after Ajax call

I know this has been asked on SO a lot, but I have trawled through the posts for a few hours now and nothing works.
I'm working on a Wordpress blog where the prev/next buttons on a single post page have to load the prev/next post by Ajax. I have written the code (jQuery Ajax) all fine (I think - if you want to improve it, be my guest!), but in each post there a few bits of jQuery that need to work. However, after I click either of the prev/next buttons to move between posts, the jQuery won't work (it works absolutely perfectly when the page is first loaded). I know this is due to the content not being 'connected' to the JS anymore but I'm not sure what to do about it.
Here is my code:
$(".page-feed").on('click', '.post-nav>a', function() {
event.preventDefault ? event.preventDefault() : event.returnValue = false;
var link = $(this).attr('href'); // get the value of the href attribute on the links
$(".post-content").html("Loading...");
$.get(link, function(result) {
$result = $(result);
$content = $result.find(".post-content");
$(".post-content").replaceWith($content);
}, 'html');
});
I know that you're probably going to ask what I've already tried, but if I'm honest, not a lot that would be worth putting here.
The code above is located right at the top of a file called script.js, with all the other JS below it (which doesn't currently work after the Ajax call). The script is started by the standard $(document).ready(function() { statement.
Thanks for any help :)
First, you need to accept the event object as an argument.
$(".page-feed").on('click', '.post-nav>a', function(event) {
Next, by using the jQuery event object, you can simplify the next line because event is normalized by jQuery to work cross-browser.
event.preventDefault();
Now, as far as it working on the first click but not after, that's likely because .page-feed is a dynamic element. You'll need to instead select an element that is an ancestor of .post-content. document is a decent replacement, but it would be better if you picked one more local.
$(document).on('click', '.post-nav>a', function(event) {

jQuery scrollbar plugin not working on Ajax loaded content

The problem is this:
I have a simple, two fields form which I submit with Ajax.
Upon completion I reload two div's to reflect the changes.
Everything is working perfect except a jQuery plugin. It's a simple plugin that can be called with simple
function(){
$('.myDiv').scrollbars();
}
It's simple and easy to use, but it doesn't work on Ajax loaded content. Here is the code I use to post form and reload div's:
$(function() {
$('#fotocoment').on('submit', function(e) {
$.post('submitfotocoment.php', $(this).serialize(), function (data) {
$(".coment").load("fotocomajax.php");
}).error(function() {
});
e.preventDefault();
});
});
I've tried creating a function and calling it in Ajax succes:, but no luck. Can anyone show me how to make it work ? How can that simple plugin can be reloaded or reinitialized or, maybe, refreshed. I've studied a lot of jQuery's functions, including ajaxStop, ajaxComplete ... nothing seems to be working or I'm doing something wrong here.
If you're loading elements dynamically after DOM Document is already loaded (like through AJAX in your case) simple binding .scrollbars() to element won't work, even in $(document).ready() - you need to use "live" event(s) - that way jQuery will "catch" dynamically added content:
$(selector).live(events, data, handler); // jQuery 1.3+
$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+
$(document).on(events, selector, data, handler); // jQuery 1.7+
Source: jQuery Site
Even if I am totally against using such plugins, which tries to replicate your browser's components, I'll try to give some hints.
I suppose you are using this scrollbars plugin. In this case you may want to reinitialize the scrollbars element, and there are many ways to do this. You could create the element again like in the following example
<div class="holder">
<div class="scrollme">
<img src="http://placekitten.com/g/400/300" />
</div>
</div>
.....
$('.scrollme').scrollbars();
...
fakedata = "<div class='scrollme'>Fake response from your server<br /><img src='http://placekitten.com/g/500/300' /></div>";
$.post('/echo/html/', function(response){
$('.holder').html(fakedata);
$('.scrollme').scrollbars();
});
If you want to update the contents of an already initialized widget instead, then things gets more complicated. Once your plugin initialize, it moves the content in some custom wrappers in order to do its 'magic', so make sure you update the correct element, then trigger the resize event on window, pray and hopefully your widget gets re-evaluated.
If it doesn't help, then try to come up with some more details about your HTML structure.
I want to thank everyone of you who took their time to answer me with this problem I have. However, the answer came to me after 4 days of struggle and "inventions" :), and it's not a JS or Jquery solution, but a simple logic in the file.
Originally, I call my functions and plugins at the beginning of the document in "head" tag, like any other programmer out here (there are exceptions also ).
Then my visitors open my blog read it and they want to post comments. But there are a lot of comments, and I don't want to scroll the entire page, or use the default scroll bars, simply because they're ugly and we don't have cross browser support to style that, just yet.
So I .post() the form with the comment, and simply reload the containing all of them. Naturally .scrollbars() plugin doesn't work. Here come the solution.
If I put this :
<script>$('.showcoment').scrollbars();</script>
in the beginning of my loaded document (with load() ), will not work, because is not HTML and it's getting removed automatically. BUT !!! If i do this:
<div><script>$('.showcoment').scrollbars();</script></div>
at the same beginning of loaded document, MAGIC .... it works. The logic that got me there I found it in the basics of javascript. If your script is inside an HTML element, it will be parsed without any problem.
Thank you all again, and I hope my experience will help others.
If I understand you correctly, try this:
var scrollelement = $('.myDiv').scrollbars();
var api = scrollelement.data('jsp');
$(function () {
$('#fotocoment').on('submit', function (e) {
$.post('submitfotocoment.php', $(this).serialize(), function (data) {
$(".coment").load("fotocomajax.php");
api.reinitialise();
}).error(function () {
});
e.preventDefault();
});
});
reinitialise - standart api function, updates scrolbars.

run selected link in background, update url and icon of link?

I'm not quite sure how to word this.. but here goes :)
I have links similar to :
<img src='go.png'>
<img src='go.png'>
<img src='go.png'>
When someone clicks on the first link I want to run go.php?go=4a in the background, and change the icon on the link to stop.png, but also change the URL of this link to go.php?stop=4a.
If they think click the same link, I'd want to revert all this back to what it was.
Effectively making each link a go / stop toggle !
I seem to think jquery can do this, but I can't find any examples.
Anyone any ideas ?
Thanks :)
Provided you have jQuery loaded, and you have a container x which serves as your page content, you can use $.ajax to load dynamic content to the container and have it load/stop like:
$(function () {
$('a.tip').on(' click', function () {
var $this = $(this),
container = $('#x'),
prevHTML = container.html(),
req = {};
if ($this.hasClass('go')) {
req.abort();
container.html(prevHTML);
$this.find('img').attr('src', 'go.png');
$this.removeClass('go');
} else {
$this.find('img').attr('src', 'stop.png')
.end().addClass('go');
req = $.ajax({
url: 'go.php?go=' + $this.attr('id'),
type: 'get',
success: function (data) {
container.html(data);
$this.removeClass('go');
}
});
}
});
});
p.s. This is a rough example to get you started. Cheers!
As far as I know - what you want is not possible. Changing the URL refreshes the page, so your ajax will be lost in the nick of time.
You can use anchors though (for example if you're on go.php, you can change the url to go.php#go4a, and with the proper coding, you will be able to make the page work as if the AJAX ran.
About reverting, you will need to use a flag to see its state, then do the appropriate reverts. Not sure what you need, so this is all the information I can give you.

PHP post and get value to a jQuery box page, refresh page as `msnbc.com`

Finally, I find some article in http://code.google.com/intl/en/web/ajaxcrawling/docs/getting-started.html msnbc use this method. Thanks for all the friends.
Thanks for your all help. I will study it for myself :-}
Today, I updated my question again, remove all of my code. Maybe my thinking all wrong.
I want make a products show page.
One is index.php, another is search.php (as a jquery box page). index.php has some products catagory lists; each click on product catagory item will pass each value to search.php. search.php will create a mysql query and view products details. It(search.php) also has a search box.(search.php can turn a page to show multiple products; the search result looks similar to a jQuery gallery...).
I need to do any thing in search.php but without refreshing index.php.
I tried many method while I was thinking: Make search.php as an iframe (but can not judge search.php height when it turn page and index.php without refresh); use jquery ajax/json pass value from index.php to search.php, then get back all page's value to index.php. (still met some url rule trouble. php depend on url pass values in search.php, but if the value change, the two page will refresh all. )
so. I think, ask, find, try...
Accidental, I find a site like my request.
in this url, change search word after %3D, only the box page refresh
in this url, change search word after = the page will refresh
I found somthing in its source code, is this the key rules?
<script type="text/javascript">
var fastReplace = function() {
var href = document.location.href;
var siteUrl = window.location.port ? window.location.protocol+'//'+window.location.hostname +':'+window.location.port : window.location.protocol+'//'+window.location.hostname;
var delimiter = href.indexOf('#!') !== -1 ? '#!wallState=' : '#wallState=';
var pieces = href.split(delimiter);
if ( pieces[1] ) {
var pieces2 = pieces[1].split('__');
if ( pieces2[1] && pieces2[1].length > 1) {
window.location.replace( unescape(pieces2[1].replace(/\+/g, " ")));
}
}
}();
</script>
If so. in my condition. one page is index.php. another is search.php.
How to use js make a search url like
index.php#search.php?word=XXX&page=XXX
then how to pass value from one to another and avoid refreshing index.php?
Still waiting for help, waiting for some simple working code, only js, pass value get value.
Thanks to all.
I have read your problem, though I can not write complete code for you (lack of time ) So I can suggest you to what to do for your best practice
use dataType ='json' in jQuery.ajax function and
write json_encode() on B.php
and json_decode() on A.php or $.getJSON()
Alternate:
Read
jQuery.load()
assuming you really want to do something like here: http://powerwall.msnbc.msn.com/
I guess they are using a combination of ajax-requests and something like this: http://tkyk.github.com/jquery-history-plugin/
make shure that the navigation (all links, etc.) in the box works via ajax - check all the links and give them new functionality by js. you can write some function which requests the href url via ajax and then replace the content of your box. ...
function change_box_links(output_area){
output_area.find('a').each(function(){
$(this).bind('click', function(e){
e.preventDefault();
var url = $(this).attr('href');
$.ajax({
url: url,
success: function(data){
output_area.html(data);
//update url in addressbar
change_box_links(output_area);
}
});
});
});
}
it is upgradeable but shell show the main idea...
addendum[2011-05-15]
Get away from thinking you will have two files, that can handle some many "boxes". i mean you can do this but it's worth it.
but to be able to set up your templates like normal html page you could use the above script to parse the ajax requested html pages.
build your html-pages for
viewing the content,
viewing the search result
, etc.
on your main page you have to provide some "box" where you can display what u need. i recommand a div:
<div id="yourbox"></div>
your main page has buttons to display that box with different content, like in the example page you have showed us. if you click one of those a JS will create an ajax call to the desired page:
(here with jquery)
$('#showsearch_button').bind('click', function(){showsearch();});
function show_search() {
$.ajax({
url: 'search.php',
success: function(data){
var output_area = $('#yourbox');
output_area.html(data);
$.address.hash('search');
change_box_links(output_area);
}
});
});
for other buttons you will have similar functions.
the first function (see above) provides that the requested box-content can be written as a normal html page (so you can call it as stand-alone as well). here is the update of it where it also provides the hashtag url changes:
jquery and requireing the history-plugin
function change_box_links(output_area){
output_area.find('a').each(function(){
$(this).bind('click', function(e){
e.preventDefault();
var url = $(this).attr('href');
$.ajax({
url: url,
success: function(data){
output_area.html(data);
var name = url.replace('/\.php/','');
$.address.hash(name);
change_box_links(output_area);
}
});
});
});
}
and you will need some kind of this function, which will bind the back and forward buttons of your browser:
$.address.change(function(event) {
var name = $.address.hash();
switch(name){
case 'search': show_search(); break;
default: alert("page not found: "+name);
}
});
the above code should give an idea of how you can solve your problem. you will have to be very consequnt with filenames if you just copy and past this. again: it is improveable but shell show you the trick ;-)
im not sure that i fully understood what you want, but correct me if i didnt,
i think u need something like a dropdown that once the user select one item some div inside ur page show the result of another page result..
if so u can do it with jquery .load() and here is an example (no need for json)
Step 1:
Index.php
<p>
brand:<select id=jquerybrand>$jquerybrands</select><br />
Model:<select id=jquerycars></select><br />
</p>
<script type=\"text/javascript\">
$(document).ready(function(){
$('#jquerybrand').change(function(){
var value=$(this).value;
var url='api/quick.php?'+this.id+'='+this.value+' option';
$('#jquerycars').load(url);
});
});
</script>
This will simply show 2 dowpdown boxs (can be text or anything u like). and will add a listener to any change in value. once changed it will submit the id of the field and the new value to api/quick.php , then quick.php responce will be loaded into #jquerycars dropdown.
Step 2 quick.php
if(isset($_GET['jquerybrand'])){
$jquerycars="";
require_once("../lib/database.php");
$sql_db = new database();
$l=$sql_db->Item_in_table("car","sheet1","WHERE `brand`='$jquerybrand';");
foreach($l as $l)$jquerycars .="<option>$l</option>";
echo $jquerycars;//response that will replace the old #jquerycars
}
this will confirm that this is a request to get the query result only, then it will do the query and echo the results.
now once the results come back it will replace the old :)
hope it helps :).

Categories