0

I have a section of my code that sends info via jQuery Ajax to call the getMute function on the server but I'm having trouble with my getter. I want it to return a boolean that will allow me to create a button toggle but instead, I'm getting a console error that says 'result' is undefined. It works when I return just the data but I need the boolean specifically. Any tips on what I'm doing wrong?

function setMute(check) {
    $.ajax({
        url: url,
        data: JSON.stringify(createData('setMute', check)), // Check is a Boolean
        type: "POST",
        dataType: "json",
        success: function (data) {
            console.log(data);
        }
    });
}

function getMute() {
    response = $.ajax({
        url: url,
        data: JSON.stringify(createData('getMute', null)),
        type: "POST",
        dataType: "json",
    });

    response.done(function (data) {
        console.log(data.response);
        return data.response.result;
    });
knox0
  • 17
  • 7
  • *I'm having trouble with my getter* please be as specific as possible. What trouble are you having and what errors are you encountering? – Emiel Zuurbier Aug 30 '23 at 19:11
  • You can't return from an asynchronous call. – epascarello Aug 30 '23 at 19:15
  • @EmielZuurbier edited. sorry for the confusion – knox0 Aug 30 '23 at 19:15
  • @epascarello I thought that the response.done() would act as a "synchronizer" and get the current states. how can i fix this to work as I intend – knox0 Aug 30 '23 at 19:16
  • @knox0 The callback in`response.done()` would fire at a later moment whenever the data has been fetched, much like an event listener. If the request would be synchronous, then the entire page would freeze until it's finished. Async makes it possible to wait for it to finish while doing other stuff. I'd suggest you look into the native [fetch](https://developer.mozilla.org/en-US/docs/Web/API/fetch) function and learn about [Promises](https://javascript.info/promise-basics) which `fetch` utilizes. It's a powerful part of JavaScript and will be a very helpful addition to your toolkit. – Emiel Zuurbier Aug 30 '23 at 19:29

0 Answers0