Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to manage chained AJAX calls with jQuery
    text
    copied!<p>I have this website that connects with a local service that manages a CardReader with a PIN Pad. There are many different operations that can be completed using this device. Heres an example of one of them:</p> <ol> <li>Lock the device</li> <li>Ask for PIN number</li> <li>Release device</li> </ol> <p>Before I used to chain the callbacks between each other, but now, because there are new operations, that also use methods like "lock" and "release", I need to change my code, so that the code for step 1 and 3 is reusable.</p> <p>I have been trying to solve this with jQuery promises, but Im quite new to this, and I still havent really figured out how they work. Can someone give me a hand?</p> <p>This is an example of the code im using now. I have removed the business logic from inside the functions, to simplify the example:</p> <pre><code>var CardReader = { //////////////////// // Different possible messages to the Card Reader //////////////////// lockDevice: function() { this.makeAjaxCall("GET", "/LockDevice", this.lockDeviceCallback); }, getPin: function() { this.makeAjaxCall("POST", "/getPin", this.getPinCallback); }, releaseDevice: function() { this.makeAjaxCall("POST", "/Release", this.releaseDeviceCallback); }, ////////////////// // Callbacks for each message to the Card Reader ////////////////// lockDeviceCallback: function(jqXHR, textStatus) { if (textStatus !== "success") { return; } this.getCardLogin(); }, getCardLoginCallback: function(jqXHR, textStatus) { if (textStatus !== "success") { return; } this.releaseDevice(); }, releaseDeviceCallback: function(jqXHR, textStatus) { if (textStatus !== "success") { return; } //End }, //////////////// // Other methods //////////////// init: function() { // UI BIndings $(#button).on("click", this.logIn.bind(this)); }, logIn: function() { this.lockDevice(); }, makeAjaxCall: function(callType, resource, callbackMethod) { $.ajax({ type : callType, url : "http://localhost:1337" + resource, cache : false, dataType : "json", contentType: "application/json", context : this, complete : callbackMethod }); } }; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload