1

How can I use callback function from ajax in another function

I've got function with ajax:

function correct_date(raw_date){ 
    return $.ajax({
            method: "GET",
            url: "../date/correct.php",
            data: {
                method: 'correct_date',
                date: raw_date
            },
            cache: false,
            dataType: 'json',
            success: function(result) {
                console.log(result.DATE_NEW);
                showTheValue(result);
            }  
     });
}

    var showTheValue = function(correct_day_value) {
     console.log(new Date(correct_day_value.DATE_NEW).toLocaleDateString('de-DE'));
     return correct_day_value;
    };

And I want to have the response/data value from ajax in another function like that:

function correct_start_date() {
        document.getElementsByTagName("INPUT")[1].value = showTheValue();
    }

How can I use response data from ajax in another function ?

13
  • You have to place var showTheValue = function ... before the ajax, or make it an named function function showTheValue() {}. Commented Sep 16, 2016 at 7:49
  • I've tried like this: function showTheValue(correct_day_value) {document.getElementsByTagName("INPUT")[1].value = showTheValue();} And i've got this error in console: index.html:87 Uncaught RangeError: Maximum call stack size exceeded Commented Sep 16, 2016 at 8:11
  • How are you currently calling correct_date and correct_start_date functions? Commented Sep 16, 2016 at 8:18
  • where did you call correct_date? Commented Sep 16, 2016 at 8:19
  • 1
    @eisbehr you are wrong! that function is created at the initial time when the file is loaded. It starts reading from beginning and creates all the functions & variables first. Then, when the ajax is performed you can use those created functions and variables. Commented Sep 16, 2016 at 8:27

5 Answers 5

1

You can you the JavaScript Promise.

http://www.html5rocks.com/en/tutorials/es6/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(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();
  });
}
Sign up to request clarification or add additional context in comments.

Comments

1
function correct_date(raw_date, callback){ 
    return $.ajax({
            method: "GET",
            url: "../date/correct.php",
            data: {
                method: 'correct_date',
                date: raw_date
            },
            cache: false,
            dataType: 'json',
            success: function(result) {
                console.log(result.DATE_NEW);
                return callback(result);
            }  
     });
}

function showTheValue() {
    correct_date(raw_date, function(correct_day_value) {
        document.getElementsByTagName("INPUT")[1].value = correct_day_value;            
    });
}

Comments

1

You must use those two functions like:

function correct_date(raw_date){ 
    return $.ajax({
            method: "GET",
            url: "../date/correct.php",
            data: {
                method: 'correct_date',
                date: raw_date
            },
            cache: false,
            dataType: 'json',
            success: function(result) {
                console.log(result.DATE_NEW);
                correct_start_date(showTheValue(result));//***
            }  
     });
}

var showTheValue = function(correct_day_value) {
     console.log(new Date(correct_day_value.DATE_NEW).toLocaleDateString('de-DE'));
     return correct_day_value;
};

function correct_start_date(correct_day_value) {
    document.getElementsByTagName("INPUT")[1].value = correct_day_value;
}

Or if the "correct_start_date" is used according to a case:

function correct_date(raw_date){ 
    return $.ajax({
            method: "GET",
            url: "../date/correct.php",
            data: {
                method: 'correct_date',
                date: raw_date
            },
            cache: false,
            dataType: 'json',
            success: function(result) {
                console.log(result.DATE_NEW);
                var correct_day_value = showTheValue(result);
                if (/* some case */) {
                    correct_start_date(correct_day_value);//***
                }
            }  
     });
}

Or wait until the value is set by the Ajax:

var globalVar = null;
function correct_date(raw_date){ 
    return $.ajax({
            method: "GET",
            url: "../date/correct.php",
            data: {
                method: 'correct_date',
                date: raw_date
            },
            cache: false,
            dataType: 'json',
            success: function(result) {
                console.log(result.DATE_NEW);
                globalVar = showTheValue(result);
                //correct_start_date(globalVar);
            }  
     });
}

var showTheValue = function(correct_day_value) {
     console.log(new Date(correct_day_value.DATE_NEW).toLocaleDateString('de-DE'));
     return correct_day_value;
};

function getGlobalVar() {
    if(globalVar == null) {
        window.setTimeout(getGlobalVar, 50); 
    } else {
        return globalVar;
    }
}

function correct_start_date() {
    if (
    document.getElementsByTagName("INPUT")[1].value = getGlobalVar();
}

6 Comments

I'm not sure about this, because it's async. But declaring the variables showTheValue and setValue after $.ajax, they could be undefined. You have to make it a named function then, or place it before the AJAX call ...
No no I just mis-typed the second function, now fixed. Which are run asynchronously? I think the answer from Ajax is asynchronous. Then from there, you can use any function at "success" phase.
I tried this by calling localDate(); in other function and it gives me: LocalDate is undefined
Why did you use localDate() ? Does Javascript has a function like that? this error is normal.
No, your first code: var setValue = function(correct_day_value) { var localDate = new Date(correct_day_value.DATE_NEW).toLocaleDateString('de-DE'); console.log(localDate); return localDate; }; And then I use localDate() to get the value to another function, but it's undefined
|
0

This code worked for me:

function correct_date(raw_date){
        return $.ajax({
            method: "GET",
            url: "../date/correct.php",
            data: {
                    method: 'correct_date',
                    date: raw_date
            },
            cache: false,
            dataType: 'json'
     });
}

And then I can insert it wherever I want like this:

function parse_correct_day() {
      .
      .
      .
      .  
        var parse_correctday_value = correct_date("12.1.2016");
        parse_correctday_value.success(function (data) {
            var corrected_date = new Date(data.DATE_NEW);
            document.getElementsByTagName("INPUT")[1].value = corrected_date.toLocaleDateString('de-DE');
        });
}

Comments

-1

Instead of calling 2 functions you should return the result from the function showTheValue and then show the response in the desired elements :

function correct_date(raw_date){ 
    return $.ajax({
            method: "GET",
            url: "../date/correct.php",
            data: {
                method: 'correct_date',
                date: raw_date
            },
            cache: false,
            dataType: 'json',
            success: function(result) {
                console.log(result.DATE_NEW);
                //You need to check the return value of your function and add the value accordingly
                document.getElementsByTagName("INPUT")[1].value = showTheValue(result);
            }  
     });
}

function showTheValue(correct_day_value) {
   var localDate = new Date(correct_day_value.DATE_NEW).toLocaleDateString('de-DE');
   console.log(localDate);
   return localDate;
};

6 Comments

Could you try adding a comment before downvoting to be polite and give feedback what you felt was wrong with the answer
I didn't downvote you, I just saw your answer and gonna try it :)
Maybe because your code will never work?! You declared a anonymous function which will not get used anytime. Instead of complain about downvotes you should test your code before just posting it. ;)
@eisbehr, that was a typo my bad, you could have hinted on that earlier, will update
@BadHorsie thanks, but it feels bad when trying to help someone and due to a small mistake/typo lose some of that hard earned reputation.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.