Using $.get(url, function (_data, status)

I am using $.get to retrieve data from a server. In the function getting the data the first $.get works but the second does not. the two calls are identical except for the url. The function of interest is:

function run_board_test(button){
    var BoardTest = document.getElementById("RunBoardTest");
    var label = document.getElementById("BoardTestLabel");
    if (test_status == 0 ) {
        jQuery.post("/RunBoardTest");
    }
    
    $.get(tx_test_status_url, function (_data, status) {
        var array = _data.split(',');
        var content =
        test_status = array[0]; //*****This works*******//
    });
    
    console.log("test status is: " + test_status); //test_status = 1  when data is ready! OK
    
    if(test_status == 1){
        $.get(tx_test_data_url, function (_data, status) {
            var array = _data.split(',');
            var content =
            test_status = array[0]; //*****This does not work***** 
        });

        console.log("test steps is: " + test_status); //test_status is undefined
        
        var testWindow = window.open("", "MsgWindow", "top=200,left=200,width=500,height=200");
        testWindow.document.write("<p>Test Results</p>");
        testWindow.document.write("<p>Pass/Fail</p>");
        testWindow.document.write("<p>Results Ready: " + test_steps + "completed </p>");
    }
}

The function is called by a button on the main page. The goal is when there is test data to display it is called in a printed to a window that the user closes after viewing the test data. The same test_status var is used and the first get brings back a flag that the test is completed. The second get needs to bring back the number of test steps so the results window can be formatted correctly. I know the data from the server is being sent correctly as I have debug statements on that side that shows what is being sent.

I am new to java script but not new to C. This should be straight forward, but alas I may be expecting too much and missed something simple.

whats the purpose of content?

1 Like

excellent question.
The example I took this from was part of the example HTTP webserver demo for the processor I am using to perform the webserver functionality. There are instances where it appears in the get call and other where it it does not. The usage is not clear. In the main routine that is loading the data in the example one of the queries has:

jQuery.get(tx_url, function (_data, status) {
    var array = _data.split(',');
    var content =
    document.getElementById("tx_active").innerHTML = "Resumptions : " + array[0];
    document.getElementById("tx_suspended").innerHTML = "Suspentions : " + array[1];
    document.getElementById("idle_returns").innerHTML = "Idle Returns : " + array[2];
    document.getElementById("non_idle_returns").innerHTML = "Non Idle returns : " + array[3];

and the very next query has:

jQuery.get(nx_url, function (_data, status) {
    var array = _data.split(',');
    document.getElementById("nx_sent").innerHTML = "Total Bytes Sent  : " + array[0];
    document.getElementById("nx_received").innerHTML = "Total Bytes Received  :  " + array[1];

So it would appear that it is not needed or does nothing.
In fact, in the original code from the example it looks like a mistake.
Removing the line does not change the operation even where I have get queries that are working and more closely matching the example where text is directed back to the main page.

okay.

You say you see the second get… go out, lets say. Do you see it come back?

Open the Developer Console in your browser (usually F12), open the Network tab, and observe the traffic when you click the button. You should see two requests go out to tx_test_data_url (whatever its value is, obviously, you wont see the words “tx_test_data_url”).

If you click on the second one, and look at the Response, does the response from the server look correct? (What does it look like?)

I have given the code from your initial post a bit of indentation. It was hard to see what went with what.

Note: To make your code a codeblock select it and click on the </> option in the menu. This will wrap your code in three opening and closing ticks ```.

Thank you for the debugging guidance. I am still new to the tool. I was able to follow that to a missing line in my webserver code which when corrected solved the “undefined” issue. However, there is still a problem. I also inserted copious console.logs. The result was as follows:
Console log data Network Response log data
Enter while loop for status

test status in while loop is: 0
sleep 1 sec
Get board test status Response Payload: 1, 0
test status after get is: 0

test status in while loop is: 0
sleep 1 sec
Get board test status Response Payload: 1, 0
test status after get is: 1
Exit while

Get board test data Response Payload: 21, 0
test steps is: 1
sleep 1 sec
Get board test data 2nd time Response Payload: 21, 0
test steps is: 21

As you can see, the data parsed from the array after var array = _data.split(‘,’) statement is not always passed to the target variable as received from the webserver.

For reference this is what the code looks like now:

    test_status = 0;
    jQuery.post("/RunBoardTest");
    console.log("sleep 2 secs");
    await sleep(2000);

    console.log("Enter while loop for status");
    while(test_status == 0){
        console.log("test status in loop is: " + test_status);
        console.log("sleep 1 sec");
        await sleep(1000);
        console.log("Get board test status");
        $.get(tx_test_status_url, function (_data, status) {
            var array = _data.split(',');
            test_status = array[0];
        });
        console.log("test status after get is: " + test_status);
    }//while
    console.log("Exit while");
    console.log("Get board test data");
    $.get(tx_test_data_url, function (_data, status) {
    var array = _data.split(',');
    test_status = array[0];
    });
    console.log("test steps is: " + test_status);

    console.log("sleep 1 sec");
    await sleep(1000);
    console.log("Get board test data 2nd time");
    $.get(tx_test_data_url, function (_data, status) {
    var array = _data.split(',');
    test_status = array[0];
    });
    console.log("test steps is: " + test_status);

got it.

1 Like

This gets more interesting. I added another get command to return the number for test errors after the command that returns the number for test steps completed which finally ends up being 21. When I issue the next get the response is 0 but the value parsed from the array is 21 which is the previous value. Timing maybe?

Nailed it.
Prior to my last get I put a sleep. Anything below 50ms and I get the previous data parsed by var array = _data.split(‘,’) in the statement:

$.get(tx_test_err_count_url, function (_data, status) {
   var array = _data.split(',');
   test_status = array[0];
   });

With 50ms or greater I get the data back to the javascript as intended.

I have very deterministic control over the webserver, but no control over what kind of computer the client will be deployed on. So is there a better way to control this other than sleep?

Well that’s because $.get is asynchronous.
It sends off the request, but doesnt wait for it to come back before continuing.

Try this.

test_status = 0;
jQuery.post("/RunBoardTest");


console.log("Wait 2 seconds, then Check status");
setTimeout(GetTestStatus,2000);

function GetTestStatus() {
	console.log("Get board test status");
	$.get(tx_test_status_url, function (_data, status) {
		var array = _data.split(',');
		test_status = array[0];
		console.log("test status after get is: " + test_status);
		if(test_status == 0) { setTimeout(GetTestStatus,1000); } else { GetTestData(); }
	});//EndGet
	
}//EndFunc

function GetTestData() {
	$.get(tx_test_data_url, function (_data, status) {
		var array = _data.split(',');
		test_status = array[0];
		console.log("test steps is: " + test_status);
	}); //EndGet
} //EndFunc

This should make the code deterministic based on the result of the get, rather than stabbing randomly at how long it takes $.get to return.

EDIT: Reindenting so I dont go crosseyed reading my own code.

3 Likes

That is slick! Works beautifully. Thank You for the help, incite, and coding mentoring.
I marked it as the solution. Much better than using sleep.

1 Like

Just a thought, but would you want to add an attempts variable too?

if (test_status == 0 && attempts < 10) ...

Or is that overkill in this instance?

you’d need to if/elseif/else that branch, because if the attempts caps out, you want to abort, not continue.

1 Like

That’s what my ... included :biggrin:

1 Like