Insert dynamic content into php page and change the URL - php

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!

Related

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

saving and loading the ajax state of a page

I'm working on an ajax loading function on a Wordpress single page portfolio.
The principle is that when you click a thumbnail in the gallery, it opens a container (#DrawerContainer) and fetch the ajax content of this article into it. With a lot of help, I'm already able to open the drawer and load the post content when I click a thumbnail.
Here is a fiddle if you want to see it working (the ajax will not load but it works locally). http://jsfiddle.net/RF6df/24/
The part I'm working on now: I need my site to be crawlable and the urls to be shareable. If I give http://mywebsite.com/#!project5 to someone, I need project5 content to be opened when he loads the page.
I thought the hash-bang (#!) urls was the way to go to make this work. With the code below (commented on the jsfiddle), I can update the url and add the hash of the clicked thumbnail.
var pathname = $(this).find('a')[0].href.split('/'),
l = pathname.length;
pathname = pathname[l-1] || pathname[l-2];
window.location.hash = "#!" + pathname;
But when I load a page, the ajax state isn't remembered. I assumed it was because my ajax container was only loaded on click event, but there is no change when I add a persistant container in the php.
Is there a way to load the page with a post content already displayed, or to open the #DrawerContainer when the page is loading a hash-bang url?
Please keep in mind that I'm just learning jquery and ajax. So I'd really appreciate if you explain or comment a little bit what you do, I'll for sure learn at the same time... :)
on onload you should check the window.location.hash and trigger a click on the particular link/div.
$(document).ready(function() {
var hash = window.location.hash;
if ( hash.length > 0 ) {
hash = hash.replace('#' , '' , hash );
$('a[rel="'+hash+'"]').trigger('click');
}
});
I have used the following on sites where I want to trigger via hash changes.
First I bind a hashchange event to get the hash value
$(window).bind('hashchange', function(o){
url = window.location.hash.substring(1);
o.preventDefault();
if (!url) {
return;
}
}
Then I trigger the hashchange when I want - in your case when the page loads i.e. on document ready.
jQuery(document).ready(function($) {
$(window).trigger('hashchange');
});
You can then use the hash value in your function that loads the correct content

Loading results of PHP function into DIV container

It seems this question has been answered in the past, however, I'm either 1) having a hard time grasping the solutions or 2) not implementing them correctly.
I have a PHP function, that when run, will return results of a database query. Results look similar to this:
Koenji
I can echo this into a page just fine. What I'd like to do is give an end user the option to refresh the link (which can be done by refreshing the page and echoing a new random string returned by the php function) without having to refresh the whole page. I've tried a few different methods, but it seems the function that returns the element is only run when the page reloads - so my URL never changes.
Here is my latest attempt. I figured the url I'm grabbing from the database was only getting set when the paged loaded. I thought setting a function to initialize the url variable would help - no good. It still only works once on page load.
$(document).ready(function() {
updateVariable();
$('#dannychoolink').html(random + url);
$('.danny-choo').attr('target', '_blank');
});
$('#clicky').click(function() {
updateVariable();
$('#dannychoolink').html(random + url);
$('.danny-choo').attr('target', '_blank');
});
function updateVariable() {
url = '<?php echo dannyChoo();?>';
random = 'Random DannyChoo.com article: ';
};
You can see it live at www.dannychoofan.com.
Any help is appreciated =0)
It looks like your looking for an ajax style call.
You should put the contents of the dannyChoo() function into a new file called articleLinkGenerator.php at the same level as your index.php file. This file should have the contents of the dannyChoo() function so that it automatically executes and echos the html you are expecting for the link like
<?php
function dannyChoo(){
// generate random link code
echo $random_link_html // Like Koenji
}
dannyChoo();
Then in your index.php (main web site) update your functions using ajax(http://api.jquery.com/jQuery.get/) to look like:
$(document).ready(function() {
updateVariable();
});
$('#clicky').click(function() {
updateVariable();
});
function updateVariable() {
$.get('articleLinkGenerator.php',function(data){
$('#dannychoolink').html(data);
});
};
It's because PHP runs before the page loads, and JavaScript runs after the page loads, so your variable never changes without another page load.

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

get or post data in jquery (show url on browser line)

Okay, i have a job to do before tomorrow morning..
i'm working on some jquery.
Where i load some external file data..
What i really want to know, is how am i going to load some data when i $.post / or $.get some data through jquery
Send request into jquery hey
and the same time change the url browser to ex. mywebsite.com/prices/ without making the refresh on the page
is it possible, and how to do ?
// edit (not working)
<li> <span>prices</span></li>
jquery: $('a.prices').click(function(e) {
e.preventDefault();
$.view.show('prices');
});`
but can see that some of the others samples are not that easy to make it work..
You can do it like this:
hey
$('a.priceLink').click(function(e) {
e.preventDefault();
$.view.load('prices');
});
When the user click the link, the normal URL will be shown on the browser line, but won't get visited (because of preventDefault) and $.view.load('prices'); will thus load in that content without refreshing the page.
EDIT: #William - please try this:
<li><span>prices</span></li>
$('a.prices').click(function(e) {
e.preventDefault();
$.view.show('prices');
});
You can use a jQuery plugin called URL Utils - there's also a great screencast that shows you how to use it.
As far as I know, you can only change the url for the anchor part (www.url.com/#anchor), and nothing else (without a browser refresh). Perhaps you can use SWFAddress for your purposes?
i found the solution!!
http://nix.lv/history/demo.html
took me about 10min to install, and it just work perfectly..(i did some mod )
solution:
<li><span>prices</span></li>
jquery(download the plugin at the link above):
$.history.init(pageload);
// PageLoad function
function pageload(hash) {
// hash doesn't contain the first # character.
if(hash) {
$.view.show(hash); // load pages
} else {
// start page
$.view.show(load_from_start);
}
}
try it.. :)

Categories