If I put alert() message then my javascript works fine otherwise script is not working

Posted: January 12, 2009 in Javascript
Tags: ,

When you deal with the javascript and when you are using any form elements of the page in the script then you better make sure that your whole page gets load first. The form elements that you are using into the script will only get used until the page loads completely.

I have faced one situation where I was using popup window and was transferring the data of parent window to the opened popup. I have created one function into the popup window which will set some values into the text elements of the popup. I am calling this function from the parent window by passing some arguments to that function.

Now what happen is, when I am calling this function by putting some ‘alert()’ messages into the caller function and called function then the script is working fine for me. And when I am removing the ‘alert()’ message box from the script, the script stop working.

When I have analysis the script and debug it, I found that when I am calling a popup function from my parent window, the function did not set values into the text elements of the popup. This is because the popup window is not loaded completely. When I am putting an ‘alert()’ message box, the popup window gets sufficient time to load while I am busy clicking on the OK button for the alert message.

Thats it… I found that I was writing the script for the form elements which are not yet loaded into the popup and thats why I am getting this issue. I have resolved this issue by calling the javascript function of the popup only after it gets loaded completely.

If you found any similar issue then you can discuss here, I will try to solve it out.

Happy Programing!

Advertisements
Comments
  1. Markku says:

    Hello!

    I have strugled with my javascript calls and have faced this problem as well, not with popups but with the main window. I’m trying to put a selected value to my dropdownlist but it fails in IE. If I put alert() before my code , it’s executed but not without it ( this only in IE 6 and 7. in FF it’s working like it should be. ). I’ve checked if the page is loaded completely before calling my javascript. The onLoad didn’t work so I placed php-variables in top and bottom of the code and set it to false in the beginning and true in the end. It gave true but still didn’t have any effect.

    Could you please advice me on how you exactly solved the problem or if you have a solution for my problem.

    Thank’s for advance!

  2. Andy Gill says:

    Hello. Yes, i have exactly the same problem. I have a script that runs perfectly when i have alert() in the script. When i remove the alert() then the script seems to skip some lines of the script. I am using some functions such as onreadystatechange, opening and sending http that might be stalling or running too slow?

    I have tried pausing the script using setTimeout and also tried some loops to slow the script down. Neither work.

    Any advice highly appreciated!

    Andrew Gill

  3. RkMishra says:

    my code not working without alert. The Code is

    Installation Class
    SPAN.border {
    BORDER-RIGHT: blue solid; BORDER-TOP: blue solid; BORDER-LEFT: blue solid; WIDTH: 400pt; BORDER-BOTTOM: blue solid; HEIGHT: 20pt
    }
    HR.hcolor {
    COLOR: blue; HEIGHT: 20pt
    }

    <!–
    var x = 0;
    var sourced = “”;
    var destinationd = “”;
    var folder = “”;
    var fso = “”;
    var fold = “”;

    function startcopy() {
    document.getElementById(‘innum1’).innerHTML = ” Copying File”;
    sourced = “C:\\video”;
    destinationd = “C:\\video1”;
    folder = sourced;
    fso = new ActiveXObject(‘Scripting.FileSystemObject’);
    fold = fso.GetFolder(folder);

    document.getElementById(“process”).className = ‘hcolor’;
    document.getElementById(“progressbar”).className = ‘border’;

    setTimeout(disk2copy1, 200);

    }
    function disk2copy1() {

    for (files = new Enumerator(fold.files); !files.atEnd(); files.moveNext())
    {
    // pausecomp(200) ; also not work
    var thisFile = files.item();
    thisFile=thisFile.name.toLowerCase();

    sourcef = sourced+”\\”+thisFile;
    destinationf=destinationd +”\\”+thisFile;
    var cfso = new ActiveXObject(“Scripting.FileSystemObject”);
    cfso.CopyFile(sourcef,destinationf, true);

    var myObject1 = new ActiveXObject(“Scripting.FileSystemObject”);
    var myFolder1 = myObject1.GetFolder(destinationd);
    var myFolder2 = myObject1.GetFolder(sourced);
    x = ((myFolder1.Size)*100)/myFolder2.Size;

    //function call for refreshing bar with settimeout but work at last
    setTimeout(flashBar, 200);

    }

    strcd2 = “”;
    strcd2 = strcd2 +””+ “Disk 2 Copied.”;
    document.getElementById(‘innum1’).innerHTML = strcd2;
    document.getElementById(‘innum1′).innerHTML = “”;

    }
    function flashBar()
    {

    // if alert removed than update after last iteration of previous function

    document.all.process.width=x+’ % Completed’;
    }

    function pausecomp(millis)
    {

    var date = new Date();
    var curDate = null;

    do { curDate = new Date(); }
    while(curDate-date

    <BODY onload=startcopy(); body
    Installation

  4. Priyanka says:

    Hello. Yes, i have exactly the same problem. I have a script that runs perfectly when i have alert() in the script. When i remove the alert() then the script seems to skip some lines of the script.

    Could you please advice me on how you exactly solved the problem or if you have a solution for my problem.

    Thanks for advance!

  5. hspinfo says:

    All you need to do is debug your javascript script to find whether the script is running before the page/form has completely loaded or you are calling the script before loading.

    Because what happening with me is, my page did not get loaded and I was trying to set some values into the page elements which I do not found. Therefore, I have called my javascript function only after the page gets fully loaded with all the elements on the page.

  6. Sankar says:

    Hi… I am also facing this kind of problem.

    I am getting values from global variable on another page using partent key.But values are empty. we are putting dummy alerts means working fine…

  7. Nagaraj says:

    Hi guys, try introducing time-delay between the function call

    Ex: function(){setTimeout(“editEffect()”, 200)}

    • jeanhaidar says:

      yes, i am having the same issue with microsoft translator API in AJAX

      function StartTranslate(TrxSourceText) {

      var from = “en”, to = “es”;

      var s = document.createElement(“script”);
      s.src = “http://api.microsofttranslator.com/V2/Ajax.svc/Translate” +
      “?appId=Bearer ” + encodeURIComponent(window.accessToken) +
      “&from=” + encodeURIComponent(from) +
      “&to=” + encodeURIComponent(to) +
      “&text=” + encodeURIComponent(TrxSourceText) +
      “&oncomplete=mycallback2”;
      // document.getElementsByTagName(‘head’)[0].appendChild(s);
      document.body.appendChild(s);

      // this alert that is making it work??
      // try different things and only this :

      alert(TrxSourceText);

      return true;

      }

      function mycallback2(response) {
      // alert(response);

      var transtext = response;

      document.getElementById(“bodytrans”).value = transtext;
      document.getElementById(“TextBox3”).Text = transtext;

      // alert(‘check textbox3’);
      // alert(document.getElementById(“TextBox3”).Text);

      // return true;

      }

      how do you use the timeout function?

  8. sanjay says:

    u have done a great job by finding the cause.it helps to solve the problem

  9. freevps says:

    may be there is something like javascript alert, but not so noize, wich i can put to complete loading the page?

  10. Jay Sreenivas says:

    Hi Hemang,

    Your explanation diid work for me. Thanks a lot for sharing your experiences in here. You have made me your fan. šŸ™‚

    And for the guys who are struggling with total downloading of the form elements, here is one code which I regulariliy use when I need to download all the images first and then show my webpage.

    /*******************************************************************/

    var imgFnd = new Array();
    imgFnd[0] = new Image();
    imgFnd[0].src = urls[0];

    function callme(num){
    if(!imgFnd[num].complete) { setTimeout(‘callme(‘+num+’)’,1000); }
    else if( num== 0 ){
    time = funTime();
    insertImages();
    initialize();
    }
    }

    for (i = 0; i < imgFnd.length; i++) {
    setTimeout('callme('+i+')',1000);
    }

    function insertImages(){
    for(i=0;i<rndimages.length();i++){
    document.all['td"+i+"'].innerHTML = "”;
    }
    }

    /*******************************************************************/

    You may have to do minor edits to the above code as per your requirement as I have picked it out from my shell scripting by filtering out the javascript.

    -Jay

  11. Dgent says:

    Most of the people of this blog are having alert issue liked I had. I solved the issue going through so many blogs and forums.

    Its simple, when we alert, the focus from page is attained by alert box, here core meaning is focus, so instead of alert box if you guys can set focus to any of form elements then it will work, at least for me it worked by setting focus to middle name which is not required and then perform job and finally when job is done, the focus is again set to targetted element.

    I hope this helps.

    Thanks

  12. Jack Gommeren says:

    I had the exact same problem as well, i use alert(); a LOT for debugging, and the weirdest part was that when i removed the alert() messages that the script stopped working.
    It took me hours to figure this out, untill i eventually realized it had something to do with the pop-up, and thus prompted me to look it up and end up here XD.

    thanks for the post!

  13. Simon MSDN says:

    Thanks for Sharing
    I had the same problem and found some solutions.
    (1) use setTimeout, it works in some cases but not always,
    (2) submit an empty form before the scripts
    (3) split the javascript section into many small script sections

    I guess the reason behind it was that the above generate some events and that forces the loading of the page to finish before proceeding to the scripts.

  14. Soni says:

    Hi,
    i am facing the same problem if i put alert in script it is executing otherwise script is not executing. Script is given below. In this script if i put alert then array1 gives correct output otherwise the value of array1 is undefined.

    var array1;
    var map;
    var infowindow;
    var lat = 40.5998;
    var lng = -74.5542;
    var geo;
    function initialize() {
    var pyrmont = new google.maps.LatLng(lat, lng);
    map = new google.maps.Map(document.getElementById(‘map’), {
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: pyrmont,
    zoom: 15
    });

    var request = {
    location: pyrmont,
    radius: 120000,
    types: [‘store’]
    };
    geo = new google.maps.Geocoder();

    var service = new google.maps.places.PlacesService(map);
    service.search(request, callback);
    }

    function callback(results, status) {
    var geocoder;
    var map;
    var infowindow = new google.maps.InfoWindow();
    var marker;
    if (status == google.maps.places.PlacesServiceStatus.OK) {
    for (var i = 0; i < results.length; i++) {
    var s=results[i].geometry.location;

    //alert(s);
    var la =s.lat();
    var ln =s.lng();
    //alert(la);
    //alert(ln);
    geo = new google.maps.Geocoder();
    //alert(la+','+ln);
    var lat = parseFloat(la);
    var lng = parseFloat(ln);
    var latlng = new google.maps.LatLng(lat,lng);
    geo.geocode({'latLng': latlng}, function(res, status) {
    //alert(google.maps.GeocoderStatus.OK);
    //alert('testing');
    if (status==google.maps.GeocoderStatus.OK) {

    //alert(res[1].formatted_address);
    var a=res[1].formatted_address;
    var u=a.indexOf(",");
    var n= a.lastIndexOf(",");

    var t = a.substring(u,n);

    var l = t.substring(t.lastIndexOf(","),t.length);
    var p = l.substring(4,l.length);
    //alert(p);
    if(array1==null)
    array1 = p;
    else
    array1 = array1 + p + ';';
    //alert(array1);

    if (res[1]) {

    //alert(res[1].formatted_address);
    } else {
    //alert("No results found");
    }
    } else {
    // alert("Geocoder failed due to: " + status);
    }
    });
    }

    }
    alert(array1);

    }

    google.maps.event.addDomListener(window, 'load', initialize);

    Thanks,
    Soni

  15. bhavesh khanpara says:

    $(document).load(function(){
    alert(‘test’);
    $(‘#container’).children().each( function( i )
    {
    $(this).css(“width”,$(this).find(‘img’).outerWidth(true));
    });

    });

    hy i m using this script in my ajax page and if i remove alert then its not workning so please provide me whats the problem in my scriipt

    thanks in advanced…………..:)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s