Ajaxify a website so that .php pages are loaded without page refresh - javascript

I have been using the code from the top answer of the following post:
Need help understanding how to ajaxify a web site
It's working correctly when I try it with .html pages, as shown in the example. However, my pages are in php. Everything is working as it should with the php pages, except that when the url updates it shows as .html instead of .php.
In the code, taken from the answer I mentioned:
<script type="text/javascript">
var directory = 'content/'; //directory of the content we want to ajax in
var state = History.getState();
//for when they click on an ajax link
$('.ajaxify').on('click', function(e){
var $this = $(this);
var href = $this.attr('href'); // use the href value to determine what content to ajax in
$.ajax({
url: directory + href + '.html', // create the necessary path for our ajax request
dataType: 'html',
success: function(data) {
$('#content').html(data); // place our ajaxed content into our content area
History.pushState(null,href, href + '.html'); // change the url and add our ajax request to our history
}
});
e.preventDefault(); // we don't want the anchor tag to perform its native function
});
//for when they hit the back button
$(window).on('statechange', function(){
state = History.getState(); // find out what we previously ajaxed in
$.ajax({
url: directory + state.title + '.html', //create our path
dataType: 'html',
success: function(data) {
$('#content').html(data);
}
});
});
</script>
I have tried changing
$.ajax({
url: directory + href + '.html', // create the necessary path for our ajax request
dataType: 'html',
success: function(data) {
$('#content').html(data); // place our ajaxed content into our content area
History.pushState(null,href, href + '.html'); // change the url and add our ajax request to our history
}
});
to (changed .html to .php):
$.ajax({
url: directory + href + '.php', // create the necessary path for our ajax request
dataType: 'html',
success: function(data) {
$('#content').html(data); // place our ajaxed content into our content area
History.pushState(null,href, href + '.php'); // change the url and add our ajax request to our history
}
});
However, this has no effect. I have also tried changing the HTML:
<ul id="nav">
<li id="home-link">Home</li>
<li id="work-link">Work</li>
<li id="labs-link">Labs</li>
<li id="blog-link">Blog</li>
</ul>
<div id="content">Home Content</div>
to (adding .php to the hrefs):
<ul id="nav">
<li id="home-link">Home</li>
<li id="work-link">Work</li>
<li id="labs-link">Labs</li>
<li id="blog-link">Blog</li>
</ul>
<div id="content">Home Content</div>
but this stops the page loads from working completely. Any advice would be greatly appreciated. Thanks!

Related

Create and Fetch Dynamic url using Jquery

