Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX function does not work without alerts

I am using a fair amount of AJAX with XML Http Requests in my website. For a seemingly random few AJAX calls, I'm not able to get all of my javascript in the onreadystatechange function to execute properly unless I have an alert call that I'm guessing pauses the execution enough for it to finish running the PHP script on the server. Here's an example of what I'm talking about:

Javascript

xmlHttp=getXMLHttp();   //function returns an xmlhttp object to use
//get parameters ready
param="id=5"
xmlHttp.onreadystatechange=function(){
    if(xmlHttp.readyState==4){
        s=xmlHttp.responseText;
        var myJson = eval("("+s+")");
        document.getElementById('Elem1').value=myJson.Result1;
        document.getElementById('Elem2').value=myJson.Result2;
        triggerEvent(document.getElementById('Elem3'),'onblur');
        document.getElementById('Elem4').value=myJson.Result3;
        document.getElementById('Elem5').value=myJson.Result4
        var sel = document.getElementById('Elem6');
        var i;
        for(i=0;i<sel.length;++i){
            if(sel.options[i].value==myJson.Result5){
                sel.selectedIndex = i;
                break;
            }
        }
        document.getElementById('MfgCustNum').value=myJson.Result6;
        document.getElementById('MfgOrderNum').value=myJson.Result7;
        document.getElementById('OrderDatePicker').value=myJson.Result8;
        document.getElementById('ShipDatePicker').value=myJson.Result9;
        document.getElementById('CancelDatePicker').value=myJson.Result10;
        document.getElementById('PO Number').value=myJson.Result11;
        //for some reason, the following 2 lines are where I'm having issues without an alert box
 document.getElementById('NewElement').value=myJson.Result12;
     document.getElementById('NewElement2').value=myJson.Result13;
 //everything else loads properly
        sel = document.getElementById('SelectBox1')
        for(i=0;i<sel.length;++i){
            if(sel.options[i].value==myJson.Result14){
                sel.selectedIndex = i;
                break;
            }
        }
        sel = document.getElementById('SelectBox2')
        for(i=0;i<sel.length;++i){
            if(sel.options[i].value==myJson.Result15){
                sel.selectedIndex = i;
                break;
            }
        }
        sel = document.getElementById('SelectBox3')
        for(i=0;i<sel.length;++i){
            if(sel.options[i].value==myJson.Result16){
                sel.selectedIndex = i;
                break;
            }
        }
        sel = document.getElementById('SelectBox4')
        for(i=0;i<sel.length;++i){
            if(sel.options[i].value==myJson.Result17){
                sel.selectedIndex = i;
                break;
            }
        }
    }
}
xmlHttp.open("POST","../ServerCall.php",true);
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.send(params);

The PHP script I'm running is a simple query on a DB that is echo'd as a JSON array

    $dc->connect();
    $query = "SELECT COLUMNS FROM TABLE"
    $res = $dc->queryDb($query);
    if(!$res){
        exit();
    }
    $ary = $dc->resultsToArray($res);
    $JSON_ARRAY=array();
    foreach($ary[0] as $key=>$value){
        if(!is_numeric($key))
            $JSON_ARRAY[$key]=$value;
    }
    echo json_encode($JSON_ARRAY);

This is becoming a pretty big problem for me as its now happened in 3 or 4 different parts of my code, yet putting in an alert dialog with the response text shows everything is running properly. I've tried running the AJAX call synchronously instead of asynchronously but it didn't help. I've also tried using settimeout to delay running the code for a second or two, but I had mixed results with that and I would prefer to not have to set a specific delay for the scripts to run.

EDIT: To answer some of the questions in the comments: For this code snippet, the problems are with the following 2 lines:

 document.getElementById('NewElement').value=myJson.Result12;
 document.getElementById('NewElement2').value=myJson.Result13;

If I Put an alert box right before that line to get the text of myJson.Result12, the elements get filled in properly on my page. Without it, they are left blank and no errors are seen in Firefox's Error Console

This code is running off an onclick. I'm using DataTables and when someone double clicks a row in my table, the page gets populated with the contents. Again, everything is working fine with the exception of the 2 new elements I added earlier today. The bigger concern is more about how this seems to be a recurring issue in my code.

Also, I've tried out jQuery's AJAX call, but haven't had much luck with it and most of my code was already written using xmlHttp with just JS.

like image 647
gdawgrancid Avatar asked Feb 13 '26 08:02

gdawgrancid


1 Answers

A probable reason;

You should do your AJAX request from the onload handler, otherwise your page may not be completely loaded by the time you get the response. If NewElement and NewElement2 aren't loaded by the time you try to update them, your script will not work.

The alert will delay the script enough to let the page finish loading, allowing the elements to exist before your script gets to that point.

like image 107
Joachim Isaksson Avatar answered Feb 14 '26 21:02

Joachim Isaksson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!