Hold off on triggering the href action until the ajax call has been completed

Is it possible to delay the execution of a click on an anchor href in a Backbone view until an ajax call has been completed?

I am looking for the following functionality:

  1. User clicks an href;
  2. Click triggers an ajax call;
  3. If the ajax call is successful, then the href should be executed;

I attempted a test by adding a method to a Backbone view linked to an anchor:

    clickNext: function(e){ 

        setTimeout(function(){
            console.log("test"); 
        }, 5000); 

Unfortunately, the href is being executed before the timeout finishes.

The necessity for this functionality arises from my desire to create a wizard where each page has a separate URL. I need to perform checks using local storage on each pageload and save data persistently using Ajax on every "Next" click.

Answer №1

In order to prevent the original click event from triggering a location change, utilize e.preventDefault(). Afterwards, you can manually adjust the window hash location within the done or success callback function after a successful ajax call.

myApp.Views.ExampleView = Backbone.View.extend({
    el: "#myView",
    events: {
        "click a": "handleLink"
    },
    handleLink: function (e) {
        e.preventDefault();
        var link = $(e.currentTarget).attr('href');
        $.ajax("/echo/json/")
            .done(function () {
            location.hash = link
        })
    }
});

var myView = new myApp.Views.ExampleView();

fiddle - http://jsfiddle.net/leighking2/hjcg77h2/

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 can I hide a div using Ajax and show success in the following div?

I'm utilizing ajax to implement search functionality onkeyup. The goal is to display all results if the textbox is empty, but when the textbox contains text, only show results that match. <input type="text" onkeyup="searchme()" id="search_id" /&g ...

I am experiencing an issue with my route where the Passport JWT req.user is unexpectedly undefined

Setting up JWT with my express app has been quite the challenge! Despite getting most of it working, I've encountered a strange issue. My register and login routes are generating valid tokens and authentication works fine in the '/users' rou ...

Comparison of Arrays Containing Objects

I'm looking for a way to compare arrays of nested objects in Mongoose. In the scenario below, I am seeking results where the name properties match. Is there anyone who can assist me with this? Organisation.find( { $or: [ { "c ...

Dependable timekeeping tool for an online discussion platform

Seeking assistance in selecting the best solution (nodeJS + socket.io + redis) for a chat room timer. In this scenario, multiple Rooms are created with each room having a designated HOST or admin and up to 500 members. The number of rooms can vary at any ...

Correlating Mailgun Webhook event with Mailing list email

Recently, I have started using the Mailgun API to send emails and have also begun utilizing their mailing list feature. When sending to a mailing list, such as [email protected], I receive a single message ID. However, when receiving webhook responses, t ...

Encountering issue - SCRIPT5022: Error parsing message from server in Sys.WebForms.PageRequestManagerParserErrorException

I'm in need of assistance. I've developed a web application in .Net 3.5 that utilizes asp.net Master page, update panel, and server controls. The asp.net page created with the Master page includes an update panel that contains other server contro ...

The speed at which a DIV moves when dragged with JavaScript mouse events is too fast

I am currently working on moving the #frame-slider-thumb across the image. Initially, I achieved this by monitoring the difference in mouseX position. However, a problem arose where if the thumb was not at 0 to start with, it would jump back to 0. To add ...

The uploading of a file in NodeJS is not possible as the connection was closed prematurely

When I created a website using nodejs, there was a specific page for uploading images to the server. It worked perfectly fine when tested on my computer. However, upon deploying it to the server, the upload functionality stopped working. Upon checking the ...

Having difficulty accessing the attributes of an object within a property

I am encountering an issue when trying to access the properties of an object that contains a reference property of another object. Essentially, there is an object nested within another object. Upon fetching data from API calls like this one for instance:, ...

Utilizing Knockout to Render JSON List Items

Utilizing Knockout.js to dynamically update a view from JSON response has been my current focus. The structure of the JSON is as follows: var data = { "Properties": { "Engine Capacity": "1499cc", "Doors": 3, "Extras": [ "LED lights", ...

The issue with CORS is preventing the AJAX POST request from reaching the Express.js server, even with body-parser configured

Recently, I have been trying to send an AJAX POST request from my HTML page that is hosted on an Apache server. The goal of this request is to post a filename to an express.js server in order to perform some operations with another node. To facilitate this ...

smoothly slides into view and playfully bounces

http://jsfiddle.net/E6cUF/ The concept involves a grey box sliding left from behind a green box after the page is fully loaded, with a slight bouncing effect if possible. Update: I created a new version inspired by modifications made by others on the jsf ...

JavaScript encountered an issue when trying to display HTML content

Through my PHP code, I am attempting to create a popup window that displays the content of an HTML file. However, after adding script tags, no HTML content is displayed. When I tried echoing out $row2, only the word 'array' appeared on the screen ...

Using Chrome with Selenium WebDriver in JavaScript (webdriver.js)

I have been using Selenium Webdriver with Chromium and everything works perfectly. However, when I try to switch to Chrome (which I prefer because it supports headless mode in the latest version), I encounter a problem where Chrome fails to start up proper ...

An alternative option for the location parameter in the post

$.post("location_example.php",{data:data},function(){ //performing some action }); I attempted to specify the full location path as "localhost:8888/myweb/data/index.php", but it does not seem to be posting anything. It appears that the parameter cannot ...

Ways to adjust the brightness of any color when hovered over

Is it possible to create a universal effect where an element becomes darker or lighter when hovered over, regardless of the initial color? Here is an example: .change-color{ Background:green; width:100px; height:100px } .change-color:hover{ Background ...

Saving the data retrieved from an ajax request

I am facing an issue with storing a variable from an ajax get request that calls a PHP script. The data is successfully retrieved and stored in the variable within the PHP script, but when I return to the code containing the ajax request, the variable appe ...

Executing multiple calls with Angular's $http service and then resolving them within a loop using underscore

I am facing an issue while trying to fetch multiple data from $http inside _.each function and display the combined data in $scope.tasksData. The problem I encountered is that _.each is being executed later, causing it to return null first. Can someone pl ...

Generate selection choices by looping through a JSON document

I am attempting to develop a search box that will provide autocomplete suggestions based on user input from a key-value pair in a json file. I initially thought using datalist would be the most suitable approach for this task, however, upon running the cod ...

Finding ways to access intricate JSON objects in Angular 2

//component.ts public items: any; getResult(){ var jsonBody = {}; jsonBody['activity'] = this.activity; jsonBody['seatnumber'] = this.seatNo; this.localService.postCall(jsonBody) .subscribe( data =& ...