Callback not being triggered after AJAX request

I am currently troubleshooting some code that was not written by me, and I am facing challenges in understanding why an Ajax return is not triggering a Callback. The following code is responsible for attaching behaviors to the ajax functions:

  # Callback before AJAX request sends
cbBeforeSend = (jqXHR, settings) ->
  console.log jqXHR
  # initialize message/status elements
  $flashIcon.attr 'class', 'icon icon-refresh icon-spin'
  $flashError.html ''
  $flashNotice.html ''

# Callback when AJAX returns with success
cbSuccess = (data, textStatus, jqXHR) ->
  console.log 'success'
  $flashIcon.attr 'class', 'icon icon-ok-sign'
  window.globalLoadCallback()

# Callback when AJAX returns with error
cbError = (jqXHR, textStatus, errorThrown) ->
  console.log 'error'
  $flashIcon.attr 'class', 'icon icon-remove-circle'
  if /text\/javascript/.test jqXHR.getResponseHeader('Content-Type') 
    eval jqXHR.responseText

# Callback when AJAX returns
cbComplete = (jqXHR, textStatus) ->
  console.log 'cbComplete'
  if $flashIcon.is('.icon-refresh')
    $flashIcon.attr 'class', 'icon icon-warning-sign'

Our application includes two links to the Quoting/Quote path:

The new quote link works fine and triggers the 'success' and 'cbComplete' callbacks as shown above. Here is the code snippet for that link:

<li>
  <%= link_to new_quoting_quote_path, remote:true do %>
    <i class="icon icon-plus-sign"></i>
    <span>New Quote</span>
  <% end %>
</li>

The edit quote link navigates correctly to the appropriate partial and shows the object in the console, but doesn't trigger the 'success' and 'cbComplete' callbacks (nor does it show an error). Only the 'cbBeforeSend' callback is triggered because the classes on flashIcon remain as "icon icon-refresh icon-spin". There doesn't seem to be an issue with crm_connection since the link is rendered in the browser as "/quoting/quotes/183/edit", suggesting that the correct ID is being supplied. Here is the code for that link:

<%= client_management_tab 'Health', edit_quoting_quote_path(@crm_connection) %>

Unfortunately, I cannot provide more details as I did not write this code and my task is limited to fixing it. Thank you for any assistance you can offer.

I believe this segment of code is responsible for handling the requests:

  $flashInfo   = $('div.flash-info')
  $flashIcon   = $flashInfo.find('i#ajax-status')
  $flashError  = $flashInfo.find('#flash-error')
  $flashNotice = $flashInfo.find('#flash-notice')
  $(document).bind 'ajax:beforeSend', cbBeforeSendBound
  $(document).bind 'ajax:success', cbSuccessBound
  $(document).bind 'ajax:error', cbErrorBound
  $(document).bind 'ajax:complete', cbCompleteBound

$.ajaxSetup(
  beforeSend: cbBeforeSend
  success: cbSuccess
  error: cbError
  complete: cbComplete
  )

Answer №1

According to the jQuery documentation for ajaxSetup:

Description: Establish default values for upcoming Ajax requests. It is advised against using this feature.

I recommend modifying your call and assigning the callbacks directly to your individual ajax request:

jQuery.ajax({
    url: 'blah/blah',
    success: cbSuccess,
    error: cbError,
    etc
});

Answer №2

When jQuery.ajax has its own callback set, it will likely disregard any callbacks provided by ajaxSetup. This means that these callbacks are not very reliable for anything other than default settings, as mentioned by Ricardo in his response. The developers of jQuery also advise against using this feature.

Fortunately, there are alternative options available. jQuery offers a variety of global ajax event binding functions:

jQuery.ajaxStart, jQuery.ajaxStop, jQuery.ajaxComplete, jQuery.ajaxError, jQuery.ajaxSuccess, jQuery.ajaxSend

By utilizing these functions to bind events, they will always be triggered by ajax calls made through jQuery. However, keep in mind that setting the option "global:false" in the actual ajax request can override this behavior.

If you find yourself in a situation where "global:false" is being used, your best bet is to follow Ricardo's advice and modify the jQuery.ajax calls to include the necessary bindings.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to use JQuery to inject a variable containing HTML into a specific div element?

Hey there, I have a basic webpage with a div element (let's name it #content) that holds HTML content I want to save to a variable. <div id="content"> <div id="left"> <h1>Awesome heading</h1> <p>text</ ...

How to use a jQuery selector to retrieve the value of an element that is located near another element

I am dealing with the following HTML code snippet. In my JavaScript, I have an HTML element with the id <input id = "Test[0]name">. My next task is to retrieve the value of the select element that has an id ending with "address". <div> < ...

Identify all the CHECKBOX elements that are visible and not concealed

On my page, I have various checkboxes - some with hidden=true and others with hidden=false attributes. Despite trying to use a selector or jQuery to locate checkboxes with the hidden property, I am still facing some challenges. My goal is to differentiate ...

Are there any superior alternatives for Android webviews?

Is there a more efficient webview option available for Android? Google's documentation advises against relying on the built-in webview object. It's puzzling that using webkit in Android is so limited compared to other mobile devices with similar ...

Tips for incorporating HTML code within a select option value?

I am working with AngularJS to create a Visual Composer for a website. One feature I want to incorporate is the ability to add HTML code based on the selection made in a dropdown menu. However, I am struggling to figure out how to include the HTML within t ...

Setting the value for a HiddenField using jQuery in an ASP.NET application

Is there a way to set a value for a HiddenField control using jQuery? function DisplayContent(obj) { var FareValue = $(obj).closest('tr').find("[id*=lbFare]").text(); $(obj).parent().parent().find('[id*=pnlGrd]').show(); $ ...

Display options through numerical selection

I have been attempting to construct something, but I'm encountering difficulties. My goal is to create a functionality where entering a number in an input field will generate that many additional input fields. I've attempted to implement this us ...

How can the seating arrangement be optimized for a seating chart and what is the most effective way to transition away from a traditional table structure?

Currently, I am attempting to create a dynamic seating chart on a webpage within an asp.net-mvc site using data retrieved from a database. Initially, I used a table to organize the grid layout of rows and columns, which resembled this structure: The datab ...

Using Stored Procedures to Retrieve and Input Information from SQL Server

I have developed a stored procedure that handles inserting and retrieving data from SQL Server. CREATE procedure prc_add ( @name varchar(128)='', @email varchar(128) ='' ) as begin insert into students(name ,email) ...

Tips on concealing all classes except one through touch swiping

If you have a website with a single large article divided into multiple sections categorized as Title, Book1, Book2, & Book3, and you want to implement a swipe functionality where only one section is displayed at a time, you may encounter some issues. ...

How can I properly integrate jQuery libraries, along with CSS, in a create-react-app project?

I'm currently working on incorporating the select2 jquery library into my React application, which was created using create-react-app. After adding jquery and select2 to my package.json file, I was able to get the javascript functionality to work pro ...

Possible for jQuery autocomplete to reposition the list?

Is it feasible for me to adjust the position of the dropdown list by moving it down 4 pixels? I've experimented with various styles within .ui-autocomplete {}. These include: margin-top: 4px; top: 4px However, these modifications don't appe ...

Adjustable slider height in WordPress

Struggling with the height of the slider on my website. I've tried various CSS adjustments and even tweaked the Jquery, but it still doesn't display properly on mobile devices. For instance, setting a height of 300px looks perfect on desktop brow ...

Creating a scrolling effect similar to the Nest Thermostat

After researching countless references, I am determined to achieve a scrolling effect similar to the Nest Thermostat. I came across this solution on this JSFiddle, but unfortunately, the parent element has a fixed position that cannot be utilized within my ...

Excellent resource for Python documentation similar to ruby-doc.org

Although I am passionate about Python, I must admit that I find its online documentation quite lacking compared to Ruby. Ruby seems to have a plethora of well-organized documentation sites: http://api.rubyonrails.org/ (I understand this is Rails-specific ...

Is it possible to have the cursor rotate or animate by 45 degrees when clicked

Do you know how to create a unique custom cursor using CSS? Say, for example, we have this code: cursor: url(images/cursor.png) 15 15, auto; Now, what if we wanted to take it up a notch and make the cursor rotate -45 degrees when clicked, and then revert ...

The dropdown menu vanishes from sight as soon as the cursor moves away from a link

Recently, I encountered an issue while trying to create a dropdown menu using Jquery. The problem arose when attempting to select the second link, as the entire menu would disappear. Additionally, is there a way to ensure that only one dropdown menu is vis ...

PHP Database Query Automation

Looking to continuously query a database every .5 seconds in PHP to check for a specific field's status. Although I have achieved this functionality in Java, I am uncertain how to implement it in PHP due to the lack of threading support. While researc ...

Encountering an error while trying to add text: SyntaxError - Unexpected token 'for

I'm trying to print out the elements of an array using JavaScript. let listToArray = ["a","b","c"]; $(".tooltip").append(for(let i = 0; i < listToArray.length; i++) {listToArray[i]}); But I keep getting an error that says Uncaught SyntaxError: U ...

Error occurs when multiple checks are performed on the same script during form validation

I have recently developed a script that validates email addresses and checks for the availability of usernames. However, I am encountering an 'error on page' issue when I try to check both textboxes simultaneously. Strangely, if I test them indiv ...