Jquery Function running multiple times - javascript

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

Related

How to return to URL stored in cookie

I've set up an infinite scroll on our category page. When a user clicks load more, the current page URL is stored as a cookie.
when the user then clicks onto a product and hits the back button I would like them to return to the same point.
How would I set the back button to go back to the URL stored in the cookie?
Current JS :
$(document).on('click', '.page-next a', function (e) {
e.preventDefault();
var self = $(this),
loadparent = self.parents('.ajax-load');
setTimeout(function () { $(loadparent).fadeOut(); }, 700);
$('.ajaxLoaderOverlay').addClass('show');
$.ajax({
url: $(this).data('url'),
method: 'POST',
dataType: 'html',
success: function (data) {
$('.mid-content').append(data);
$('.ajaxLoaderOverlay').removeClass('show');
}
});
var thisCookie = $(this).parent().data('href');
setCookie('listingPerRow', thisCookie, '30');
});
Many thanks in advance
One simple solution would be to have the "Load more" button change the url to a link to a certain element (www.example.com/#id). Then, the back button will scroll to that part of the page without any need for additional JavaScript:
var place = 0;
...
location.href = location.href.slice("#")[0] + "#load-" + place++;

JQuery & Ajax disable click

I have a table with data and a function to help me get values from rows:
function getRow () {
$('#mytable').find('tr').click( function(){
let fname = $(this).find('td:eq(4)').text();
let start = $(this).find('td:eq(5)').text();
let end = $(this).find('td:eq(6)').text();
.......ajax method () etc
................
}
So far, it has been working perfectly and fetching me the correct data. I had another function elsewhere in the page, where clicking on some links would fetch some data from the server and reload the page to display the new data. Everything was working like clockwork.
Now, I decided that when re-displaying fresh data, instead of reloading the page, it's better to refresh the #mytable div. Indeed, it worked, but alas it spoiled the first function. So basically the function below has introduced a bug elsewhere in the page, and I'm not sure why or how to fix it. It's as if the div refresh has completely disabled the event handler. Any ideas?
$(document).ready(function() {
$(".key").click(function(event) {
event.preventDefault();
var word = event.target.innerHTML;
$.ajax({
url: '.../',
data: {
action : "key",
keyword: word
},
type: 'get',
success: function(data){
$('#mytable').load("/.../../..." + ' #ytable');
},
error: function(e){
console.log(e);}
});
});
});

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

Prevent previously requests on click

I have list of tables,
<table id="<%#DataBinder.Eval(Container.DataItem, "Certificate")%>" class="tbl_evenSearchResultRow" onmouseover="this.className='ResultGridRowSeleted'" onmouseout="this.className='tbl_evenSearchResultRow'" onclick="return SynopsisWindowOpen(this)">
onclick of each i use next function:
function SynopsisWindowOpen(obj) {
var title = $(obj).find("strong[name='title']").html();
var isParentools = 0;
if (window.location.href.indexOf('recent_releases.aspx') > -1)
isParentools = 1;
var url = "/ratings/Synopsis.aspx?logoonly=1&Certificate=" + obj.id + "&Title=" + encodeURIComponent(title) + "&parentools=" + isParentools;
$("#ratingModal").on("show.bs.modal", function (e) {
$.ajax({
url: url,
cache: false,
dataType: "html",
success: function (data) {
$("#ratingModal").find(".modal-body").html(data);
}
});
});
$("#ratingModal").on("hide.bs.modal", function (e) {
$(this).find(".modal-body").html('');
});
$("#ratingModal").modal('show');
return false;
}
By url i render body of modal : i get certificate from request.query and according to it render body
LoadSynopsisContent(Request.QueryString["Certificate"], Request.QueryString["parentools"]);
Problem : when i click at first - everything seems to be good, on second click in modal body firstly rendered body of first click and then of second click. And so on.
I don't know where is problem.
Firstly i use jquery load function, but then i change to simple ajax call with disabled caching.
Move the all event bindings to outside of the function and everything should work fine.
Thus, these parts should not be inside the function:
$("#ratingModal").on("show.bs.modal", ....);
$("#ratingModal").on("hide.bs.modal", ....);
Here is one way you could organize your code:
var url; //a global variable ... not a good idea though
function SynopsisWindowOpen(obj) {
....
url = .....
}
$(function() {
$("#ratingModal").on("show.bs.modal", ....);
$("#ratingModal").on("hide.bs.modal", ....);
});
However, the way would be to not use inline JavaScript but to take advantage of the power of jQuery to separate structure from behavior.
UPDATE
Instead of using a global variable url you can store the new url in a data attribute of the modal. Then you can get it from there when the modal opens.
In the function:
//calculate the url
var url = .....
//store the url in the modal
$('#ratingModal").data('table-url', url);
In the modal event handler:
$("#ratingModal").on("show.bs.modal", function(e) {
//retrieve the url from the modal
var url = $(this).data('table-url');
//use the url
$.ajax({ url: url, .... }):
});

Ajax response change location

I have a function in jquery that submit a form that is working fine, but i need different types of reaction according to the response, sometimes i need to show a message, sometimes reload the window, and other relocate the window
I have a problem with this last part, i dont know how can i detect that is a url, and change the location.
this is my script jquery
function process_form(type_form, id_content_error){
var url = "url.php?form="+tipo_form;
var response= document.getElementById(id_content_error);
response.style.display='block';
$.ajax({
type: "POST",
url: url,
data: $('#'+type_form).serialize(),
success: function(data)
{
if (data==1){
window.location.reload();
}else{
response.innerHTML=data;
}
}
});
return false; // Evitar ejecutar el submit del formulario.
};
My php returns 3 types of sentences,
"1": when i need to reload the window.
"messaje": when i need to show something.
"some_url.php":when i need to relocate the window.
sorry for my english, and thanks
I resolve it adding this in the sucsess function
}else if (data.search(/.php/)!=-1){
window.location = data;
}

Categories

Resources