0

Good Day!

I came across an interesting issue while coding an extension I've been fiddling with for a while-- showing/hiding a specific button based on an 'if statement' inside a jQuery get() function. Since the function takes longer than the buttons and other elements to load, when calling a variable defined by the jQuery get() results to determine the button display (block or none), it returns undefined. Several solutions I have thought of are a possible setTimeout() to grab the value after an x amount of seconds, but this approach is not viable since the display should be dependent on the completion (success or failure) of the get statement, similar to an onload is to the html body.

Any Ideas?

flancast90
  • 101
  • 6
  • https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call?rq=1 – CBroe Nov 27 '20 at 13:52

3 Answers3

1

Create a promise that will have a callback that will call your function after the request has completed. See Mozilla Docs for more info on promises.

function get(url) {
// Return a new promise.
return new Promise(function(resolve, reject) {
    // Do the usual XHR stuff.
    var req = new XMLHttpRequest();
    req.open('GET', url);

    req.onload = function() {
      // This is called even on 404 etc so check the status.
      if (req.status == 200) {
          // Resolve the promise with the response text.
          resolve(JSON.parse(req.response));
      }
      else {
          // Otherwise reject with the status text which will hopefully be a meaningful error.
          reject(Error(req.statusText));
      }
    };
    // Handle network errors
    req.onerror = function() {
    reject(Error("Network Error"));
    };
    // Make the request.
    req.send();
});


let promiseUrl = 'yoururlhere';

get(promiseUrl).then(function(response){
    displayButton(response);

}, function(error) {
  console.error("Failed!", error);
})
  • 1
    Thanks for all your help. Your solution was a definite viable alternative for completing the given task, even though I was able to find a simpler method. I definitely learned a lot from your answer! +1 for sure – flancast90 Nov 27 '20 at 14:37
0

Share your code here if my suggestion is not working. See code below hopefully it will give you idea how to handle your scenario. both success and error alert will call after return on get call

var jqxhr = $.get( "example.php", function() {
  alert( "success" );
})
.fail(function() {
  alert( "error" );
})
  • your example is showing how to call a response from inside the same function of the get(). However, as I am retrieving it from a url and then working with the data, and then determining the display of the button dependent on this function inside another function outside the get, I do not see how this approach would work. Furthermore, since the approach would need to work every time the user clicked a specific tab your answer would work for the page load, but then end since the addEventListener changes the button display. – flancast90 Nov 27 '20 at 14:02
  • I can see how I left out important info in my question, my bad! I guess the base of what I need is some way to determine when the get() ends, and then run the function holding the determinate for the button display – flancast90 Nov 27 '20 at 14:04
0

If anyone has this same issue, I just discovered a simple solution using async and await.

button display block when a>b (a is 10, b is 9)

var a = 10;
var b = 9;
if (a>b) {
async function myDisplay() {
  let myPromise = new Promise(function(myResolve, myReject) {
    myResolve('block');
  });
  document.getElementById("demo").style.display = await myPromise;
}

myDisplay();
}else{
myResolve('none');
}
#demo{
display: none;
}
<h1 id="demo">Hi</h1>

button display none when a<= b (a is 8, b is 9)

var a = 8;
var b = 9;
if (a>b) {
async function myDisplay() {
  let myPromise = new Promise(function(myResolve, myReject) {
    myResolve('block');
  });
  document.getElementById("demo").style.display = await myPromise;
}

myDisplay();
}
#demo{
display: none;
}
<h1 id="demo">Hi</h1>
flancast90
  • 101
  • 6