e.preventDefault() on a link still loads the page - javascript

the title may be a bit misleading but I'm not sure how to phrase it better, so I apologize for that.
I'm creating a custom handler so the site doesn't refresh when new content is pressed (similar to how youtube works, for example).
For that I'm using this script:
$('.sidebar2 li a').click(function (e) {
test = true;
var button = $(this);
var noteId = button.data("noteid");
$(".sidebar2 li.active").removeClass("active");
var postData = { id: noteId };
$.ajax({
url: '/API/Note',
type: 'get',
data: postData,
success: function (resp) {
if (resp.success == true) {
$('#app-bar-left').html(resp.note.navBarHTML);
$('#cell-content').html(resp.note.noteContentHTML);
window.history.pushState({ path: window.location.href }, resp.note.title, '/MyNotes/Note/' + resp.note.noteId);
document.title = resp.note.title;
$('*[data-noteId="'+resp.note.noteId+'"]').parent().addClass("active")
e.preventDefault();
test = false;
return false;
}
}
});
});
even though I've stated e.preventDefault() to trigger, javascript loads the new content into the current frame without refreshing, but the browser refreshes again anyway.
I've tried to use href="#" however in this case when I go back and handle that, I always end up with two same pages, one without and one with # at the end, and in addition to that it wouldn't be very user friendly to have all links href="#"
What am I doing wrong to make the browser redirect "normally" even though I've told him no no no?
I've also tried adding onclick="javascript:void(0)" on a elements and that didn't help

ajax is async. By the time success callback is called event will already be bubbled up the DOM tree and processed. You need to call preventDefault before sending a request.
$('.sidebar2 li a').click(function (e) {
e.preventDefault(); // here for example
test = true;
var button = $(this);
var noteId = button.data("noteid");
$(".sidebar2 li.active").removeClass("active");
var postData = { id: noteId };
$.ajax({
url: '/API/Note',
type: 'get',
data: postData,
success: function (resp) {
if (resp.success == true) {
$('#app-bar-left').html(resp.note.navBarHTML);
$('#cell-content').html(resp.note.noteContentHTML);
window.history.pushState({ path: window.location.href }, resp.note.title, '/MyNotes/Note/' + resp.note.noteId);
document.title = resp.note.title;
$('*[data-noteId="'+resp.note.noteId+'"]').parent().addClass("active")
test = false;
// returning here makes no sense also
// return false;
}
}
});
});

Related

jQuery onsubmit function using incorrect target element

Really stuck on this one, I've inherited a website that was built using a page builder vomits
I've created a script that guards the downloads on this page (resources) the user must fill out a form and input their details, the form submission works correctly and when it completes I open the resource using window.open(href, '_blank') this works correctly on the first submit but if you try and download a second resource it always returns the first clicked href and opens that.
Here is my code: Im getting all the anchors on the page, looping over them and adding an onClick event listener, when a user clicks the link it opens the modal, then jquery to submit the form. As you can see in the comments the href is logged correctly when outside of the submit function, however when inside the submit function it always reverts back to the first href clicked.
e.g user clicks resource1, submits the form and downloads, user then clicks resource2, submits the form but is directed to resource1 :'(
jQuery(document).ready(function ($) {
const anchors = Array.from(
document.querySelectorAll('.page-id-17757 .elementor-element-7121f28 .elementor-widget-icon-list a')
);
const modal = document.querySelector('#resources-modal');
function getFormData($form) {
var unindexed_array = $form.serializeArray();
var indexed_array = {
data: {},
};
$.map(unindexed_array, function (n, i) {
indexed_array.data[n['name']] = n['value'];
});
return indexed_array;
}
function updateFormResponse(status, anchor) {
if (status == 200) {
$('.form-response').html('Success.');
modal.close();
$('.form-response').html('');
$('#resources-submit').prop('disabled', false);
} else {
$('.form-response').html('There has been an error, please refresh the page and try again');
$$('#resources-submit').prop('disabled', false);
}
}
anchors.forEach((anchor) => {
anchor.addEventListener('click', function (e) {
e.preventDefault();
modal.showModal();
let href = e.target.parentElement.href;
$('.resources-download').submit(function (e) {
console.log(e);
e.preventDefault();
e.stopImmediatePropagation();
let form = $(this);
$('#resources-submit').prop('disabled', true);
let formData = getFormData(form);
$.ajax({
url: '/wp-content/themes/hello-elementor/raisley/resources-download.php',
type: 'POST',
data: formData,
dataType: 'json',
complete: function (data) {
updateFormResponse(data.status, href);
if (data.status == 200) downloadResource();
},
});
});
console.log(href); // this logs the correct href
function downloadResource() {
console.log(href); // logs incorrect href, always returns the first clicked href
window.open(href, '_blank');
}
});
});
});
I'm really struggling with this one, need some pro help please!
Thanks,

How to restrict multiple user logins at same time using JavaScript / jQuery

