HTML API popstate prevent ajax Request - javascript

I have a problem with popstate, Basically my code works really well. I perform an AJAX request and pushState. The problem comes up when I hit the back button on the browser. The whole page will request AJAX again. As you know Github is using this method also but when we hit back button it will not request AJAX again. how does Github do that? This is my code :
function loadProducts(dataPage) {
$.ajax({
type: "GET",
url: test.php,
data: {page : dataPage},
dataType: "html",
cache: true,
success: function(checks) {
$(".ajaxpage").html(checks).fadeIn("slow");
}
});
};
window.onpopstate = function(event) {
if (event.state != null) {
var pop = event.state;
loadProducts(pop.dataPage)
document.title = pop.dataPage;
}
};
$('#product').on("click", ".paging a", function(e) {
e.preventDefault();
history.pushState({
dataPage: $(this).attr('href')
}, null, $(this).attr('href'));
loadProducts($(this).attr('href'));
});
i try to remove "loadProducts(pop.dataPage)" but the page did not show previous page that should be. only the URL had change.
What's wrong with my code?

Related

My ajax request is not working on first page load?

I have dynamically loaded content .task-listing. The click works because it does "show" the div. But the ajax request doesnt function properly. I get a 200 status in the console, but I get no response from the server. If I refresh the page, it works properly. Why would this occur? I cant figure it out, I have been researching for over 2 hours. When I use firefox it doesnt happen again until I close the browser...
$(document).ready(function () {
$(document).on("click", ".task-listing", function () {
var info = $(this).attr("id");
getTaskInfo(info);
$(".task-data").show();
});
});
function getTaskInfo(info) {
$.ajax({
type: "POST",
url: "/src/php/get-info-task.php",
dataType: "json",
data: "info=" + info,
success: function (response) {
alert("ok");
},
});
}

Display loading icon and then redirect to new page

Lets say I have one page "page1" which consist of some info and a button named "Add".
When I click on this button, it opens a popup modal window that consists of a form with around 10 fields and submit button. Once I click on this button, I used ajax post to submit the form and at the server side it does insert and update operation and return success or failure result.
During this ajax process, I am displaying a loading image. What I am trying is just after this loading image it should redirect to new page. Lets say "page2". But in my code, i see after this loading stops , I see the modal window and "page1" for about 2-3 seconds and then only it redirects to "page2".
I am not sure if my question is logical or not but still if there is any method to stop it.
Below I have ajax processing code.
Thank you.
$.ajax({
type: 'POST',
url: 'page2.php',
data: {
'data': form_data
},
success: function(response)
{
var arr = JSON.parse(response);
if(arr.success == true) {
window.location.href = 'page3.php';
}
else {
alert('There are some error while saving record.');
}
},
beforeSend: function()
{
$('.loader').show().delay(9000);
},
complete: function(){
$.fancybox.close();
$('.loader').hide();
}
});
$.ajax({
success: function(response)
{
...
if(arr.success == true) {
...
}
else {
...
$('.loader').hide();
}
},
...
complete: function(){
$.fancybox.close();
}
});
Don't hide the loader after ajax request is done.

JS, jQuery not working when I refresh part of page with Ajax

