views:

275

answers:

3

Hello all, 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?

+2  A: 

This link has a working implementation (ignore the success callback, its wrong)

F.Aquino
+2  A: 

I'm not sure if I understood your question correctly, let me know if I've misunderstood.

  1. 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.

  2. 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.

o.k.w
Ah! Got it, thanks! Yes, I was trying to create a generic error handler for all ajax calls, as I am using $.get() to actually perform the calls. Looking at the provided links from both answers, I realized that the $.ajax() function is not a configurator, but actually runs an ajax call. The correct function to call which fixed it is $.ajaxSetup({error: function() { alert('boo') } }). Thanks for the help!
eidylon
Glad you that you got it! I was still trying to find a better way to explain. :)
o.k.w
+2  A: 

You want to change the global settings. Check jQuery documentation.

$.ajaxSetup({
  error: function () { alert('boo'); }
});
Jace Rhea