How to press a button after successful Ajax? - javascript

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

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 abort ajax request on page refresh

I have a form, on submit of that I am making an ajax request which is sometimes taking time to get the request, so what I am trying to do is whenever user refresh or clicks back button of the browser after form submitting i want to abort that ajax call
What I am doing is
$("#formId").submit(function(event) {
event.preventDefault();
var xhr = $.ajax({
url : "Drilldown",
method : "GET",
success : function(data) {
// here doing ,my stuff
},
complete : function() {
$('.loader').hide();
$('.overlay').hide();
}
});
window.onbeforeunload = function() {
return "some message"; // here when user clicks on leave then want to abort like `xhr.abort`
};
});
whenever the user clicks on leave I want to abort my ajax request
How can I do that?
**I specifically want to do that when ever form submit and once form is submitted,i want to abort that function also onbeforeunload **
You can directly xhr.abort() in "onbeforeunload" event handler method:
// Define xhr variable outside so all functions can have access to it
var xhr = null;
$("#formId").submit(function(event) {
event.preventDefault();
xhr = $.ajax({
url: "Drilldown",
method: "GET",
success: function(data) {
// here doing ,my stuff
},
complete: function() {
$('.loader').hide();
$('.overlay').hide();
}
});
});
window.onbeforeunload = onUnload;
function onUnload() {
if(xhr) xhr.abort();
return "some message";
};
call below method to abort ajax call
xhr.abort()

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

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

Disable javascript function on successful ajax request

To be specific, I want to disable a function from executing on successful ajax request. I do not know whether that's possible or if any workaround is there. Have a look at what I do:
<script>
$(document).ready(function() {
function load(){
...
...
}
});
$.ajax({
...
success: function(option){
disable load function // I want this functionality somehow
}
});
</script>
Can someone help? I need this because load function is a scrolling function which loads products on scrolling to end & on ajax request another file uses the same, so somehow I need this function disabled. Any help will be appreciated.
EDIT
I want this function working on first time page load but with a successful ajax request I want this function be stopped. I'm putting the whole code for you to get the clear idea.
<script>
$(document).ready(function() {
var track_load = 0;
var loading = false;
var total_groups = <?php echo $total_groups; ?>;
var cat_id= <?php echo $cat_id; ?>;
$('.autoload').load("xyz.php", {'group_no':track_load, 'cat_id':cat_id}, function() {track_load++;});
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height())
{
if(track_load <= total_groups && loading==false)
{
loading = true; //prevent further ajax loading
$('.animation_image').show();
$.post('xyz.php',{'group_no': track_load, 'cat_id':cat_id}, function(data){
$(".autoload").append(data);
$('.animation_image').hide();
track_load++;
loading = false;
}).fail(function(xhr, ajaxOptions, thrownError) {
$('.animation_image').hide();
loading = false;
});
}
}
});
});
</script>
<script>
$(document).ready(function(){
$('#subcat').change(function(){
var val=$(this).val();
$(this).value= val;
$('#furcat').show();
if(val=='A'){
$('#furcat').html("<option selected='true' disabled='disabled'>Choose Further Category</option><option>B</option><option>C</option>");
var sub_cat=41;
}
$('.autoload').empty();
$('.animation_image').show();
$.ajax({
type: "POST",
url: "abc.php",
data: {sub_cat:sub_cat},
success: function(option){
$('.autoload').replaceWith(option);
$('.animation_image').hide();
}
});
});
});
</script>
And as I need the same scrolling function in upcoming data, I'm involving another php file which uses the same code as this & to remove double ajax request I need to disable this function.
You can create flag which you can set to 'true' on Document Ready and then set it to 'false' after successful ajax call.
<script>
var flag=true;
$(document).ready(function() {
flag = true;
function load(){
if(flag){
...
...
}
}
});
$.ajax({
...
success: function(option){
flag=false;
}
});
</script>
you can simply add the logic of flag variable. which will make sure that your load method will not execute after ajax success.
<script>
$(document).ready(function() {
var flag=false;
function load(){
if(!flag){
...
...
}
}
});
$.ajax({
...
success: function(option){
flag=true;
}
});
</script>
hope this helps you
You don't need any if-statements and additional variables.
Look at this code:
var load = function () {
...
};
$( document ).ready(function() {
$.ajax({
...
success: function () {
//"delete" the `load` function
load = '';
}
});
});
The load function is stored into a variable and when the ajax request was successful, that variable is cleared.

Stopping an $.ajax call on page unload

I have a procedure running on a timeout to load data in the background:
(function getSubPage() {
setTimeout(function() {
if (cnt++ < pagelist.length) {
loadSubPage(pagelist[cnt]);
getSubPage();
}
}, 500);
})();
In loadSubPage() I'm making $.ajax() calls:
function loadSubPage(page) {
if (typeof(initSubPages[page]) === "undefined") {
$.ajax({
type: "POST",
url: '/Main/GetPageData',
data: { page: page },
success: function (returndata) {
// ...
},
error: function() {
alert("Error retrieving page data.");
}
});
initSubPages[page] = true;
}
}
The problem I'm having is that the error handler is being hit when the user navigates away if any ajax requests are open. I'm trying to get around this by .stop()ing the requests on window.onbeforeunload, but I'm not sure what object to call .stop() on?
jQuery exposes the XMLHttpRequest object's abort method so you can call it and cancel the request. You would need to store the open request into a variable and call abort().
activeRequest = $.ajax({...
and to stop it
activeRequest.abort()
Abort Ajax requests using jQuery
This should come in handy.. You have a jQuery method for doing just that.
The $.ajax returns XMLHTTPRequestObject which has .abort function. This function will halt the request before it completes.
var xhr = $.ajax({ /*...*/
..
..
/* Later somewhere you want to stop*/
xhr.abort();
Read more: How to cancel/abort jQuery AJAX request?
Here is the solution I used based on the feedback:
window.onbeforeunload = function() {
for (page in ajaxing) {
if (ajaxing[page] != null)
ajaxing[page].abort();
}
};
var ajaxing = {};
function loadSubPage(page) {
if (typeof(initSubPages[page]) === "undefined") {
var ajaxRequest = $.ajax({
type: "POST",
url: '/Main/GetPageData',
data: { page: page },
success: function (returndata) {
// ...
},
error: function() {
alert("Error retrieving page data.");
},
complete: function() {
ajaxing[lot] = null;
}
});
ajaxing[page] = ajaxRequest;
initSubPages[page] = true;
}
}

Categories

Resources