I have some JS files included in my page that are simple for displaying blocks on click ant etc..
On another part of page, I have a button. When I click it an ajax call is made that returns some values that I display on the page. To display it, I'm reloading part of page like this:
$(document).ready(function () {
$(document).on('click', '.add', function (e) {
$this = $(this);
$.ajax({
type: 'POST',
url: 'add',
dataType: 'JSON',
data: {product: $this.parent('.input-append').find('input').data('id'),quantity: $this.parent('.input-append').find('input').val()},
success: function (data) {
if(data.success == false){
alert('error')
}else{
$('.test').load(" .test");
$('.sidebar').load(" .sidebar");
$('.top').load(" .top");
}
}
});
});
This reloads part of page, displays values and etc..
However, after the ajax call is made, the JS stops working. When I click my buttons, nothing happens. No errors or anything.
I think it has to do with the ajax when I refresh part of twig and it messes up the previously loaded JS files. But what can I do in that situation? Somehow refresh the loaded JS files? How?
You have to attach event listener on button starting from the container which doesn't get reloaded by Ajax request, like this:
//#mainCont is a container that doesn't get reloaded by Ajax
$("#mainCont").on("click", ".yourBtn", function(){
//do something
});
As said #Nacho M, you need to reinit listener from the loaded element, so you hsould have something like this :
function init() {
$(document).on('click', '.yourclass', function (e) {
//your content
}
// add every button who needs to be reloaded.
}
Init them on loading page first :
$("document").ready(function() {
init();
})
And on success of Ajax call :
$.ajax({
type: 'POST',
url: 'add',
dataType: 'JSON',
data: {product: $this.parent('.input-append').find('input').data('id'),quantity: $this.parent('.input-append').find('input').val()},
success: function (data) {
if(data.success == false){
alert('error')
}else{
$('.test').load(" .test");
$('.sidebar').load(" .sidebar");
$('.top').load(" .top");
init();
}
}
});

Using history.pushstate on jquery ajax

I have a heavily ajax based application wherein i only have a login page and the main page.
Most of my links are "ajaxed" and i have them done like this:
//get the href of the link that has been clicked, ajaxify ANY links
$(document).on('click', '.tree a', function () {
var link = $(this).attr('href'); //get the href off the list
$.ajax({ //ajax request to post the partial View
url: link,
type: 'POST',
cache: false,
success: function (result) {
$('#target').html(result);
$.validator.unobtrusive.parse($("form#ValidateForm"));
}
});
return false; //intercept the link
});
I want to implement "pushState" on my application and the first step that i have done so far is to add this code:
$(document).on('click', 'a', function () {
history.pushState({}, '', $(this).attr("href"));
});
Now it updates my address bar whenever i click on any of my links and the ajax content gets successfully loaded.
I am kinda new to this API so i don't know what am i missing but here are my issues so far:
when i press the "back" button, nothing happens. I read about "popstate" and browsed through SO to look for solutions but i can't
seem to make them work.
When i click the link from the history, i get the "raw" view of the child html w/o the layout from the master html. What do i need to do if i want it to be displayed like
it was clicked from my main application?
Most of my child views are either forms or list.
This code should help you :
function openURL(href){
var link = href; //$(this).attr('href');
$.ajax({
url: link,
type: 'POST',
cache: false,
success: function (result) {
$('#target').html(result);
$.validator.unobtrusive.parse($("form#ValidateForm"));
}
});
window.history.pushState({href: href}, '', href);
}
$(document).ready(function() {
$(document).on('click', 'a', function () {
openURL($(this).attr("href"));
return false; //intercept the link
});
window.addEventListener('popstate', function(e){
if(e.state)
openURL(e.state.href);
});
});

jQuery: make get request to the same page with parameters

In my application, running in a PHP page, I want that a get request is done after a value from a select menu is chosen. The url of the page is
www.mydomain.it/admin/gest-prenotazioni-piazzola.php
So with a jQuery I would like to make a get request to the same page so that it is reloaded but with a parameter. In fact, at the beginning of the page I have:
if (isset($_GET["param1"])) {/*build page with content 1*/}
else if (isset($_GET["param2"])) {/*build page with content 2*/}
So I tried with
jQuery("#tipologia_piazzola").on('change', function() {
if (this.value == "mensile") {
jQuery.ajax({
url: "",
type: "get",
data:{param1:"mensile"},
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
}
});
But this doesn't do exactly what I want because the call is done in background and the page is not reloaded. Any help would be appreciated.
Thanks for reading
You don't need ajax for this. All you need to do is:
$("#tipologia_piazzola").on('change', function() {
window.location.href = window.location.href + '?param1=' + $(this).val();
});

Categories

Resources