I have developed an ASP.NET MVC Application using JavaScript, jQuery.
I have implemented to be restrict multiple user logins at same time using onbeforeunload/beforeunloadevent.
It works fine, but sometimes not working in onbeforeunload/beforeunloadevent.
var myEvent = window.attachEvent || window.addEventListener;
var chkevent = window.attachEvent ? 'onbeforeunload' : 'beforeunload'; /// make IE7, IE8 compitable
myEvent(chkevent, function (e) { // For >=IE7, Chrome, Firefox
if (!validNavigation)
{
$.ajax({
url: '#Url.Action("ClearSession", "Account")',
type: 'Post',
data: "",
dataType: "json",
success: function (data)
{
console.log("onbeforeunload Success")
},
error: function (data) {
console.log("onbeforeunload Error")
}
});
}
return null;
});
There is one also function in AJAX - jQuery is called complete: function(){};
This function checks weather request is running for same user id and password on browser or not, Like this here
complete: function() {
$(this).data('requestRunning', false);
}
Whole AJAX-jQuery implementation here see and implement accordingly, I hope it will work fine for you
Code Here
$('#do-login').click(function(e) {
var me = $(this);
e.preventDefault();
if ( me.data('requestRunning') ) {
return;
}
me.data('requestRunning', true);
$.ajax({
type: "POST",
url: "/php/auth/login.php",
data: $("#login-form").serialize(),
success: function(msg) {
//stuffs
},
complete: function() {
me.data('requestRunning', false);
}
});
});
See this me.data('requestRunning', false); if it will get any request running for same user id and password it returns false and cancel login.
For more help see here link Duplicate, Ajax prevent multiple request on click
This is not perfect solution but you can implement like this

How to press a button after successful Ajax?

