Jquery Ajax call HTML5 History and back button - javascript

I've read a lot about this and feel that while I understand all the parts, I can not figure out how to put it all together without redoing my project. I have ajax set up and working really well on my site. I was able to add a # in the URL when new content comes in. The back button works, and goes through all the correct URLs without reloading the page, but the ajax doesn't refresh.
This is my HTML for the buttons:
<a class="portfolioThumbnail" onclick="return false;" data-name="myPage" href="myPage.html">
<img src="imagepath" />
</a> <!-- portfolioThumbnail -->
and here is my Jquery:
$('.portfolioThumbnail').on('click', function(){
var thisProject = $(this).attr('href')
$.ajax('http://oursite.com/' + thisProject, {
success: function(response) {
$('.projectWrapperReplace').html(response);
},
error: function() {
alert('error');
},
timeout: 5500,
beforeSend: function() {
$(this).find('.portfolioThumbnail').addClass('loading');
},
complete: function() {
$(".blurable").addClass('blur');
$(".blurable").addClass('whiteOut');
$('.projectWrapper').fadeIn('slow', function(){
$('.projectWrapper').addClass('noBlur');
window.location.hash = thisProject;
});
}
});
});
I have a div called projectWrapperReplace in my HTML too. Looking if anyone can help me get this working. Thanks

You need an event listener for when the back or forward buttons are pressed (right now you're only loading the ajax content when you click the .portfolioThumbnail buttons).
Make the ajax load and state classes a separate function, say hashChange()
Checkout onhashchange
//call hashChange on window hash chage
window.onhashchange = hashChange;
//and also on buttonclick
$('.portfolioThumbnail').on('click', function() {
hashChange();
})

Related

Ajax requests keep doubling

I have a website where on the main page there is a content div and content is being switched using ajax. Everytime I switch between different pages it seems to me like ajax keeps making double the amount of requests. Here is the code handling the page switching:
$(document).on('click','#sideNav a',function(e){
e.preventDefault();
var url = $(this).attr('href'); //get the link you want to load data from
$.ajax({
type: 'GET',
url: url,
success: function(data) {
$("#content").empty();
$("#content").html(data);
}
});
//window.history.pushState('object', 'New Title', url);
});
});
Now lets say I switch to my templates page where it displays created templates and lets me create templates.
Now the first time I switch to this page and create a new template everyhting is fine, one post is made to php and one new entry is made to the database. Now if I switch between pages and back to my templates page and create a new template, only this time ajax makes two posts to php and 2 database entries are made, now if I do that one more time 4 posts are mad and so on.
It happens with every function that uses ajax. It doesn't happen when I go to my templates page seperately not through my main page with the content div, so I suspect something is messed up with how I switch pages.
Edit: it actually isn't doubling but adding one request each time.
UPDATE
Somehow I fixed it, not exactly sure how but here's the things I did: I added .off('click','#sideNav a') to my function and I also put the function into separate .js file. I feel like it was loading the script again every time, again not exactly sure what exactly fixed it, hope it helps somebody.
As a solution to this you could use off() to dettach the click event (if exist) before attaching :
$(document).off('click','#sideNav a').on('click','#sideNav a',function(e){
e.preventDefault();
var url = $(this).attr('href'); //get the link you want to load data from
$.ajax({
type: 'GET',
url: url,
success: function(data) {
$("#content").empty();
$("#content").html(data);
}
});
//window.history.pushState('object', 'New Title', url);
});
});
IMO the cause of this problem comes from the posted code when you call it multiple time every time you call it the event will be attached another time and so on.
Your above script works just fine. Check out this plunk:
Html:
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#3.2.1" data-semver="3.2.1" src="https://cdn.jsdelivr.net/npm/jquery#3.2.1/dist/jquery.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<h1>Ajax request</h1>
<div id="sideNav">
Link 1
Link 2
</div>
<div id="content">
Some Content Goes Here
</div>
</body>
</html>
Javascript:
$(document).on('click', '#sideNav a', function(e) {
e.preventDefault();
var url = $(this).attr('href'); //get the link you want to load data from
$.ajax({
type: 'GET',
url: url,
success: function(data) {
console.log(data)
$("#content").empty();
html = `<p><b>Name:</b> ${data.name}</p>
<p><b>Email:</b> ${data.email}</p>
<p><b>body:</b> ${data.body}</p>`
$("#content").html(html);
}
});
// window.history.pushState('object', 'New Title', url);
});
Checkout this issue for other reasons that may cause your requests to be doubled.

Jquery Ajax preloader only onclick with several Ajax requests an phps

I am facing the following problem. I have got an index.php that contains a form. There are several AJAX-requests which point to different phps that dynamically load further form elements, e.g. when the option of a selectbox is changed.
The form itself contains a click-button which points to a php performing an AJAX-Request when being clicked. While waiting for the php to respond to the Ajax-Request, the preloader icon shall appear.
Everything works fine except:
When I change the select box the preloader icon appears which is wrong. But when I click the button of the form, the preloader icon does not appear but it shall appear.
This is my code at the start of the index php. As I am not a Jquery expert, does anyone have a hint for me what I'm doing wrong?
Thank yo very much in advance for your help!
<script>
$(document).ready(function(){
$('#submit').click(function(){
$.post("calculate.php", $("#calculate").serialize(), function(response) {
$('#success').html(response);
});
return false;
});
});
</script>
<script>
$(document).ready(function(){
$('#showcontentonchange').change(function(){
$.post("showcontentonchange.php", $("#showcontentonchange").serialize(), function(response) {
$('#successshowcontentonchange').html(response);
});
return false;
});
});
</script>
<script>
jQuery.ajaxSetup({
beforeSend: function() {
$('#preloader').html(' <img src="preloader.gif" style="position:relative;left:50%;margin-left:-64px;margin-top:5px;z-index:1;">')
},
complete: function(){
$('#preloader').html('')
},
success: function() {
$('#preloader').html('')
}
});
</script>

jQuery ajaxForm complete works sometimes, other times it only fires a native javascript function then stops

This may be a duplicate of this topic, but I must revive it as my issue seems to be a little deeper than this. I'm currently using ajaxForm() to submit a 4 question quiz to a PHP script, receive the result, and then populate it back into the DIV. The beforeSend function fires, sending the information to the ajax.php script. beforeSend also shows a loading graphic in the quiz container. Then the complete function fires properly as ajax.php returns the HTML to be populated back into the DOM. At that point, everything stops. The next line is a call to slideUp the loading div and then display the returned information in the quizContainer.
At this point if I put in a javascript alert it always fires, meaning that complete is at least firing when it should, but the jQuery reference to the loading div is completely ignored. Here's the code for the javascript file that handles the submission - the section handling this is "Handle the quiz submission":
$(document).ready(function () {
// Get rid of the message box after 15 seconds
setTimeout(function() {
$('#message').slideUp('fast');
}, 10000);
// Handle the Course List LIs
$('#courseList li').on('click', function () {
// Get the background color as it's set initially
var color = $(this).attr('oColor');
jQuery('div', this).toggle('slow', function () {
if ($(this).is(":hidden")) {
$(this).css('background-color', color);
}
});
// Change the background to be the same as the content background when it's expanded
if ($(this).is(":hidden")) {
$(this).css('background-color', '#33CC66');
} else {
$(this).removeAttr('style');
}
});
// Handle the quiz submission
jQuery.fn.exists = function(){return this.length>0;}
if ($('#quizForm').exists()) {
$('#quizForm').ajaxForm({
beforeSend: function() {
$('#quizContainer').slideUp('fast', function () {
$('#loading').show();
});
},
complete: function(xhr, theStatus) {
alert(theStatus);
$('#loading').slideUp('fast', function () {
$('#quizContainer').html(xhr.responseText);
$('#quizContainer').show();
});
}
});
}
});
If necessary I can provide more information and a temporary login to access this if anybody would like to see it in action. I'm currently using jQuery 1.8.1(.)
Thanks for any help!
Jon
I believe the first argument of the complete function is xhr.responseText rather than an xhr object which is actually the third argument. Try removing .responseText from your complete: function.

jQuery click event interrupts setInterval

I'm creating script where I use AJAX from jQuery. I've got a problem, as on my website I've got hidden object. Moreover I use setInterval to frequently refresh a piece of my script. Everything works well, but until I click on link to set this hidden object to be visible. When I click on link and make object visible, setInterval stops refreshing page. This is my code to AJAX:
$(document).ready(setInterval(function() {
$.ajax({
type: "POST",
url: "score.php",
success: function(html){
$("#loadplace").hide().show().html(html);
}
});
return false;}, 60000));
and this is code for link:
$('div#bar a#squad1').click(function(e) {
e.preventDefault();
$('div#s1 table.events1').hide();
$('div#s1 table.index_players1').fadeIn();
});
$('div#bar a#events1').click(function(e) {
e.preventDefault();
$('div#s1 table.index_players1').hide();
$('div#s1 table.events1').fadeIn();
});
is there any solution in jQuery for my problem ?
P.S. I hope you understand what I wrote, I know that my English is not so good as I wish it to be.

How to wait for form to load before applying form functions?

I have a checkout-button on my site wich dynamicly loads the form where the user can fill in his/her personal details.
The form has an id of #order. After the form is loaded it must call the .submit function from the jquery-form plugin.
When i first made this it did not work so i put my minimal debug skills to use (placing alert's, i know not the best method ;-)). Suddenly it worked when i put an alert between the loading of the form and the .submit call.
I figured it had something to do with the form not being completely loaded before calling the .submit. But after a quick search i found that the .html function is synchronous so any code
executed after the .html() call will definitely occur after the html
is set.
Can someone please help me with this problem?
$('.checkout').live('click', function(event) {
event.preventDefault();
$.get('/gva/templates/gva/form.html', function(data){
$('#blog').html(data);
});
alert('with this alert it works, without it doesn't');
var options = {
target: '#response',
beforeSubmit: validate,
success: showResponse
};
$('#order').submit(function() {
$(this).ajaxSubmit(options);
return false;
});
});
$('.checkout').live('click', function(event) {
event.preventDefault();
$.get('/gva/templates/gva/form.html', function(data){
$('#blog').html(data);
var options = {
target: '#response',
beforeSubmit: validate,
success: showResponse
};
$('#order').submit(function() {
$(this).ajaxSubmit(options);
return false;
});
});
});
The alert caused a delay which ensured the DOM had been updated by the time the next bits of your code fired. I've put them in the proper handler so that they fire at the proper time.

Categories

Resources