I have a page single-colur.html and it can take a variety of set query strings as can be seen below:
single-colur.html?id=1
single-colur.html?id=2
single-colur.html?id=3
single-colur.html?id=4
The id above is referenced to a colour table which has the following columns:
id
name
content
When people come to single-colur.html and they request a specific ID, I'd like to get the respective ID from the URL and send an AJAX request to a PHP page which will get the corresponding row from my table based on the ID that is provided, this is currently implemented.
My question is: Is it possible that if someone goes to single-colur.html?id=1 then all the data is fetched and displayed in a new URL based on the name field which is referenced by the ID e.g. single-colur.html?id=1 points you to a dynamically created file called red.html and it shows the data from the colour table for this ID?
My restriction is that I must create the new file dynamically and it cannot be done statically.
EDIT
Currently i have two pages .
1)archive-colour.html
2)single-colour.html
in archive-colour.html
<div>
Red
Green
Blue
</div>
in single-colur.html?id=anynumber
<div class="result">
</div>
In single-colur.html i am doing ajax and fetch details from database using requested id and display in class result .
This is the current process . But what i need is
in single-colur.html?id=anynumber
i have to replace the current page url with colour-name.html
and show the details . [BUT the thing is there is no colour-name.html page in server . ie there is no red.html, green.html,blue.html in server . It have to be virtually created by jquery . ]
Use Ajax :
$.ajax({
url: "my-colours.html",
type: "get", //send it through get method
data: {
id: //<Your id here >
},
success: function(response) {
window.location.href = '/' + response.color + '.html' ;
},
error: function() {
//Do Something to handle error
}
});
I suppose this is what you're looking for. Here a dynamic link will be created by ajax and you can give a dynamic value to Id each time.
So you use
window.location = window.location.hostname + "here put the returned from ajax" + ".html";
Explain
window.location.hostname
returns the website url
This example is as complete as it can be in this environment.
Load on click via ajax
Set content
Set virtual url
$( 'a.virtual' ).click( function( e ) {
var link = $(this);
console.log( "Loading: " + link.attr('href') );
$.ajax({
url: link.attr('href'),
type: "get",
success: function(response) {
// parse json or howerver data get transferred
var result = parseJSON(response);
var content = result['content'];
var virtual_url = result['url'];
// set content
$('#content').html( content );
// set virtual url
window.history.pushState([], 'Title', virtual_url);
}
});
// do not follow the link!
e.preventDefault();
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li><a class="virtual" href="my-colours.html?id=1">Link A</a></li>
<li><a class="virtual" href="my-colours.html?id=2">Link B</a></li>
<li><a class="virtual" href="my-colours.html?id=3">Link C</a></li>
<li><a class="virtual" href="my-colours.html?id=4">Link D</a></li>
<ul>
<br/>
Content delivered via ajax:<br/>
<div id='content'>
</div>

Ajax / Jquery refresh page after variables are passed

Okay so am using Ajax to send a JS variable from index.php to page2.php . Once it is set to page2.php, the database is edited while the user has been on index.php the entire time. However, I need the index.php to reload or refresh once page2.php has finished updating the database in the background. To give you a better clue, I will include some of my code.
On Index.PHP is :
<a href='#' class='dbchange' onclick='dbchange(this)' id='".$ID'>Update</a>
and
function dbchange(obj) {
var id = $(obj).attr('id');
$.ajax({
type: "POST",
url: 'page2.php',
data: "NewID=" + id,
});
}
So basically when they click the button that says "Update" it sends the ID of the button the page2.php and page2.php from there updates the changes the database using that info. However, the URL the user is on is:
http://website.com/index.php#
and the database has not updated for them and they have to see the annoying hash symbol in the URL. I have googled how to refresh the page in JS, and found things that either do not work or do work , but result in the variables not being sent to the PHP file. I just need it so that after it is sent to the php file, and preferably after the php file is finished, the index.php page refreshes and without the # at the end.
e.preventDefault() is the answer but if I may suggest:
Get rid of that inline function and add the event handler with jQuery.
$(function () {
$('.dbchange').click (function (e) {
e.preventDefault();
var id = this.id;
$.ajax({
type: "POST",
url: 'page2.php',
data: {NewID: id},
success: function(data) {
window.location.reload();
}
});
});
});
Remove # then replace with javascript:void(0):
<a href='javascript:void(0)' class='dbchange' onclick='dbchange(this)' id='".$ID'>Update</a>
JS:
function dbchange(obj) {
var id = $(obj).attr('id');
$.ajax({
type: "POST",
url: 'page2.php',
data: "NewID=" + id,
success: function() {
window.location.reload();
}
});
}

Load PHP partial in Bootstrap HTML "Delighted" Template

I started an app using the "Delighted" app template and I am trying to convert an html partial page to a php partial page and have it load when HTML on left nav is clicked. Once I changed the HTML to PHP, it stopped working and will not load. I have tried modifying the JS provided (below).
Any thoughts?
OLD HTML:
My Accounts
NEW HTML:
<a href="my-accounts.php" data-original-title="My Accounts"> My Accounts</span>
</a>
JS:
function loadPage(url, container) {
*//added this piece*
if (url.lastIndexOf(".") > -1) {
urlExt = url;
}
*//original code*
else {
urlExt = url + '.html';
}
//console.log(container)
$.ajax({
type: "GET",
url: urlExt,
dataType: 'html',
cache: false,
success: function...etc...
});
}

Update div content using PHP and Javascript variables

I'm new to Ajax and need some help with this.
The idea is simple, I have a list of directories within the div 'list' and when I click on one of the directories, the div 'content' must list the content of this directory with a php function.
This is my html code:
<div id="list">
<ul>
<li id="directory_1" class="test">directory_1</li>
<li id="directory_2" class="test">directory_2</li>
<li id="directory_3" class="test">directory_3</li>
<li id="directory_4" class="test">directory_4</li>
</ul>
</div>
<div id="content">
<!-- Here you can see the folder content-->
</div>
This my jQuery + Ajax:
$(".test").click(function(){
var name = $(this).attr("id");
$.ajax({
url: 'list.php',
type: "POST",
data: ({folder: name}),
});
});
It works, I arrive to list.php. And on PHP I have a function that lists directory content.
So how can I refresh 'content div' with the php function?
So if I click on directory_1 it will show /var/www/pg/directory_1 folders, and then if I click on directory_2 it will clear the 'content' div and will then list out the directory_2 folders.
Here is a jsfidde without the PHP code:
http://jsfiddle.net/e5v1dgpc/
Sorry for my English, if someone has a question I will try to clarify.
You could do something like this:
jQuery('#content').html('');
Which will just set everything inside the html to be blank.
Or I think you could use .empty() - http://api.jquery.com/empty/
If you called it at the start of your function then it should clear the div before repopulating it.
$(".test").click(function(){
var name = $(this).attr("id");
$( "#content" ).empty();
$.ajax({
url: 'list.php',
type: "POST",
data: ({folder: name}),
});
});
In order to set the target of your ajax you could do something like this with a success condition. You'd need to change it to display whatever content you want.
$.ajax({
url: 'list.php',
type: 'POST',
success: function(html) {
var divSuccess = $('#content', $(html)).addClass('updated');
$('#content').html(divSuccess);
}
});
This link might also be useful to you - jquery ajax load certain div
Instead of Emptying the 'content' div initially, you can empty it
OnSuccess of the Ajax post, as below:
$(".test").click(function(){
var name = $(this).attr("id");
$.ajax({
url: 'list.php',
type: "POST",
data: ({folder: name}),
success: function(){
$( "#content" ).empty();
}
});
});
Hope this is what you are looking for..

How to refresh a DIV in jquery (mobile)?

UPDATE: Sorry, I accidentally copied the data-dom-cache="true" line into my content-div. Seems very logical that the app is loading from the dom instead the new content! I've changed it to false and now it works perfectly.
Thanks.
I have a list which is dynamically generated. If someone is clicking on an entry in the list, the user is redirected to a new page where the data is loaded (dynamically). The data which is loaded depends on the list entry which the user has clicked.
When the app is loaded the first time, all things work well. But when the user is clicking on another list entry, the same data are represented as on the first run.
I've played around with the .empty() function from jQuery (to clear the div and append the new data) but it doesn't work.
EDIT:
My headlines.html file looks like this:
<div id="content>
<div id="headlineslist">
<ul data-role="listview" data-theme="c" id="headlineslist">
</ul>
</div>
</div>
<script>
$(document).ready(function() {
HeadlinesLoad();
});
</script>
Here's the Javascript file:
function HeadlinesLoad() {
$.ajax({
type: "POST",
url: "headlines_getter.php",
dataType: 'json',
cache: false,
success: function(data1) {
$.each(data1, function(i, currentObj) {
$('ul#headlineslist').append('<li data-role="list-divider"
class=​"ui-li ui-li-divider ui-bar-b">​' + currentObj.main + '</li>​').listview('refresh');
$.each(currentObj.sub, function (j, currentSub) {
$('ul#headlineslist').append('<li>
' + currentSub.name + '</li>').listview('refresh');
});
});
}
});
}
function headlineID(hID) {
window.localStorage.setItem("headlineID", hID);
}
function onHeadlinesLoad() {
var hID = window.localStorage.getItem("headlineID");
window.localStorage.removeItem("headlineID");
window.localStorage.clear();
$.ajax({
url: "headlinesclicked_getter.php?hID=" + hID,
success: function(html) {
if(html){
$("#headlineshome").empty();
$("#headlineshome").html(html);
}
}
});
}
And here is the snippet which lays in the HTML file where the data should be displayed (and refreshed on every new click the user does):
<div data-role="content" id="headlineshome"></div>
<script>
$(document).ready(function() {
onHeadlinesLoad();
});
</script>
I don't know why it doesn't work, so I ask you for help.
Thanks in advance.
Best regards, John.
Once you update your list using jQuery mobile, consider trigger "create" event, however that's out dated, so use
.page()
on your list like this:
$('ul#headlineslist').page();

Categories

Resources