How to manully trigger an ajaxComplete event - javascript

Using Jquery I need to trigger a ajaxComplete event.
At the moment I'm using this code with no success
$.getJSON(assetUrl, function (data) {
...
$.trigger("ajaxComplete");
With Error:
TypeError: 'undefined' is not a function (evaluating '$.trigger("ajaxComplete")')
Any idea what I'm doing wrong? Thanks

The ajaxCompleted event is fired on the DOM, and you will need to call the trigger method on a jQuery wrapper element: $(document).trigger(...), for example.
There is not static function "trigger" on the jQuery object (that's what the error message is telling you), you might use $.event.trigger - though I fear that's internal.
However, you won't need to do it manually; getJSON does trigger the event itself. For aborting a running ajax request, see the abort method of XHR objects.

You can define a global jQuery ajaxComplete (and ajaxError) function that will run on document ready and after every completed ajax request. You can define the ajaxComplete function on the intial page load (or whenever really) like this:
$(function(){
$(document).ajaxComplete(function(){
// on complete code
}).ajaxError(function(){
// on error code
});
});
To call this event handler at any time, just execute the following:
$(document).triggerHandler('ajaxComplete');

If anybody else is looking at this, the correct way to manually trigger ajaxComplete is $(document).trigger('ajaxComplete', [xhr, settings]);
It's probably important to pass the xhr object to the ajaxComplete trigger event, as the event handler might need it.
However, you only need this, if you're not making your requests through jquery, since jquery handles this automatically for you.

Related

xhr.send() does not trigger ajaxComplete/ajaxSuccess, but $.get does. Why?

Imagine I have these three functions:
$( document ).ajaxSuccess(function( event, xhr, settings ) {
console.log('ajaxSuccess fired');
});
function doCall1 () {
var xhr = new XMLHttpRequest();
xhr.open('get', 'someurl.com', true);
xhr.send();
}
function doCall2 (){
$.get('someurl.com');
}
When I call doCall1, ajaxSuccess does not fire. However, when I call doCall2, ajaxSuccess does fire.
I understand this is related to the fact jQuery is in fact using a callback function to various methods of $.ajax() rather than looking at onreadystatechange / readyState of the XMLHttpRequest (correct me if I'm off the mark), but I still don't completely understand.
Can someone give me a quick explanation or direct me to some docs that'd get me the rest of the way to getting this?
As others have noted, ajaxSuccess and ajaxComplete are non-native events added by jQuery. If for some reason you wanted interop between jQuery and vanilla js, you could dispatch the events yourself (with the caveat that browser support for CustomEvent is limited):
var event = new CustomEvent("ajaxComplete");
document.dispatchEvent(event);
Thats because the ajaxSuccess and ajaxComplete methods are part of jQuery and they are only triggered by the jQuery functions.
XMLHttpRequest is a native javascript object and its not related with jQuery.
The code for triggering ajaxSuccess/ajaxComplete are written in the end of $.ajax(), $.get(), $.post(), etc. The above events are related to jQuery and the $.ajax(), $.get(), $.post() functions are jQuery functions.
The XHR is native JavaScript and is no way related to jQuery.
the one thing is the jQuery object having deferrers and the other one a native JavaScript object, where you have to attach a callback yourself and may forward it to the ajaxSuccess of jQuery (jQ wraps the native XMLRequest object and does that).

Call jquery function without any particular event handler

How to use jquery functions more similar to javascript ? What i mean about that, is to call a function from script tag in html like do_something()and this will trigger the function.
I have on my jquery script file $(document).ready(function() {... } and it contains some functions with onclick handlers and others, but how to trigger function by just simply inserting name of that function in html, which can be call in some instances while processing code and loading page ?
jQuery is just a JavaScript library. Its functions are JavaScript functions. You can call them in the same way as any other JavaScript function.
Passing a function as an argument to ready just means "When the ready event fires, call this function". It's similar to setTimeout(function () { … }, 5000) only with a condition other than "after 5 seconds".
It sounds like you are having trouble with the scope that $(document).ready(function(){...}) creates;
You will want to place do_something() outside of the $(document).ready(). This will allow your DOM (in html) handlers to call it.
Also keep in mind that $(document).ready() is only used to make sure that the DOM is ready before JS tries to interact with it. If you are placing your JS in the html, the DOM will be ready by the time the functions are called.
You may want to see this question for more details:
Global javascript variable inside document.ready

get error message from jquery's eventData object

I currently have a javascript error handler like this:
window.onerror = function(msg, url, line){ //stuff }};
But I would like to be able to use jquery to attach to onerror like so:
$(window).error(function(evtData){//stuff});
My question is, from jquery's eventData object, how can i get the error's message, url, and line number, as I did in the non-jquery function?
Thanks in advance.
From jQuery docs.
Note: A jQuery error event handler should not be attached to the
window object. The browser fires the window's error event when a
script error occurs. However, the window error event receives
different arguments and has different return value requirements than
conventional event handlers. Use window.onerror instead.
Refernce: http://api.jquery.com/error/

Events on DOM elements not yet created, in Javascript?

I have a Javascript module the following Javascript:
EntryController = function$entry(args) {
MainView();
$('#target').click(function() {
alert('Handler called!');
});
}
MainView() has a callback that creates the #target button. Because of the callback the code will pick up and run through the rest of the code $('#target') ... before #target is created. If this is the case the event is never hooked up to the #target. If I put a breakpoint at $('#target') that'll give the callback enough time to return and build the #target, when I press play everything works as expected.
What's the best way to deal with this? I would like all events to take place in the controller so it can choose which view to send it to.
I was thinking about placing the entire $('#target').click ... inside MainView() and instead of alert('Handler called!'); I'd put a references to EntryController.TargetEventRaise(), but that started to look a bit like steady code. What's the best way to approach this?
You're looking for jQuery's live event handlers, which will handle an event on every element that matches the selector, no matter when the element was created.
For example:
$('#target').live('click', function() {
alert('Handler called!');
});
Alternatively, you could make the MainView function itself take a callback, and add the handler in the callback. You could then call the callback in MainView inside of its callback.

JQuery error property for error handler

I'm just playing around for the first time with jQuery's ajax functionality. I wanted to add a function that could handle any errors. So, in one of my client javascript blocks, I added the following line:
<script type="text/javascript">
....
$.ajax({ error: function () { alert('boo'); } })
....
</script>
I expected that this would bind the error handler, so that when an error occurs, it would fire the anonymous function included.
What happens instead though, is that it immediately fires the function on page load, as soon as it parses this line of code.
What am I doing wrong? What is the proper way to bind the ajax error handler?
I'm not sure if I understood your question correctly, let me know if I've misunderstood.
I assume that you are trying to create a generic ajax call error handler? If that's the case, you have got the wrong idea.
Are you are just trying to bind the event handler? In this case, you are executing it.
I would recommend you read and check out the examples on these jQuery API reference docs:
API/1.3/Events
Ajax/jQuery.ajax
Also check out the post link provided by F.Aquino and this SO post: JavaScript Exception Handling.
This is could be helpful too: Handling AJAX Errors With jQuery.
You want to change the global settings. Check jQuery documentation.
$.ajaxSetup({
error: function () { alert('boo'); }
});

Categories