Search code examples
javascriptjqueryjsonreturnreturn-value

Store result of json request in a variable


I need to store a value of json response to use in another function.

I have this code:

const url_moodle = "https://xxxxx/xxxxx/app/appmoodlejson.php";

var moodleEmail = function (email){
  $.post( url_moodle, { "email":email, "postvar":"email" }, "json")
    .done(function( data, textStatus, jqXHR ) {
      if(data.data){
       // console.log(data.data.id_mdl);
       return data.data.id_mdl;
      }
      
    })
    .fail(function( jqXHR, textStatus, errorThrown ) {
      toastr.error('Error, contact support');
      if ( console && console.log ) {
        console.log( "Fail response: " +  textStatus);
      }
    });
};

var id_mdl = moodleEmail('[email protected]');

If I go to browser console use console.log, data.data.id_mdl show correctly value, but if I use "return" to store value, code no show any error and no function.

Please helpe with any idea to resolve this.


Solution

  • Issue is that its asynchronous and when you call the method, its already done with the call before getting a response back from the post request. try wrapping it around a promise and see if that works!

    var moodleEmail = function(email) {
      return new Promise((resolve, reject) => {
        $.post(url_moodle, { "email": email, "postvar": "email" }, "json")
          .done(function(data, textStatus, jqXHR) {
            if (data.data) {
              // Resolve the promise with the response data
              resolve(data.data.id_mdl);
            } else {
              // Reject the promise if no data is found
              reject(new Error("No data found"));
            }
          })
          .fail(function(jqXHR, textStatus, errorThrown) {
            toastr.error('Error, contact support');
            if (console && console.log) {
              console.log("Fail response: " + textStatus);
            }
            // Reject the promise in case of an error
            reject(new Error("Request failed"));
          });
      });
    };
    
    // Example usage:
    moodleEmail("[email protected]")
      .then(id => {
        console.log("ID:", id);
      })
      .catch(error => {
        console.error("Error:", error);
      });