Seemingly Asynchronous Page Load - php

I am not sure what to call this but in google plus, when you navigate to different pages, the HTTP address changes but the userbars seem to remain static and not reload. What is happening and how is this done?
I hope this makes sense! Thank you!

AJAX (Asynchronously loading the content)
The content is being loading asynchronously and the url in the address bar is being altered.
An basic example of loading content asynchronously:
$.ajax({
url: 'http://www.example.net/load.html',
dataType: 'html',
success: function(data){
// This will replace all content in the body tag with what has been retrieved
$('body').html(data);
}
});
See here for the $.ajax() documentation.
Modifying the URL without Redirecting
To change the url withour redirecting, you need to use the HTML5 history API. A similar question has been asked here before, please see:
Modify the URL without reloading the page
Extracted answer:
function processAjaxData(response, urlPath){
document.getElementById("content").innerHTML = response.html;
document.title = response.pageTitle;
window.history.pushState({"html":response.html,"pageTitle":response.pageTitle},"", urlPath);
}
For more information on the HTML5 History API, please see here.

It's likely that they're using the HTML5 History API, specifically the pushState method to add new history states. They're also probably using Ajax (XHR) to load in new content and then adding that content to the page via the DOM API.
Check out pjax, a library that takes care of most of this for you.

Related

jQuery Mobile form submission over multiple pages with CakePHP

I hope I am missing something simple here. I have a CakePHP web site I am using jQuery mobile with. I think CakePHP might have something to do with it, but I am not sure.
Anyway, I have a form I've created on my view page for adding comments. The Ajax call is working as expected on the first page that loads, but navigating to any other page prevents the data from being submitted. The console still logs 'data' each time I press the button (after using 'pagebeforeshow' as recommended somewhere else), however it seems to be the data from the original loaded page (I know this because I am currently debugging $this->request->data on the Form action page).
Clearly, I must need to "reset" the form somehow when moving across pages, but I am not sure if this is possible without refreshing the page. I do know about "data-ajax"="false" and "rel"="external" which can be used as a last resort, but I want to avoid refreshing the page if I can.
Any suggestions? Thank you.
Here is the JS I am using for the Ajax call
//<![CDATA[
$(document).on('pagebeforeshow', function(){
$(document).off('click', '#comment_add').on('click', '#comment_add',function(e) {
$.ajax({
async:true,
data:$("#sCommentViewForm").serialize(),
dataType:"html",
success:function (data, textStatus) {
//$('#comments').remove();
//$('<div id="comments"></div>').appendTo('#comments_container');
$("#comments").html(data).trigger('create');
//$('#comments_box').remove();
//$('<div id="comments_box"></div>').appendTo('#comments_container');
console.log(data);
},
type:"POST",
url:"commentsUsers/comment_add/<? echo $template['Template']['id']; ?>"});
return false;
});
});
//]]>
</script>
It was my basic lack of understanding. After lots of searching this simple post was most helpful:
Jquery Mobile Javascript not working on ajax load
Basically, I was using IDs for everything - when I switched to class names it was smooth sailing.

Load content without refresh

I have codeigniter website which is done 1 year ago. No, I want to implement new HTML5 history API (pushstate) function to enable change content based on the url without header refresh. Is there any simple way, to avoid url restructure and load whole content using new HTML5 history API? I was trying to find some way, but most of them are using get methods.
$(function() {
$('nav a').click(function(e) {
$("#loading").show();
href = $(this).attr("href");
loadContent(href);
// HISTORY.PUSHSTATE
history.replaceState('', 'New URL: '+href, href);
e.preventDefault();
});
// THIS EVENT MAKES SURE THAT THE BACK/FORWARD BUTTONS WORK AS WELL
window.onpopstate = function(event) {
$("#loading").show();
console.log("pathname: "+location.pathname);
loadContent(location.pathname);
};
});
function loadContent(url){
// USES JQUERY TO LOAD THE CONTENT
$.getJSON("content.php", {cid: url, format: 'json'}, function(json) {
// THIS LOOP PUTS ALL THE CONTENT INTO THE RIGHT PLACES
$.each(json, function(key, value){
$(key).html(value);
});
$("#loading").hide();
});
// THESE TWO LINES JUST MAKE SURE THAT THE NAV BAR REFLECTS THE CURRENT URL
$('li').removeClass('current');
$('a[href="'+url+'"]').parent().addClass('current');
}
Here is demo for this : http://sandbox.cergis.com/html5-historyAPI/page1.php
I want to implement new HTML5 history API (pushstate) function to enable change content based on the url without header refresh.
pushState is there to allow you to change the url without loading a new page.
Is there any simple way, to avoid url restructure and load whole content using new HTML5 history API?
Changing the content is the job of DOM.
You can use XMLHttpRequest (or other Ajax techniques) to load new content from the server (and then insert that into the page using DOM manipulation)
Generally, you should use the history API in combination with DOM manipulation. You change the content of the page with DOM, then change the URL to one that the server can use to generate the same page from scratch. This means the page still works for users (including search engines) without JavaScript, and it avoids the homepage loading before being replaced (after a few seconds) with different content.

Variables from Javascript to PHP [duplicate]

