Trouble accessing variables declared outside ajax function

I have Case objects, each connected to multiple clients, and to many Draft Invoices.  I'm trying to make a script that will take a single Draft Invoice and create a Final Invoice from it for each client.  Having trouble with my JS variables.

I'm trying to follow this example:  

$(document).on('knack-record-create.view_141', function (event, view, record) {
    var Class = $('#view_141-field_71').val();
    var attendance_Date = record.id;
var user = Knack.getUserToken();
var headers = { "Authorization": user, "X-Knack-Application-ID": app_id, "Content-Type":"application/json"}

$.ajax({
url: ‘https://api.knackhq.com/v1/scenes/scene_1/views/view_25/records/’ + Class,
type: ‘GET’,
headers: headers,
success: function (data) {
Knack.showSpinner();
var students = data.field_28_raw;
var total = Students.length;

    students.forEach(function (student) {
        var data = { field_72: attendance_Date, field_31: Class, field_65: student.id };
        $.ajax({
            url: 'https://api.knackhq.com/v1/scenes/scene_72/views/view_145/records/',
            type: 'POST',
            headers: headers, 
            data: JSON.stringify(data),
            success: function (response) {
                total--
                console.log('Attendance added!!!');
                redirect(total, class, attendance_date);
            }
       })
    });
}

});
});

 

Here’s my code: 

//on draft invoice edit submit, create final invoice for each client
$(document).on(‘knack-record-update.view_252’, function (event, view, record) {

//get current draft invoice record ID for case lookup
var draftInvoiceID = record.id;

// api url for cases
var api_url = ‘https://api.knackhq.com/v1/objects/object_1/records’;

// prepare filter for cases by current draft invoice record
var filters = [
{
field: ‘field_195’,
operator: ‘contains’,
value: draftInvoiceID
}
]

// add filter to URL
api_url += ‘?filters=’ + encodeURIComponent(JSON.stringify(filters));

// GET case for current draft invoice record
$.ajax({
url: api_url,
type: ‘GET’,
headers: {
‘X-Knack-Application-Id’: ‘XXX’
, ‘X-Knack-REST-API-Key’: ‘XXX’
},

  //if successful, put case data into function to create final invoices for each client
  success: function(caseData) {
    
    // array of clients connected to the case
    var clients = caseData.records[0].field_69_raw;
    
	//log each client name
           clients.forEach(function (client) {
      
                 console.log(client.identifier);
                 console.log(client.id);
                 console.log(draftInvoiceID.id);
                 console.log(record.id);

      

    });
  }

});
});

   

Once I step inside clients.forEach(function (client) {});, I lose access to the previous variables.  The code successfully logs client.id and client.identifier, but fails for draftInvoiceID.id and record.id.  

I’m stuck because I don’t see how what I’m doing is different from the sample code, with variables declared outside the ajax code and then accessed by functions within it.

Thanks for your help!

Good Post! , it was so good to read and useful to improve my knowledge as an updated one, keep blogging.After seeing your article I want to say that also a well-written article with some very good information which is very useful for the readers....thanks for sharing it and do share more posts likethis. https://www.3ritechnologies.com/course/angular-js-training-institute-in-pune/


Greetings. I know this is somewhat off-topic, but I was wondering if you knew where I could get a capt ha plugin for my comment form? I’m using the same blog platform like yours, and I’m having difficulty finding one? Thanks a lot

<a href="https://www.acte.in/software-testing-training-in-chennai"> Software Testing Training in Chennai </a> | <a href="https://www.acte.in/software-testing-training-in-annanagar"> Software Testing Training in Anna Nagar</a> | <a href="https://www.acte.in/software-testing-training-in-omr"> Software Testing Training in OMR</a> | <a href="https://www.acte.in/software-testing-training-in-porur"> Software Testing Training in Porur</a> | <a href="https://www.acte.in/software-testing-training-in-tambaram">Software Testing Training in Tambaram</a> | <a href="https://www.acte.in/software-testing-training-in-velachery"> Software Testing Training in Velachery</a>

 

This post is really nice and informative. The explanation given is really comprehensive and informative. I want to share some information about the best  oracle dba training  and  weblogic 12c tutorial  training videos. Thank you .Hoping more articles from you.

 

Great post and creative ideas. I am happy to visit and read useful articles here. I hope you continue to do the sharing through the post to the reader. 
 
AWS Online Training
 
AI Online Training
 

function get_something(){    $.getJSON("get_something.php",function(json){                  console.log(json.something);    });    }


How would I use the value of json.something outside of the get_something(); function?   R Programming Online Training |  SAS Online Training | Android Online Training | Weblogic Online Training | MongoDB Online Training | MongoDB Admin Online Training SQL Online Training

I am a regular contributor of your blog. Useful information shared here. Thanks a lot. 

Mainframe Training | Oracle DBA Training

What you expect is the synchronous (blocking) type request.

var it_works = false;

jQuery.ajax({

  type: "POST",

  url: 'some_file.php',

  success: function (data) {

    it_works = true;

  },

  async: false // <- this turns it into synchronous

});​

// Execution is BLOCKED until request finishes.

// it_works is available

alert(it_works);

Requests are asynchronous (non-blocking) by default which means that the browser won't wait for them to be completed in order to continue its work. That's why your alert got wrong result.

Now, with jQuery.ajax you can optionally set the request to be synchronous, which means that the script will only continue to run after the request is finished.

Figured it out.  Needed to set ajax to disable asynchronous execution.