When Ajax call is successful, user gets redirected to main page:
$('#button_1').on('click', function () {
//code
$.ajax({
method: "POST",
url: "/somewhere",
data: {
//code
}
}).done(function () {
location.href = "/";
});
});
After getting redirected, I want to automatically click another button, which opens a modal. I tried inside done function different methods:
.done(function () {
location.href = "/";
$('#button_2').click(); // doesn't work
});
.done(function () {
location.href = "/";
setTimeout(function ()
$('#button_2').click(); // doesn't execute
}, 2000);
});
.done(function () {
location.href = "/";
$(document).ready( function () {
// executes but user is immediately redirected to main page
$('#button_2').click();
});
});
I also tried outside Ajax, in the function that Ajax call is in, but had the same results.
How can I click the button programmatically after the Ajax call?
You need to add that logic in the target (main) page.
Once you redirect, the current page is not longer the active one and all logic is removed.
You could add some parameter to the URL in order to know when you are there due to redirection, something like:
location.href="/?redirect=1"
and then check that parameter
The lines of code next to
location.href = "/";
will not be executed because the browser is navigating to another page.
So you should put your logic in the / page (#button_2 should be in that page).
You're currently trying to execute code after a redirect which isn't possible directly because the code after location.href = "/" will never be reached. Once you redirect you've have a fresh page with a clear state.
Your current function can still look like this:
$('#button_1').on('click', function () {
$.ajax({
method: "POST",
url: "/somewhere",
data: {
//code
}
}).done(function () {
location.href = "/?modal-open=1";
});
});
As you can see I've added a query parameter to the redirect so we know we were redirected with the intention to open the modal.
For your Root Page (/) you will need a script like this:
$(document).ready( function () {
// check the URL for the modal-open parameter we've just added.
if(location.search.indexOf('modal-open=1')>=0) {
$('#button_2').click();
}
});
This will check if the parameter is in the URL and trigger the click.
First of all when you redirect a new page you can not access DOM because the page is reloaded. You can send a parameter for do that.
$(document).ready( function () {
//after page load
var isButtonActive = findGetParameter("isButtonActive");
if(isButtonActive){
alert("button_2 activated");
$('#button_2').click();
}
$('#button_1').on('click', function () {
//code
$.ajax({
method: "POST",
url: "/somewhere",
data: {
//code
}
}).done(function () {
alert("page will be reload. button_2 wil be activated");
location.href = "/?isButtonActive=true";
});
});
$('#button_2').on('click', function () {
alert("button_2 clicked");
});
});
function findGetParameter(parameterName) {
var result = null,
tmp = [];
location.search
.substr(1)
.split("&")
.forEach(function (item) {
tmp = item.split("=");
if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
});
return result;
}
Thank you for your answers. I researched a bit more and found another way to do it:
$('#button_1').on('click', function () {
sessionStorage.setItem("reload", "true");
//code
$.ajax({
method: "POST",
url: "/somewhere",
data: {
//code
}
}).done(function () {
location.reload();
});
});
And in main page:
$(document).ready(function () {
var reload = sessionStorage.getItem("reload");
if (reload == "true") {
$("#button_2").click();
sessionStorage.setItem("reload", false);
}
});

Objects generated by javascript vanish right after appearing

On a button click I'm calling a python script and I'm populating the result into an array. Once done, I create <a href> as many <a href> objects as the length of the array. Problem is, once the links are displayed, they vanish immediately.
Body:
//I obviously get the same effect by putting the onclick event in the submit button
window.onload = function() {
alert("loaded");
document.getElementById('submit_searchsubs').onclick = function () {
FindSubtitles();
};
};
function FindSubtitles() {
postData = {"movie": "Outlander", "season":"1", "episode":"2"};
$.ajax({
url: "/cgi-bin/find_subtitles.py",
type: "post",
datatype:"json",
async : false,
data: {postData},
success: function(response){
var subs = new Array();
var json = $.parseJSON(response);
for (var i=0;i<json.length;++i) {
subs[i] = new Array(json[i].IDSubtitle, json[i].SeriesEpisode, json[i].SubHash, json[i].SubDownloadsCnt, json[i].SeriesSeason, json[i].ZipDownloadLink, json[i].MovieName, json[i].id, json[i].SubFileName);
}
DisplaySubtitles(subs); //show the users the new words found in this subtitle
}
})
.fail(function(err) {
alert("error" + err);
});
}
function DisplaySubtitles(subs) {
var SubtitleDiv = document.getElementById("SubtitleDiv");
var a = document.createElement('a');
for (i = 0; i < subs.length; i++) {
var linkText = document.createTextNode(subs[i][8]);
a.appendChild(linkText);
SubtitleDiv.appendChild(a);
}
}
So what happens:
Page loads
alert("loaded") is displayed as it's fired in window.onload
FindSubtitles runs
DisplaySubtitles runs and <a> links appear
<a> links disappear and alert("loaded") is displayed again.
I don't know if I should use async: true, because in that case I get [Object object] error, which is strange because in case of another script I use that, otherwise it would freeze the UI.
Any ideas?
As Kieveli mentioned, if submit_searchsubs is a form button that submits, it may be refreshing the page after submit. Try using return false; to bypass the default browser onclick action.
document.getElementById('submit_searchsubs').onclick = function () {
FindSubtitles();
return false;
};

AJAX loading a page without reload

I am trying to load content from a new page using AJAX. The test website I am working on is dev.dog-company.com.
This is my code:
$('a[rel="load"]').click(function(){
//var siteurl = "";
var link = $(this).attr("href");
$(this).attr("href", '#');
$('#slider-wrapper').slideUp();
$('#content').wrap('<div id="wrap"></div>').css('opacity', '0.75').css('background-color', 'black');
$.ajax({
type: 'POST',
url: link,
success : function(data){
var response = $(data);
var head= response.find('head');
var slider = response.find('#slider-wrapper');
var content = response.find('#content');
$('#content').unwrap('<div id="wrap"></div>')
jQuery("head").html(head);
if(slider != null)
jQuery("#slider-wrapper").html(slider).slideDown();
jQuery("#content").html(content);
return false;
}
$(this).attr("href", link);
})
});
I am trying load the content on click but the page reload everytime without the click working. Also I am not sure if I need to be doing something else other than what I am doing to my code. The rel="load" is only on home, info->AboutUs & FAQ.
Your help is appreciated.
Update:
I still can't get it to work. This is my latest code. And the site is still running it. When i use the debugging for chrome it never goes through my code. is it the re="load" that is causing the problem?
Update:
My initial problem was not having the document ready. But not I think the way I am parsing the information isn't working. I tried find and filter both seem to not work correctly. Also how do I change the url in the browser after I it pushes the post.
Update
After a lot of messing around with it I got it to partially work. One thing I can't do it replace head. and then the data pushed in slider is there but it does not seem to work on the website. It doesn't slide down like I have it in the code.
$('document').ready(function() {
$('a[rel="load"]').click(function(e){
//var siteurl = "";
e.preventDefault();
var link = $(this).attr("href");
$('#slider-wrapper').slideUp();
$('#content').wrap('<div id="wrap-overlay"></div>');
/*$('#wrap').css({
'opacity': '0.75',
'background-color': 'black',
'z-index' : '10'
});*/
$.ajax({
//ajax setting
type: 'POST',
url: link,
dataType: 'html',
success : function(data){
//parse data
var response = $("<div>").html(data);
console.log(typeof(response));
console.log(response);
//var head = response.find('<head>').html();
slider = response.find('#slider-wrapper').html();
var content = response.find('#content').html();
console.log(content);
//console.log(head);
//console.log(slider);
//Post data
$('#content').unwrap();
//jQuery("head").empty().append(head);
if(slider != null){
jQuery("#slider-wrapper").empty().slideDown().append(slider);
}
jQuery("#content").empty().append(content);
return false;
}
})
});
});
Try this:
$('a[rel="load"]').click(function(e) {
e.preventDefault();
// ...
});
You need to stop default browser behaviour on link click, which is following it.

Categories

Resources