This question already has answers here:
Closed 11 years ago.
I have a javascript function I would like to run on a page, that when executed will send a variable to a PHP script but not open the PHP page just stay on the current page.
What I am trying to do is add this function to pages on a website and for it to return information about the page it was run on, such as URL and user IP.
Everything I have tried so far has not done the job, so any info is appreciated.
Many thanks
Thanks Quentin, but I have tried to javascript forms, but they all open the url the form is being posted to. My most recent example:
var form = new Element('form',
{method: 'post', action: 'http://www.site.com/data.php'});
form.insert(new Element('input',
{name: 'u', value: ""+u, type: 'hidden'}));
$(document.body).insert(form);
form.submit();
I also tried:
document.location.href='http://www.site.com/data.php?u='+u;
but again this open the page :S
For those that have suggested AJAX, thank you but it wont work because that needs a script link in the header and I need to be able to plug this into a page without editing the header. I did try to dynamically insert it via the javascript function, it went in OK but none of the AJAX functions would execute.
What you are looking for is called AJAX (Asynchronous Javascript and XML). These type of calls in Javascript are made trivial with things like jQuery.
This is what jQuery's website says about AJAX: The jQuery library has a full suite of AJAX capabilities. The functions and methods therein allow us to load data from the server without a browser page refresh.
And an example jQuery POST:
$.post('ajax/test.html', function(data) {
$('.result').html(data);
});
Using jQuery
for simplicity do something like this
$.ajax('foo.php',function(d){ alert(d); });

how can I get just a single div to refresh on submit as apposed to the entire page?

I am working with a dynamically generated page written in PHP. The divon the page contain contents listed FancyBox links that open editing screens.
Once editing is complete and the user closes the FancyBox modal the changes
need to be reflected on the parent page.
Right, so I was able to find a solution that refreshes the entire page on submit
using
parent.location.reload (true);
to refresh the entire parent page. But, that causes a browser prompt
that is confusing to users and a bit of over kill as I really only
need the information edited to refresh.
how can I get just a single div to refresh on submit as
apposed to the entire page??????
You need to submit the form through AJAX. Since your using something that uses jQuery, you can use it to do it.
Here you can find a tutorial on how to do it
I think the best way is loading page fragments with .load().
something like,
$('#pageNeedToBeRefreshed').load('test.html #pageNeedToBeRefreshed');
User ,
It should be pretty easy
have a div place holder like below
<div id="dataToRefresh"> </div>
Once you close the dialog, have a event handler...
$('dataToRefresh').html('testing'); // give your data here
it should upate the parts of the page
let me know if you need anything else
please go thruogh .html api for more info
http://api.jquery.com/html/
Suppose you have the below div to refresh:
Then write
$("#dataToRefresh").load();
Might it will be helping you
Instead of using submit in html you can submit your form using the ajax -
$('#formid').submit(function(){
var data = $(this).serialize(); //this gives you the data of all elements of form in serialized format
$.ajax({
type: 'POST',
dataType:"json",
url: 'your url',
data: data,
success: function(data){
//replace the contents of the div you want to refresh here.
}
});
});
jQuery('#id_of_div').load('/url/to/updated/html');
See jQuery docs for load()

Send data to database when click on a link without page refresh

Is there a way to send data to database when click on a link without page refresh?
I use php/mysql...
I will give you an example using jQuery.
Let's say that we have a link with an attribute id="button_id" (you have to learn the jQuery selectors ).
$("#button_id").click(function(){
var var_data = 5;
$.ajax({
url: "my_script.php",
data: { var_PHP_data: var_data };
success: function(data) {
// do something;
alert(data);
},
});
});
Explanation: you will send the variable var_data with the name var_PHP_data to a my_script.php without page refresh using an ajax call (using GET method).
This is very simple example of what you have to write on your PHP script.
<?php
$var_name = $_GET['var_PHP_data'];
echo 'This is what you have send'.$var_name;
?>
Because the default method to send variables in the ajax function in jQuery is GET.
We have to use the $_GET function in PHP.
This php script will print a message and this message will be handled in the success: function in the Ajax call and just for example we will alert this message returned from PHP.
You'd have to use JavaScript. When a user clicks a link, if you don't use JavaScript, then you need to go user -> server -> user and they get a whole new page.
HTTP is stateless.
It's not possible without a page refresh but this is the classic use-case for AJAX requests. If you're not familiar with AJAX then there are various methods of doing this using all the popular JavaScript frameworks such as Prototype and jQuery
You can't send data directly to a database, but you can use AJAX to send data to a php page that will save them to the database, without reloading the page or following the link in the browser..
Have a look at http://api.jquery.com/jQuery.post/
Not using PHP because it is server side - you need JavaScript / AJAX for this.
Check out frameworks like dojo (http://www.dojotoolkit.org/) , mootools (http://mootools.net/) or jQuery ( http://jquery.com/ ).
Yes, you can use AJAX.
This is a very big topic, but I'd recommend you do some research on AJAX and jquery (javascript).
Here are some tutorials:
http://www.ajaxf1.com/tutorial/ajax-php.html
http://www.talkphp.com/vbarticles.php?do=article&articleid=58&title=simple-ajax-with-jquery
Do a search in google for more info.

Categories