0

I am working on the jquery to call a function to get the return value that I want to store for the variable email_number when I refresh on a page.

When I try this:

function get_emailno(emailid, mailfolder) {

    $.ajax({
        url: 'getemailnumber.php',
        type: 'POST',

        data : {
            emailid: emailid,
            mailfolder: mailfolder
        },

        success: function(data)
        {
            email_number = data;
        }
    });
    return email_number;
}

I will get the return value as 6 as only when I use alert(email_number) after the email_number = data;, but I am unable to get the value outside of a function.

Here is the full code:

var email_number = '';

// check if page refreshed or reloaded
if (performance.navigation.type == 1) {
    var hash    = window.location.hash;
    var mailfolder = hash.split('/')[0].replace('#', '');
    var emailid = 'SUJmaWg4RTFRQkViS1RlUzV3K1NPdz09';
    get_emailno(emailid, mailfolder);
}

function get_emailno(emailid, mailfolder) {

    $.ajax({
        url: 'getemailnumber.php',
        type: 'POST',

        data : {
            emailid: emailid,
            mailfolder: mailfolder
        },

        success: function(data)
        {
            email_number = data;
        }
    });
    return email_number;
}

However, I have been researching and it stated that I would need to use callback via ajax but I have got no idea how to do this.

I have tried this and I still don't get a return value outside of the get_emailno function.

    $.ajax({
        url: 'getemailnumber.php',
        type: 'POST',
        async: true,

        data : {
            emailid: emailid,
            mailfolder: mailfolder
        },

        success: function(data)
        {
            email_number = data;
        }
    });

I am getting frustrated as I am unable to find the solution so I need your help with this. What I am trying to do is I want to call on a get_emailno function to get the return value to store in the email_number variable.

Can you please show me an example how I could use a callback function on ajax to get the return value where I can be able to store the value in the email_number variable?

Thank you.

  • We just closed this question. Don't post the same question over again. Read the link we provided in the last question you posted. https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Scott Marcus Oct 01 '19 at 22:41
  • @ScottMarcus No this is a different question so please check my question carefully. –  Oct 01 '19 at 22:49
  • 1
    @chrisoojer, it's *almost* same question. However, to give you some quick help, the callback you researched about is talking of the `success`, `error` and `complete` callbacks. You already have `success` callback in your code – Udo E. Oct 01 '19 at 23:14
  • UdoE Thank you for your advice. So what callback is the best for me to use? is it `complete` callback? –  Oct 01 '19 at 23:21
  • @chrisoojer, see my answer. – Udo E. Oct 02 '19 at 00:28

1 Answers1

1

From the jquery documentation, the $.ajax() method returns a jqXHR object (this reads fully as jquery XMLHttpRequest object).

When you return data from the server in another function like this

function get_emailno(emailid, mailfolder) {

    $.ajax({ 
        // ajax settings
    });
    return email_number;
}

Note that $.ajax ({...}) call is asynchronous. Hence, the code within it doesn't necessarily execute before the last return statement. In other words, the $.ajax () call is deferred to execute at some time in the future, while the return statement executes immediately.

Consequently, jquery specifies that you handle (or respond to) the execution of ajax requests using callbacks and not return statements.

There are two ways you can define callbacks.

1. Define them within the jquery ajax request settings like this:

$.ajax({ 
    // other ajax settings 
    success: function(data) {},
    error: function() {},
    complete: function() {},
});

2. Or chain the callbacks to the returned jqXHR object like this:

$.ajax({ 
    // other ajax settings 
}).done(function(data) {}).fail(function() {}).always(function() {});

The two methods are equivalent. success: is equivalent to done(), error: is equivalent to fail() and complete: is equivalent to always().

On when it is appropriate to use which function: use success: to handle the case where the returned data is what you expect; use error: if something went wrong during the request and finally use complete: when the request is finished (regardless of whether it was successful or not).

With this knowledge, you can better write your code to catch the data returned from the server at the right time.

var email_number = '';

// check if page refreshed or reloaded
if (performance.navigation.type == 1) {
    var hash    = window.location.hash;
    var mailfolder = hash.split('/')[0].replace('#', '');
    var emailid = 'SUJmaWg4RTFRQkViS1RlUzV3K1NPdz09';
    get_emailno(emailid, mailfolder);
}

function get_emailno(emailid, mailfolder) {

    $.ajax({
        url: 'getemailnumber.php',
        type: 'POST',

        data : {
            emailid: emailid,
            mailfolder: mailfolder
        },

        success: function(data)
        {
            // sufficient to get returned data
            email_number = data;

            // use email_number here
            alert(email_number); // alert it
            console.log(email_number); // or log it
            $('body').html(email_number); // or append to DOM
        }
    });
}
Udo E.
  • 2,665
  • 2
  • 21
  • 33