-1

I want to make two ajax calls in a click event. Each ajax call does a distinct operation and returns back data that is needed for a final callback. The first call is an onload event the returns a search form with id's generated from the api. This api is returning the search form with no issues. The calls themselves are dependent on one another, and the final one can only work with the results from the first one. The error that I get is f is not defined.

$(document).ready(function() {

    var searchForm = (function() {

        $.ajax({
         async: true;
            //"code"// 
        data.map(function(f)) {
         return <input id=f.Datafield>
         }
        });
    });



    $("#btn").on("click", function(event) {

     event.preventDefault();

     var id = searchForm($("#" + f.DataField));

    $.ajax({ 
    URL= "api" + id
     async:true;
    });
});
searchForm()
}
denis
  • 159
  • 9
  • Where is f defined? – Rahi Feb 18 '19 at 16:42
  • The last 2 lines (`fun1()` and `}`) don't look like they belong here. Is that a mistake? – Pedro LM Feb 18 '19 at 16:43
  • @PedroLM fun1 returns the function from the first api and renders the search form on the document. – denis Feb 18 '19 at 16:49
  • @KevinB I believe the question that you are saying has already been asked is just asking how to render the ajax call to the dom? I am needing to render the second call using the id assigned from the first call – denis Feb 18 '19 at 16:51
  • nah, the rendering to the dom is no different than using the return in another function. The problem remains the same, the data you're trying to act on doesn't exist yet. – Kevin B Feb 18 '19 at 16:52
  • @Rahi f is defined in the first ajax call. f is the function of a .map to get the ids assigned to the search form. – denis Feb 18 '19 at 16:53
  • @KevinB are you asking that I delete this question then and get my answer from the previously asked question that you provided? – denis Feb 18 '19 at 16:58
  • Nah, you can do what you want. – Kevin B Feb 18 '19 at 16:58

1 Answers1

0

Ajax requests are asynchronous. You either need to use your 1st request as a promise, or set the async flag to false.

$(document).ready(function() {
 let res = $.ajax({
   ...
   async: false
 });
 // do whatever you want with res

or as a promise :

$(document).ready(function() {
 $.ajax({
   ...
 }).then(function(data, textStatus, jqXHR) {
     //the request was a success
     // read the doc here : http://api.jquery.com/jquery.ajax/
     console.log(data)
 }, function(jqXHR, textStatus, errorThrown) {
     //the request failed
     // read the doc here : http://api.jquery.com/jquery.ajax/
}))
Nathan Schwarz
  • 631
  • 5
  • 19