Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 12 of 12
  1. #1
    Regular Coder
    Join Date
    Dec 2011
    Posts
    186
    Thanks
    0
    Thanked 1 Time in 1 Post

    Ajax button calls the wrong script

    I'm practicing writing Ajax scripts that talk to mysql. I wrote two buttons that, when clicked, use ajax to talk to mysql. I had the "Show Databases" button working fine. It called the "show_mysql_databases.html" script successfully (an apache directive tells apache to go thru html files) .

    I added the "Describe Customers Table" button that calls the "describe_customers_table.html script. This button works fine.

    Something went wrong after I added the second button. Now, clicking either button calls the "describe_customer_tables" script. Both buttons call the "describe" script. Neither calls the show_mysql_databases script.

    There is a line that I didn't write in the code below. I think my avg virus software wrote it. I highlighted the line in bold. I have the SAME problem with this script on another browser that doesn't run Windows XP or AVG antivirus.


    The html page:
    Code:
    <!DOCTYPE html>
    <html>
    <head>
    <title>Button</title>
    </head>
    <body>
    
    
    <div>
    <button name="conn_to_mysql" value="do" id = "1"  onclick = "showDatabases(); return false"  style = "float: left;
                          width: 10em;
    ">Show Databases</button>
    
    
    
    <div id = '2'  style = 'float: left;
                            width: 25em;
    '></div> 
    
    </div>
    
    
    
    <div>
    <button name="describe_customers_table" value="dop" id = "3"  onclick = "describeCustomersTable(); return false" style = "clear: left;
                                             width: 15em;
    ">Describe Customers Table</button>
    
    <div id = '4'  style = 'width: 25em;
    '></div> 
    </div>
    
    
    
    
    <script src="/A2EB891D63C8/avg_ls_dom.js" type="text/javascript"></script><script type="text/javascript"> 
      <!--
      var request;//The variable that makes ajax possible.
       try { request = new XMLHttpRequest();
       } catch (e) {
         if(request=undefined) alert('e.message');
         }
    //-->
    </script>
    
    
    <script type="text/javascript">
    <!--
    //function checkData(){
    //         alert(request.readyState);
    //         }
    function showDatabases() {
           if(request.readyState == 4){
              if(request.status == 200){
              var ajaxAnswer=document.getElementById("2");
              ajaxAnswer.innerHTML = request.responseText;
              }
              else 
              {
                alert("No Ajax Zip Code Response");
              }
           }
    }
       var show = encodeURIComponent(document.getElementById("1").value);
       var parameters = "conn_to_mysql="+show
       request.open("POST", "/cgi-bin/show_mysql_databases.html", true);
        //request.onreadystatechange = checkData;
       request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
       request.send(parameters);
    
    
    
    
    function describeCustomersTable() {
           if(request.readyState == 4){
              if(request.status == 200){
              var ajaxAnswer=document.getElementById("4");
              ajaxAnswer.innerHTML = request.responseText;
              }
              else {
                alert("No Ajax Zip Code Response");
              }
           }
    }
        var describe = encodeURIComponent(document.getElementById("3").value);
        var parameters = "describe_customers_table="+describe
        request.open("POST", "/cgi-bin/describe_customers_table.html", true);
        //request.onreadystatechange = checkData;
        request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        request.send(parameters);
    //-->
    </script>
    </body>
    </html>


    The show_mysql_databases.html script:
    PHP Code:
    <?php
    if(isset($_POST['conn_to_mysql'])) {
        
    $conn mysql_connect('localhost''root''xxxxxxxx');
        
    $qry "show databases;";
        
    $result mysql_query($qry$conn);


        while(
    $databases mysql_fetch_assoc($result))
        {
        echo 
    "<p>$databases[Database]</p>";
        }

        if(
    $conn)
        {
        echo 
    "<p>Connection To Mysql Established</p>";
        
    $close mysql_close($conn);

            if(
    $close)
            {
            echo 
    "<p>Mysql Connection Closed</p>";
            }
            else
            {
            echo 
    "<p>Connection did not close.</p>";
            }
        }
        else
        {
        echo 
    "<p>Could not connect to mysql</p>";
        }


    }

    The describe_customers_table.html script:
    PHP Code:
    <?php
    if(isset($_POST['describe_customers_table'])) {
        
    $conn mysql_connect('localhost''root''xxxxxxxx');
        
    $use "USE daily_schedule;";
        
    mysql_query($use$conn);
        
    $qry "DESCRIBE customers;";
        
    $result mysql_query($qry$conn);

        
    //Build Result String
        
    $result_string "<table>";
        
    $result_string .= "<tr>";
        
    $result_string .= "<th>Field</th>";
        
    $result_string .= "<th>Type</th>";
        
    $result_string .= "<th>Null</th>";
        
    $result_string .= "<th>Key</th>";
        
    $result_string .= "<th>Default</th>";
        
    $result_string .= "<th>Extra</th>";
        
    $result_string .= "</tr>";

        
    //Insert A New Row For Each Field In escribe Result Set

        
    while($row mysql_fetch_assoc($result))
        {
        
    $result_string .= "<tr>";
        
    $result_string .= "<td>$row[Field]</td>";
        
    $result_string .= "<td>$row[Type]</td>";
        
    $result_string .= "<td>$row[Null]</td>";
        
    $result_string .= "<td>$row[Key]</td>";
        
    $result_string .= "<td>$row[Default]</td>";
        
    $result_string .= "<td>$row[Extra]</td>";
        
    $result_string .= "</tr>";
        }
        
    $result_string .= "</table>";

        echo 
    $result_string;
    ?>
    Does anyone know what went wrong when I added the Describe Customers Table button? Thanks

  • #2
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,391
    Thanks
    11
    Thanked 568 Times in 561 Posts
    The curly brackets for your functions in Javascript are wrong. You end the functions before you start the requests. I think you'll have to move the request part into(!) the functions. The functions themselves only handle the request status changes. This is not correct. This should only be done by onreadystatechange handlers. All of this explains the behaviour that you described.
    Code:
    function showDatabases() {
       var show = encodeURIComponent(document.getElementById("1").value);
       var parameters = "conn_to_mysql="+show
       request.open("POST", "/cgi-bin/show_mysql_databases.html", true);
       request.onreadystatechange = function() {
           if(request.readyState == 4){
              if(request.status == 200){
              var ajaxAnswer=document.getElementById("2");
              ajaxAnswer.innerHTML = request.responseText;
              }
              else 
              {
                alert("No Ajax Zip Code Response");
              }
           }
       }
       request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
       request.send(parameters);
    }
    
    
    
    
    function describeCustomersTable() {
        var describe = encodeURIComponent(document.getElementById("3").value);
        var parameters = "describe_customers_table="+describe
        request.open("POST", "/cgi-bin/describe_customers_table.html", true);
        request.onreadystatechange = function() {
           if(request.readyState == 4){
              if(request.status == 200){
              var ajaxAnswer=document.getElementById("4");
              ajaxAnswer.innerHTML = request.responseText;
              }
              else {
                alert("No Ajax Zip Code Response");
              }
           }
        }
        request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        request.send(parameters);
    }

  • #3
    Regular Coder
    Join Date
    Dec 2011
    Posts
    186
    Thanks
    0
    Thanked 1 Time in 1 Post
    Thanks very much for taking the time to help. It works now. I'm curious about something.


    What is this code doing:
    Code:
    request.readystatechange = function()
    {
             if(request.readyState == 4)
             {
                    if(request.status == 200)
                    {
                     //return response to specific element
                    }
             }
    }

    That this code is not doing:
    Code:
     if(request.readyState == 4)
             {
                    if(request.status == 200)
                    {
                     //return response to specific element
                    }
             }

    In other words, why is this line so important?
    Code:
    request.readystatechange = function()
    Thank you

  • #4
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,391
    Thanks
    11
    Thanked 568 Times in 561 Posts
    first of all: It's onreadystatechange and not readystatechange

    But, more importantly: This is just the way it works, and it works this way with every asynchronous methods you can call from Javascript.

    Generally, Javascript is single-threaded. That means that only one thread will run at one given time (= the program flow). When you start a Ajax request it will run "in the background" (mostly on server side). When something happens with the request, the status of the request changes and the "normal program flow" must be informed about this. This is done by triggering the event "readystatechange" on the request object. The function that you assign to the onreadystatechange property will be called when this event is triggered.

    So if you omit the request.onreadystatechange = function() {...} part you'll check for the readyState == 4 immediately. But this will never work since the request is still running (readyState will always be 1 there).

  • #5
    Regular Coder
    Join Date
    Dec 2011
    Posts
    186
    Thanks
    0
    Thanked 1 Time in 1 Post
    Thanks for the explanation. It makes sense. I'll repeat some of what you said in my own words.

    Once javascript sends the key=value pair(in a post request) to the server script, it waits for the script to send an answer or response. Without the onreadystatechange event handler, the javascript if(readystate and status) function runs one time and does so immediately.

    "Immediately" is usually a point in time that is before the script has done its work and sends a response.

    If the server side script does not have a response ready before the if(readyState and status) function fires (it fires "immediately"), the function fires one time only and too soon to receive the response from the server.

    The chain of events that make ajax work is broken. The onreadystatechange event waits until the time is right, then runs the nested if statements contained within it.

    Only one ajax process can be run at a time, because it is single threaded. All of this makes sense. Thanks for pointing out the typo. I had it right in the script, so it works.

    Thanks very much for your help.

  • #6
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,391
    Thanks
    11
    Thanked 568 Times in 561 Posts
    Close, but not correct
    Once javascript sends the key=value pair(in a post request) to the server script, it waits for the script to send an answer or response.
    No, it's exactly the opposite. It does not wait for anything, it just continues with the next line of code regardless of what the state of the request is.
    the javascript if(readystate and status) function runs one time
    This is just an if statement and not a function. But you're right, the statement runs only once and it does that immediately after the request started but definitely before the request finishes.
    The onreadystatechange event waits until the time is right, then runs
    It doesn't wait. It's being called ("triggered") by a status change of the request.
    Only one ajax process can be run at a time, because it is single threaded
    Javascript is single threaded. But you can send more than one request to the same or different servers before another request has finished. So "Ajax" is not single threaded, just Javascript.

  • #7
    Regular Coder
    Join Date
    Dec 2011
    Posts
    186
    Thanks
    0
    Thanked 1 Time in 1 Post
    Thank you - one more question, if you're willing...


    In your first response you showed me the proper way to write the function. The first and last lines only are shown below to minimize typing:
    Code:
    function showDatabases() {
        var show = encodeURIComponent(document.getElementById("1").value);
        request.send(parameters);
    }
    This function runs onclick. If I wanted it to run automatically on page load, without the user clicking on anything, would I simply have to remove this part:
    Code:
    function showDatabases(){
    }
    and put the rest in script tags like this?
    Code:
    <script type = "text/javascript">
    var show = encodeURIComponent(document.getElementById("1").value);
    request.send(parameters);
    </script>

  • #8
    Senior Coder DanInMa's Avatar
    Join Date
    Nov 2010
    Location
    Salem,Ma
    Posts
    1,577
    Thanks
    13
    Thanked 248 Times in 248 Posts
    just a side not here, ID's shouldnt start with a number

  • #9
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,391
    Thanks
    11
    Thanked 568 Times in 561 Posts
    The first and last lines only are shown below to minimize typing
    So you mean all of the code, but you only show two lines? I ask because the two lines alone won't do anything good :-)

    Anyway, taking the code out of the function will only work if you move the code below the content of your page (maybe right before the closing </body> tag)

  • #10
    Regular Coder
    Join Date
    Dec 2011
    Posts
    186
    Thanks
    0
    Thanked 1 Time in 1 Post
    I know the entire code is needed to do the job. I haven't learned how to quote part of someone elses response, on this forum, in my own post yet. I just wrote the two lines to save myself some typing. I assumed you would know what I was referring to.


    I understand every detail counts - especially in programming. One wrong or omitted thing can crash a script.

    Thanks again for taking the time. You helped a lot.


    To DanInMA: The ID inside getElementById() or element ID's in general should not start with a number? Could you explain that a little more?
    Last edited by milesdriven; 04-02-2012 at 09:30 PM.

  • #11
    Senior Coder DanInMa's Avatar
    Join Date
    Nov 2010
    Location
    Salem,Ma
    Posts
    1,577
    Thanks
    13
    Thanked 248 Times in 248 Posts

    nm

    In CSS2, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [A-Za-z0-9] and ISO 10646 characters 161 and higher, plus the hyphen (-); they cannot start with a hyphen or a digit. They can also contain escaped characters and any ISO 10646 character as a numeric code (see next item). For instance, the identifier “B&W?” may be written as “B\&W\?” or “B\26 W\3F”.
    it's a css validity rule

  • #12
    Regular Coder
    Join Date
    Dec 2011
    Posts
    186
    Thanks
    0
    Thanked 1 Time in 1 Post
    Thanks DanInMa, you saved me some debugging.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •