JS script doesn't work when i click back on site - javascript

i create a nav on my site. Navigation works good but when i back on the main site all script from js file doesn't work. Script for my nav:
var default_content="";
$(document).ready(function(){
//Ajax navigate
checkURL();
$('footer a').click(function(){
checkURL(this.hash);
});
default_content = $('#login_box').html();
setInterval("checkURL()",250);
.........
Methods:
var lasturl="";
function checkURL(hash)
{
if(!hash) hash=window.location.hash;
if(hash != lasturl)
{
lasturl=hash;
if(hash=="")
$('#login_box').html(default_content);
else
loadPage(hash);
}
}
function loadPage(url)
{
url=url.replace('#page','');
$.ajax({
type: "POST",
url: "include/help4meApi.php",
data: 'page='+url+'&tag=navigation',
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0)
{
$('#login_box').html(msg);
}
}
});
}
Problem is when i back to the main site scripts doesn't work.

the issue comes from here $('#login_box').html(default_content);. When u calle the .html() the event binded within the element will be cleaned.
When you backspace, back to the main page, the event handler is already not there, so you have to register it again
//For show and hide register values
$("#registerInputsBtn").click(function(){
$(".register_information").hide(1000);
$(".register_values").show(1000);
$("#firstname").focus();
});
register again on the piece of code that you assign the content to #login_box. For example the quick fix:
if(hash==""){
$('#login_box').html(default_content);
$("#registerInputsBtn").click(function(){
$(".register_information").hide(1000);
$(".register_values").show(1000);
$("#firstname").focus();
});
}
but here the codes are not DRY :( rearrange the flow on how the page load and the register the event in the correct flow is recommended.

Related

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 Function running multiple times

I am using two scripts on my page and there is a general click function which records the number of clicks one user is making. So when I click on any element in the document, the click function should run after which other functions on the same element runs. But in my case, the click function runs multiple times before passing the control to the other function.
/************ 1st Jquery Script ***************/
function($) {
$(function(e) {
$('.signupCustom').click(function(){
var email = $('#form-email').val()
var password = $('#pass').val()
var firstName= $('#form-first-name').val()
var lastName= $('#form-last-name').val()
var number= $('#form-mobile').val()
var type=$('#sel1').val()
$.ajax({
url: '/login',
type: 'GET',
data: {
'email': email,
'password':password,
'firstName':firstName,
'lastName':lastName,
'number':number,
'type':type
},
success: function(data){
if ($('#sel1').val() == "Travel-Agent"){
window.location.href = "/agentVerification.html"
}
else{
window.location.href = "/dashboardTraveller"
}
}
})
})
$('.login').click(function(){
var email = $('#form-username').val()
var password= $('#form-password').val()
$.ajax({
url: '/loginCustom',
type: 'GET',
data: {
'email': email,
'password':password
},
success: function(data){
window.location.href = data['url']
}
})
})
$('.destinationsButton').click(function(){
var url="/destinations";
window.location=url;
})
}); })(jQuery);
I have attached the link to the html page which contains the second script.
Link to Page
If you go to this link, there is an image:
When I click on Login button, the click function runs multiple times before control goes to other function. I want the click function to run single time and then control should go to other function.
I tried e.stopPropagation but in case of a popup on same page, the popup does not open. Here on clicking on login, popup comes.
Is there any reason you are using the below?
jQuery('*').on("click",function(e){});
I think this might work better
jQuery('body').on("click",function(e){});
good luck
I don't know where you're stuck but you may use one to run the click function just once:
$(selector).one('click',function(){
//code runs only one click
});

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();
});

optimizing colorbox and adding extra jquery

I have two problems
I am trying to open a jQuery colorbox and it is very slow. The reason is I am trying to get html content from a different page (I cannot use iframe because I just need a part of this page). The following code works but it takes time after the button is clicked:
$(document).ready(function() {
$(".cart-link a").click(function(event) {
$(this).colorbox.close();
});
$(".rest-menuitem a").click(function(event) {
event.preventDefault();
var result = null;
var sURL = $(this).attr("href");
$.colorbox({
html: function() {
$.ajax({
url: sURL,
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
result = data;
}
});
return $(result).find('.product');
},
width: '650px',
height: '10px',
onComplete: function() {
$(this).colorbox.resize();
}
});
});
});
I want to know if there is a alternative way to do it. I dont mind if the colorbox popup and then takes time to load the content. The above version can be fount at this url (http://delivery3.water-7.com/index.php/restaurants/manufacturers/3/Barcelona-Restaurant-&-Winebar/products).
I am also trying to close the colorbox when a user clicks on add to cart. But some reason it is not triggered. $(".cart-link a").click is not triggered when I click on add to cart. Is there a special way to add jquery to colorbox content?
Try this instead:
$(".rest-menuitem a").colorbox({
href: function(){
return $(this).attr('href') + ' .products';
},
width: '650px',
height: '10px',
onComplete: function() {
$(this).colorbox.resize();
}
});
ColorBox uses jQuery's load() method for it's ajax handling, so you just need to add the desired selector to the link's href.
For your question 2 can you try this ?
$(document).ready(function() {
$(".cart-link a").live('click',function(event) {
$(this).colorbox.close();
});
});
For your question 1..it will be slow since you are fetching it from different page.Use a different logic for that
For your question no 1
$('selector').colorbox({onLoad: function() { /*Intially load a empty color box with only <div id="contenttoload"></div> (No other html content */
$.ajax({
url :'Your url',
data : {}, //data to send if any
type : "POST" //or get
success:function(data){ /*data means the stuff you want to show in color box which you must return from the other page*/
$('#contenttoload').html(data); //data should be well formatted i mean add your css,classes etc from the server itself */
}
});
}});

Categories

Resources