Event when call ends / JavaScript - javascript

We want to log the JavaScript on our Website. For that I am overwriting the log functionality with my own implementation.
On the server side we are using Log4Net for our logging. My idea now is to capture the log on the client side and send it to the server with ajax. How ever I don't want to send the Ajax request every time someone types log. So my idea was to catch all the logs and send ONE request after the call-stack ended up where it has began.
Is there an event or a way to detect when call-stack has "ended" ?

You can try to use javascript beforeunload event to send your log when user leave a page.
If you use jQuery, the code look like:
$(window).bind("beforeunload",function(event) {
//... put your ajax code here ...
return "The log has sent to server.";
});
however beforeunload event will show a message box on your screen.
Also if you want to run a function after another function run, you can use jQuery $.when() method as below:
$.when(functionOne(), functionTwo()).then(functionThree()).done(functionFour());
functionOne(), functionTwo(), functionThree(), and functionFour() must be a deferred object.
This blog give a simple explanation how to implement deferred object.

Related

NODE.JS: How to have front-end JS event listener for when there is a back-end error on form submit?

Using Node.js, I have a form that uses twilio to send an SMS. Everything works fine testing it with my phone.
However, I would like to have an animation play (in my front-end JS file) if the form submit encounters an error in the back-end. Specifically, the twilio API has a callback that takes an error as an argument with the sendMessage function. So I'm not talking about validation errors, but actual errors with twilio or the connection.
So how do I have an event listener in my front-end js files to listen for when there is an error in the callback function of submitting the form (in the back-end) so I can play an animation expressing something went wrong.
Or should I not use event listeners and do it another way?
Any help appreciated. Please respond. Thank you!
No you cannot add an event listener in the front-end for an error in the back end. That is not possible.
If using a HTML form without AJAX:
Now you are using the default HTML form and using the action and method attributes to submit the form data. Then the process will be similar to what you do with error handling. You submit the data then proceed with your interaction with Twillo API. If something fails you redirect the user to the form page with the error message/error animation.
If using AJAX:
Now as you are using AJAX you must have the ability to handle the response you get from the server.
In this process when the user submits data the back-end proceeds with the interaction with Twillo API. If something fails you send back an 500 Internal Server Error with the proper error message.
In the AJAX request callback you check the response code and error message. If something is wrong you can now play the error animation/let the user know about what happened.
Resources:
https://nodejs.org/api/synopsis.html
Check the example in this link. It is shown how to set statuscode for the response.

Using Data Generated from AJAX Call for OnClick Event

I have a web application where I want to get some data from an API right when the document is ready to execute javascript. I want to store this data in an Object for later access. When a user clicks on a certain link on the page, I will need access to this Object.
I'm wondering what the safest/most accepted pattern for achieving this is, since it involves to events to listen for (the success of the AJAX request and the later possible click). I don't really want to wrap all of my code in the AJAX request if I don't have to, but I also don't want to run the risk of the user clicking before the AJAX request has finished (it's a fairly small API call, but still).
Deferred objects to the rescue!
(function($){ // this prevents polluting the global scope
var request = $.ajax({...});
//... later on...
$(someelement).on("click",function(){
request.done(function(data){
console.log(data);
});
});
})(jQuery);

can't change location of webpage using "window.onbeforeunload"

Can anybody pls tell me, how can i make a AJAX request and send user to some other page when he performs following actions ?
Clicks on next, prev btns of browser.
refresh page by any way(f5,ctrl+r,refresh btn).
try to close browser's window(Here i don't want to redirect him, just AJAX request).
i thought window.onbeforeunload could make it,
window.onbeforeunload = function () {
makeAjaxCall();
------
------
}
// Ajax Call is successful
function makeAjaxCall_SuccessHandler() {
window.location.href = 'Home.html';
}
but it is not working at all........
after searching on this topic i found that this is a kind of rule made for browser's security.
so pls tell me how to do this or any alternate way to achieve this.
You're not describing the actual behavior you're getting so I'm kinda guessing here, but I think your problem here is with the Asynchronous part of AJAX.
You see, when your onbeforeunload handler executes it may very well initiate the AJAX call BUT it won't block waiting for its results to return. Instead the execution will continue and onbeforeunload will complete before you ever get any result from your AJAX request (if any call is made at all).
First of all add some debug traces to validate your handler is actually executed. If it is, add an idle loop to keep it busy (preventing it from returning) and see if the AJAX call comes through (I'd check the server side for that).
If that's indeed the case I guess you'll have to modify the idle loop to consult some kind of flag. Or even better, if the libraries you use allow it, make the server call synchronous.
I think no.
Browsers can stop execution at any time after action. Ajax call is very long operation for this.
With onbeforeunload you can asking user questions like "Are use sure?". You must return string or assign it to event.returnValue
You can read about it here https://developer.mozilla.org/en/DOM/window.onbeforeunload
I think with your problem you can try to make synchroness call or try to open iframe with some GET parameter or send form data in iframe in body of this function. But i don't sure about time.

Track Ajax requests on a page

I have a web page and I am associating a note with the page storing it in my database, so that the whenever the next time the page is loaded that notice can been seen till it is deleted by some other user authorized to do the same. However, say I associate a note with the page after some content is loaded through AJAX. I want the note to appear only after that particular content has loaded next time on the web page. I would like to track the AJAX request and attach the note to it? I want to do it all through simple JavaScript code put at the bottom of any web page. How can it be done?
jQuery ajax provides methods to fire events before, during and after the ajax request. Please check the api here for complete list.
Here are couple of methods that are called after completion of every ajax request.
jQuery.ajaxComplete() - Register a handler to be called when Ajax requests complete.
jQuery.ajaxSuccess() - Show a message when an Ajax request completes successfully
These functions allows you to pass a callback function to trigger after event occurs. In that call back function check if content you want is loaded or not, then show the note.
Sample code for the above methods can be found here:
http://api.jquery.com/ajaxComplete/
http://api.jquery.com/category/ajax/
Hope this helps.
You'd need to write a wrapper for all of your ajax calls that checks the result and sees if it should add a note. Here's an example, assuming you're using jQuery to handle the ajax requests:
function ajaxWrapper(settings){
var old_callback = settings.complete;
settings.complete = function(request, status){
if(status == "200"){
// check the request.responseText and add your note if appropriate
}
if(old_callback){
old_callback(request, status);
}
}
jQuery.ajax(settings);
}
And then instead of calling jQuery.ajax() directly, call ajaxWrapper() instead.
An alternate option would be to include the note in your ajax response.

Can Response.Redirect and OnBeforeUnload play nice together?

Does anyone know how to detect in a OnBeforeUnload event that the server side code sent a Response.Redirect? I want to prompt a user to keep them from moving away from a page before it's time, but when the server redirects I it shouldn't prompt the user.
I'm working with legacy code that extensively uses Response.Redirect and I'm not interested in changing the way the redirect occurs. Please don't suggest I use X redirect method.
It should be possible to do this based on the response code in the XMLHttpRequest object as a response redirect should send back a 302.
Edit: The Response.Redirect sends back a 200, with a redirect code in the body which then does a window.location.href = new page in the ASP.Net code. Is there any way to get to the server response to determine that this has happened?
I worked out a solution to it.
When the PageRequestManager is processing the response from the server, it will set the _processingRequest flag. In order to allow response.redirect to pass through, I changed my javascript to check for that. The event now looks like this:
window.onbeforeunload = function() {
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (!prm._processingRequest){
return "Are you sure you want to leave?";
}
};
For non-ajax pages, you're out of luck since the page is never sent to the browser, just the 302 header. So there's no opportunity for javascript processing of OnBeforeUnload.
With ASP.NET AJAX a Response.Redirect really isn't doing a 302. It's sending back a message via the XMLHttpRequest and ASP.NET AJAX is simulating a 302. In theory you could intercept this and perform your own processing...
Yes, Response.Redirect has an overload that lets you decide whether or not to terminate the request (raise a ThreadAbortException). If you let the Response finish (pass false as the second parameter); OnBeforeUnload will also run.
However, simply running OnBeforeUnload will not help you in this case, since your client side code (the prompt) will run before a new page can be sent to the browser (and, if you redirect, it will also only be the 302 header and not the real page).
I would use AJAX to query the server, and if it reports the operation to be completed, allow the redirect in the Javascript code.

Categories

Resources