Ajax Post getting cancelled in onclick attribute - javascript

I've seen duplicates of this question, however no solution seems to work for me. I'm trying to trigger an AJAX request based off of a link (the following). I'm writing in MVC 4. The AJAX request seems to go through well, I have a breakpoint getting hit on the other side, however the request gets cancelled by the browser. I can see this cancellation in Firebug, Chrome, etc. I found some suggestions that I need to return false at the end of the onclick handler to prevent other code from cancelling my event, however it doesn't seem to work. Are there additional quirks in the onclick handler that kill any outstanding AJAX requests? How would I stop that behavior?
Employees
function navClick(target) {
var serviceURL = '/Consequence/'+target;
try {
var dealerID = "5";
$.ajax({
url: '/Consequence/test',
data: { dealerID: dealerID },
type: 'POST',
success: function (data) {
alert(data);
},
error: function () {
alert("error");
}
});
} catch (err) {
alert("exception");
}
return false;
};

try adding a class to the link and trigger the click event off of that
Employees
then in your script
$('.linkEmployees').on('click', function(){
//your ajax call here
});

Related

AJAX call after onbeforeunload event is not working, only when refreshing the page

I am trying to handle the onbeforeunload event so that when the user closes the browser tab, a message will appear saying something like: Are you sure you want to leave this page? (The default browser message it's okay).
I was able to achieve something like this using this code:
window.onbeforeunload = function() {
return "";
}
But I realized that if I close the tab without refreshing the page beforehand, no message will appear. If I open the page, refresh (I can see a message from the browser) and then I click on close the tab, then I'm getting a message from the browser asking if I'm sure about leaving the page. If I don't refresh first, nothing happens.
I would like to do something like this (pseudo-code):
If user refresh the page:
Nothing happen
If user close the tab/browser:
Show browser alert message + run ajax call in the background.
I tried something like this but also didn't work:
window.onbeforeunload = function() {
$.ajax({
url: '/some-view/',
type: 'get',
dataType: 'json',
success: function () {
console.log("it works!");
}
});
return "";
}
Could someone provide a valid example for 2021? Almost all old stackoverflow questions are no longer supported by modern browsers and the methods are deprecated.
The problem is that ajax is an async call, and it won't wait for it to return anything. You can try to make your ajax call synchronous:
window.onbeforeunload = function() {
$.ajax({
url: '/some-view/',
type: 'get',
dataType: 'json',
async: false,
success: function () {
alert("it works!");
}
});
return "";
}
There is no reliable way to distinguish between reload and close. Page is being unloaded in both cases.

Cannot set $_SESSION variable when two synchronous ajax processing calls are sent

I have what might be a tricky question.
I am working on a form where it verifies a couple things on submit, using event.preventDefault(); to prevent the form from submitting if something went wrong. The issue here is that it sends multiple ajax requests at the same time, which seems to stop the php (which is processing the AJAX call) from modifying the $_SESSION variable.
I have determined this by changing the jquery ajax calls to process synchronously, allowing the $_SESSION variable to be changed.
My question is this: is there a way to allow the ajax calls to happen synchronously while allowing the $_SESSION variable to be modified during the process of those calls? I realize that the async:false for an AJAX call is deprecated, and obviously not the best solution.
Due to what each call does, it is not possible to combine the functionality of these two calls, although each call does not take long at all to process.
Example jquery code to explain how I am making these AJAX calls (some redaction and simplification, obviously):
$("#form-id").on('submit', function(event) {
$.ajax({
type: 'POST',
url: '/url/to/processing.php',
async:false, //fails without setting to false
...
});
});
...
$("#form-id").on('submit', function(event) {
$.ajax({
type: 'POST',
url: '/url/to/processing2ThatSetsSession.php',
async:false, //fails without setting to false
...
});
});
You have to concat the calls, to run one call after the other has ended.
I'll do it this way:
function ajaxPost(url, callback) {
$.ajax({
type: 'POST',
url: url
...
}).done(callback);
}
$("#form-id").on('submit', function(event) {
event.preventDefault(); // Always stop the event
// Do one ajax call and wait for the data
ajaxPost('/url/to/processing.php', function(data) {
// Do things with returned data and call the next ajax
ajaxPost('/url/to/processing.php', function(moredata) {
// Do something with moredata
// If everything is fine, re-post it but this time do not catch the event
$("#form-id").off("submit").submit();
});
});
});
You can add your own logic to show your error message in any callback and not continue with the next one.
With this I'll do an special method for multiple ajax form validation:
// This function will get an array of objects and
// do an ajax call and process the data, one after another
function multiAjax(calls, callback) {
var call = calls.shift();
if (call) {
var url = call.url;
post(url, function(data) {
var error = call.process(data);
if (error) {
callback(error);
} else {
multiAjax(calls, callback);
}
});
} else {
callback();
}
}
// This is the array of objects that multiAjax will process.
// You can add or remove elements to your likings, without modifying
// the submit event callback
var ajaxArray = [{
url: '/url/to/processing.php',
process: function(data) {
if (data.isWrong()) {
return "The data is wrong";
}
}
}, {
url: '/url/to/processing.php',
process: function(data) {
if (data != "OK") {
return "The data is not OK";
}
}
}];
// Now listen for the submit event
$("#form-id").on('submit', function(event) {
// Always stop the event
event.preventDefault();
// Do multiple ajax calls in one function call.
// Because the array is mutated inside multiAjax() (yeah, bad design but I've
// done this fast as an example), we slice() the array to get a new one
multiAjax(ajaxArray.slice(), function(error) {
if (error) {
// Show the error received
} else {
// submit the form the same way above
$("#form-id").off("submit").submit();
}
});
});
This is all untested code, but you get the point.
If one form submission is making two posts to the same PHP server, you should rethink the architecture instead of building complicated workarounds.
I would POST to a single PHP script that will do everything you need in the backend.
$.ajax({
type: 'POST',
url: '/url/to/all-processing.php',
... // send all the data needed by all processes
});
On the PHP side: all-processing.php
session_start();
require_once './process1.php';
require_once './process2.php';

Using ajaxForm plugin on view that is itself an AJAX response

I am building a messaging system for my site. The mailbox is flat, i.e. accessing the inbox, or sending a new message does not move to another page, it just toggles divs. When a user clicks a message, an AJAX call replaces the inbox div with the chosen thread. Inside the thread view, there is a form to reply to the message.
A few problems:
From inside this thread_view, which sends an AJAX response to a div nested inside the entire mailbox div, I don't have access to document objects outside of it. So, I can't manipulate divs outside of this view, such as the one that receives the AJAX beforeSend and Success messages. I think this may be accomplished with some kind of .load(), though I'm not sure exactly how.
My AJAX doesn't fire. I am using the Ajax.Form() plugin. I think this problem might be related to the first, but I can't say for certain. I'm not sure how to begin troubleshooting the Ajax request because I get no errors in the console.
I wonder if the problem has to do with the fact that I am trying to send an ajaxRequest from a view that is itself a response from a previous ajaxRequest, i.e. the entire view for the thread is a result of the following, in the same js file as the next request:
// compose a message function
$('#send_message').on("click", function(e) {
var send_message_options = {
type: 'post',
url: "/users/new_message",
beforeSend: function() {
//Display a loading message while waiting for the ajax call to complete
$('#message').html("Sending message...");
},
// Hide form and display results
success: function(response) {
$('#message').html(response);
}
};
$('#message_form').ajaxForm(send_message_options);
});
My new AJAX request, which does nothing:
$('#reply_in_thread').on("submit", function(e) {
e.preventDefault();
console.log("trying for reply");
var reply_options = {
type: 'post',
url: "/users/reply",
beforeSend: function() {
//Display a loading message while waiting for the ajax call to complete
$('#reply_message').html("Sending message...");
},
// Hide form and display results
success: function(response) {
$('#reply_message').html(response);
}
};
$('#reply_in_thread').ajaxForm(reply_options);
});
I couldn't say why the ajaxForm() plugin failed, but a jquery $.post was successful. The code that worked below:
$('#reply_in_thread').on("submit", function(e) {
e.preventDefault();
var data = $(this).serialize();
$.post('/users/reply',data,function(response){
$('#reply_message').html(response);
})
});

ajaxStop() doesn't fire

This is the code that wasn't working:
$(document).ajaxStop(function() {
$(this).unbind("ajaxStop"); //prevent running again when other calls finish
// Display everything
display();
});
And here's my Ajax function:
function getAjax(url, callback) {
jQuery.ajaxPrefilter(function( options ) {
options.global = true;
});
$.ajax({
url: url,
type: "GET",
dataType: "jsonp",
success: callback
});
}
Why does ajaxStop() never fire?
You'll notice I was making JSONP requests. It took me forever to find this, but the answer to this issue can be found here.
From the ticket:
JSONP requests are not guaranteed to complete (because errors are not
caught). jQuery 1.5 forces the global option to false in that case so
that the internal ajax request counter is guaranteed to get back to
zero at one point or another.
If you want all requests to fire the events, no matter what (and at the risk of the same inconsistencies 1.4.4 exhibited), you can use the following prefilter:
jQuery.ajaxPrefilter(function( options ) {
options.global = true;
});
Case in point: http://jsfiddle.net/X4JTx/

jQuery Ajax HTTP Request INTO a click function - not working

My question is:
Is it possible to do an Ajax request WITHIN a click function, with jQuery? (see example below), If so, what am I doing wrong? Because I'm not being able to do any request (I'm alerting the data through my success function and nothing is being retrieved).
Thank you very much in advance for any help! :)
function tracker(){
this.saveEntry = function(elementTracked, elementTrackedType){
var mode = "save";
var dataPost = "mode="+mode+"&elementTracked="+elementTracked+"&elementTrackedType="+elementTrackedType;
$.ajax({
type: "POST",
url: 'myURL',
data:dataPost,
success:function(msg){
alert(msg);
},
beforeSend:function(msg){
$("#trackingStatistics").html("Loading...");
}
});
return;
},
this.stopLinksSaveAndContinue = function(){
var fileName;
$("a[rel^='presentation']").click(function(e){
fileName = $(this).attr("rel").substring(13);
this.saveEntry(fileName,"Presentation");
})
}
}
If your anchor is linked with the href attribute, then this may be interrupting your AJAX request. A similar problem was recently discussed in the following Stack Overflow post:
window.location change fails AJAX call
If you really want to stick to using AJAX for link tracking, you may want to do the following:
Link
With the following JavaScript logic:
function tracker(url) {
$.ajax({
type: 'POST',
url: 'tracker_service.php',
data: 'some_argument=value',
success: function(msg) {
window.location = url;
}
});
}
Have you considered the possiblity that the request might be failing. If so, you're never going to hit the alert.
Can you confirm that the beforeSend callback is being fired?
Also, I'm assuming 'myURL' isn't that in your real-world source code?
There may also be something awry in the }, that closes your function.
Im guessing some sort of error is being generated. Try adding
error:function(a,b){
alert(a);
},
After 'success'

Categories

Resources