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.
Page 1 of 2 12 LastLast
Results 1 to 15 of 16
  1. #1
    New Coder
    Join Date
    Jun 2013
    Posts
    14
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Not sure if Ajax actually sent values

    Hi, I am trying to make my script so that when the user chooses one part of the option given, Ajax will send a variable through a page, the page where the variable is sent to will process the variable and from there decide what tables in the database will it take the information from and after that send back the array, where it will be used to display the title of the table and the result. I have omitted the result portion below the code

    The problem here is that for the life of me, I can't seem to be sure whether or not does Ajax actually send the variable to the other page or did the other page actually send the variable sent the result back to the original page since when I run it nothing actually happens.

    I would really appreciate having any feedback on how to optimize or correct this error, since I have spent quite an amount of time correcting this but to no avail. Thanks!

    This is the javascript

    Code:
    function ChoiceSelect()
    {
    var mylist=document.getElementById("myList");
    var selectedString = mylist.options[mylist.selectedIndex].value;
    if ((selectedString=="course")||(selectedString=="school")){
    
    $.ajax({
        type: "GET",
        url: "getComparison.php",
        data: "subject=" + selectedString,
        cache: false,
        success: function(msg){
            comparison = $.parseJSON(msg);
            var table=document.getElementById("comparetable");
            if(selectedString=="course"){
    for(var i = document.getElementById("comparetable").rows.length; i > 0;i--)
                {
                document.getElementById("comparetable").deleteRow(i -1);
                }
        
                var row = table.insertRow(-1);
                var celltext = ["Id","Name","Detail","School Offered","Course Start","Course End","Compare"];
                for(var i=0; i<7; i++){
                       var cell = row.insertCell(-1);
                       cell.appendChild(document.createTextNode(celltext[i]));
                }
                
            }
            else if(selectedString=="school"){
                for(var i = document.getElementById("comparetable").rows.length; i > 0;i--)
                {
                document.getElementById("comparetable").deleteRow(i -1);
                }
                var row = table.insertRow(-1);
                var celltext = ["Id","Name","Address","Details","Location","Created","Picture","Compare"];
                for(var i=0; i<7; i++){
                       var cell = row.insertCell(-1);
                       cell.appendChild(document.createTextNode(celltext[i]));
                }
            }
    }
        });
    }
    }
    This is the html code in question

    Code:
    <select id="myList" onchange="ChoiceSelect()">
      <option value =" ">Please select a value</option>
      <option value="school">School</option>
      <option value="course">Course</option>
    </select>
    
        
    <table border="1" id="comparetable">
        
    </table>

  • #2
    Senior Coder
    Join Date
    Jan 2011
    Location
    Missouri
    Posts
    4,174
    Thanks
    23
    Thanked 601 Times in 600 Posts
    A suggestion. I changed the JS to this:
    Code:
    function ChoiceSelect(selectedString)
    {
    //var   document.getElementById("myList");
    //var selectedString = mylist.options[mylist.selectedIndex].value;
    ...
    and the HTML to:
    Code:
    <select id="myList" onchange="ChoiceSelect(this.value)">
    ...
    and this does send the variable.


    Your if(selectedString=="course"){} and if(selectedString=="school"){} should be done in the php file, not here. Although it's not against any laws.
    Last edited by sunfighter; 06-11-2013 at 04:43 PM.
    Evolution - The non-random survival of random variants.

    "If you leave hydrogen alone, for long enough, it begins to think about itself."

  • #3
    New Coder
    Join Date
    Jun 2013
    Posts
    14
    Thanks
    6
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by sunfighter View Post
    A suggestion. I changed the JS to this:
    Code:
    function ChoiceSelect(selectedString)
    {
    //var   document.getElementById("myList");
    //var selectedString = mylist.options[mylist.selectedIndex].value;
    ...
    and the HTML to:
    Code:
    <select id="myList" onchange="ChoiceSelect(this.value)">
    ...
    and this does send the variable.


    Your if(selectedString=="course"){} and if(selectedString=="school"){} should be done in the php file, not here. Although it's not against any laws.
    Hi, thanks for the reply, I am assuming the variable on the first code second sentence is referring to mylist? If that's the case, I have done what you asked exactly to a T but still nothing happens.

    Out of curiosity,why is using the if/else statement from php more applicable here?

  • #4
    Senior Coder
    Join Date
    Jan 2011
    Location
    Missouri
    Posts
    4,174
    Thanks
    23
    Thanked 601 Times in 600 Posts
    I have done what you asked exactly to a T but still nothing happens.
    Then the problem is in the php file 'getComparison.php' post that code.

    Out of curiosity,why is using the if/else statement from php more applicable here?
    Just cuts down in the amount of code sent to the browser, less work for the browser, and hides it from prying eyes. No other reason. If you want it in a browser fine. I like things on the server which I am lead to believe is faster.
    Evolution - The non-random survival of random variants.

    "If you leave hydrogen alone, for long enough, it begins to think about itself."

  • #5
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,334
    Thanks
    11
    Thanked 587 Times in 568 Posts
    Quote Originally Posted by sunfighter View Post
    I like things on the server which I am lead to believe is faster.
    hmm. i'll race V8, chakra, or ionMonkey against zend any day of the week. V8 was about 5X faster when i did a mini-benchmark in 2010, and V8 is even faster now...

    that aside, you don't need an if at all, and you can never send the extra code if you use better JS:


    Code:
    var selectedString = mylist.options[mylist.selectedIndex].value;
    if ((selectedString=="course")||(selectedString=="school")){
    
    $.ajax({
        type: "GET",
        url: "getComparison.php",
        data: "subject=" + selectedString,
        cache: false,
        success: function(msg){
            comparison = $.parseJSON(msg);
            var table=document.getElementById("comparetable");
            
           var celltext =  selectedString=="course" ?
                   ["Id","Name","Detail","School Offered","Course Start","Course End","Compare"] :
                   ["Id","Name","Address","Details","Location","Created","Picture","Compare"];
    
                for(var i = table.rows.length; i > 0;i--){
                  table.deleteRow(i -1);
                }
        
                var row = table.insertRow(-1);
                for(var i=0; i<7; i++){
                       var cell = row.insertCell(-1);
                       cell.appendChild(document.createTextNode(celltext[i]));
                }
                
               
       }  
              
        });
    
    }
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  • #6
    Senior Coder
    Join Date
    Jan 2011
    Location
    Missouri
    Posts
    4,174
    Thanks
    23
    Thanked 601 Times in 600 Posts
    Quote Originally Posted by rnd me View Post
    hmm. i'll race V8, chakra, or ionMonkey against zend any day of the week. V8 was about 5X faster when i did a mini-benchmark in 2010, and V8 is even faster now...
    That good to know. Shattered what I have been taught.
    Evolution - The non-random survival of random variants.

    "If you leave hydrogen alone, for long enough, it begins to think about itself."

  • #7
    New Coder
    Join Date
    Jun 2013
    Posts
    14
    Thanks
    6
    Thanked 0 Times in 0 Posts
    Hi thanks for all of your constructive suggestions as well as taking the time to read my codes. Since from my personal experience reading and troubleshooting codes is the toughest and most time consuming thing in programming.

    Quote Originally Posted by rnd me View Post
    hmm. i'll race V8, chakra, or ionMonkey against zend any day of the week. V8 was about 5X faster when i did a mini-benchmark in 2010, and V8 is even faster now...

    that aside, you don't need an if at all, and you can never send the extra code if you use better JS:


    Code:
    var selectedString = mylist.options[mylist.selectedIndex].value;
    if ((selectedString=="course")||(selectedString=="school")){
    
    $.ajax({
        type: "GET",
        url: "getComparison.php",
        data: "subject=" + selectedString,
        cache: false,
        success: function(msg){
            comparison = $.parseJSON(msg);
            var table=document.getElementById("comparetable");
            
           var celltext =  selectedString=="course" ?
                   ["Id","Name","Detail","School Offered","Course Start","Course End","Compare"] :
                   ["Id","Name","Address","Details","Location","Created","Picture","Compare"];
    
                for(var i = table.rows.length; i > 0;i--){
                  table.deleteRow(i -1);
                }
        
                var row = table.insertRow(-1);
                for(var i=0; i<7; i++){
                       var cell = row.insertCell(-1);
                       cell.appendChild(document.createTextNode(celltext[i]));
                }
                
               
       }  
              
        });
    
    }
    I don't quite understand what you meant by not needing the if/else statement. Isn't the "?" you used in the code(Just googled that out that it is a tenary operation) a shorter term of the if/else statement?

    Another thing that worries me about the reply you gave me is that if I put in more extra code, I can never execute all of it. That is really troubling since I have been planning to add more codes down this particular function after this problem has been solved, but after hearing this, I do not know what step do I need to take next. Is there any better way or suggestion on how to remedy this?

    Quote Originally Posted by sunfighter View Post
    Then the problem is in the php file 'getComparison.php' post that code.


    Just cuts down in the amount of code sent to the browser, less work for the browser, and hides it from prying eyes. No other reason. If you want it in a browser fine. I like things on the server which I am lead to believe is faster.
    This is the php code that I did for getComparison.php.

    PHP Code:
    <?php

    include ('dbFunctions.php');

    $id $_GET['subject'];
    $data = Array();

    if (
    $id=="school"){
    // SQL query returns multiple database records.
    $query "SELECT * FROM school,course WHERE school.school_id=course.school_id"
    }

    else if(
    $id=="course"){
        
    $query="SELECT * FROM $id";
    }

    $result mysqli_query($link$query);
    while (
    $row mysqli_fetch_array($result)) {
        
    $data[] = $row;
    }

    echo 
    json_encode($data);

    ?>

  • #8
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,334
    Thanks
    11
    Thanked 587 Times in 568 Posts
    Quote Originally Posted by alucard786 View Post
    Another thing that worries me about the reply you gave me is that if I put in more extra code, I can never execute all of it. That is really troubling since I have been planning to add more codes down this particular function after this problem has been solved, but after hearing this, I do not know what step do I need to take next. Is there any better way or suggestion on how to remedy this?
    if you want to choose from many, then you REALY can get rid of the if, so long as only one thing changes between them, in this case the cellText array:

    Code:
    var celltext =   { 
    course: ["Id","Name","Detail","School Offered","Course Start","Course End","Compare"] ,
     school:  ["Id","Name","Address","Details","Location","Created","Picture","Compare"]
    }[selectedString];
    you can add new rows as you expand the app, and yet you don't ever have to repeat yourself like you would using an if
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  • #9
    New Coder
    Join Date
    Jun 2013
    Posts
    14
    Thanks
    6
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by rnd me View Post
    if you want to choose from many, then you REALY can get rid of the if, so long as only one thing changes between them, in this case the cellText array:

    Code:
    var celltext =   { 
    course: ["Id","Name","Detail","School Offered","Course Start","Course End","Compare"] ,
     school:  ["Id","Name","Address","Details","Location","Created","Picture","Compare"]
    }[selectedString];
    you can add new rows as you expand the app, and yet you don't ever have to repeat yourself like you would using an if
    Wow, I didn't that you can actually do it that way, thanks a lot for the suggestion!

    The bad news is, nothing still happens when I change the code appropriately though...

  • #10
    Senior Coder
    Join Date
    Jan 2011
    Location
    Missouri
    Posts
    4,174
    Thanks
    23
    Thanked 601 Times in 600 Posts
    alucard786, you can run getComparison.php by it's self and see if it works, but you have to change line 5 from "$id = $_GET['subject'];" to "$id = 'course';" and then to 'school'. I can see where course yields a single <table>, but not with school which queries two DBs. Your calling file only has
    Code:
    <table border="1" id="comparetable"> </table>
    Like I said before, I would make the <table> in getComparison.php and echo that to be put in a div. But that's me.
    Evolution - The non-random survival of random variants.

    "If you leave hydrogen alone, for long enough, it begins to think about itself."

  • #11
    New Coder
    Join Date
    Jun 2013
    Posts
    14
    Thanks
    6
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by sunfighter View Post
    alucard786, you can run getComparison.php by it's self and see if it works, but you have to change line 5 from "$id = $_GET['subject'];" to "$id = 'course';" and then to 'school'. I can see where course yields a single <table>, but not with school which queries two DBs. Your calling file only has
    Code:
    <table border="1" id="comparetable"> </table>
    Like I said before, I would make the <table> in getComparison.php and echo that to be put in a div. But that's me.
    Hi thanks for the reply, was just wondering, doesn't a join statement joins two tables into one? If that's the case, doesn't that mean that one table is already sufficient for it? (Speaking on my own experience)

    After trying your method on testing, nothing still seems to work as well :( I guess I will repost the whole page that I currently have at the moment.

    Again, this is my html page along with my javascript(GetComparison.php was left unchanged)

    Code:
    <!DOCTYPE html>
    <html>
    <head>
    <title>Comparison page</title>
    <script type="text/javascript">
    
    function ChoiceSelect(selectedString)
    {
    var mylist=document.getElementById("myList");
    var selectedString = mylist.options[mylist.selectedIndex].value;
    if ((selectedString=="course")||(selectedString=="school")){
    $.ajax({
        type: "GET",
        url: "getComparison.php",
        data: "subject=" + selectedString,
        cache: false,
        success: function(msg){
            var comparison = $.parseJSON(msg);
            var table=document.getElementById("comparetable");
           
        var celltext =   { 
        course: ["Id","Name","Detail","School Offered","Course Start","Course End","Compare"] ,
        school:  ["Id","Name","Address","Details","Location","Created","Picture","Compare"]
        }[selectedString];
    
                for(var i = table.rows.length; i > 0;i--){
                  table.deleteRow(i -1);
                }
        
                var row = table.insertRow(-1);
                for(var i=0; i<7; i++){
                       var cell = row.insertCell(-1);
                       cell.appendChild(document.createTextNode(celltext[i]));
                }
                
               
       }  
              
        });
    
    }
    }
    </script>
    </head>
    
    <body>
    
    Please choose the subject to compare
    <select id="myList" onchange="ChoiceSelect(this.value)">
      <option value =" ">Please select a value</option>
      <option value="school">School</option>
      <option value="course">Course</option>
    </select>
    
    <form name="Do_Comparison" action="comparison.php" method ="POST">
    <table border="1" id="comparetable">
        
    </table>
        
    </form>
    </body>
    
    </html>

  • #12
    Senior Coder
    Join Date
    Jan 2011
    Location
    Missouri
    Posts
    4,174
    Thanks
    23
    Thanked 601 Times in 600 Posts
    After trying your method on testing, nothing still seems to work as well
    A curious line. Did getComparison.php print out a json response for you and was it what you expected?
    Evolution - The non-random survival of random variants.

    "If you leave hydrogen alone, for long enough, it begins to think about itself."

  • #13
    New Coder
    Join Date
    Jun 2013
    Posts
    14
    Thanks
    6
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by sunfighter View Post
    A curious line. Did getComparison.php print out a json response for you and was it what you expected?
    Yes it is. First off, I tried using a sample variable of a certain string in getComparison.php as well as changing the code in line 5 and assigning them different values when they pass through the different if statement. It does successfully print out the accurate print out a JSON response correctly.

    Side note, I tried commenting out the ajax codes on Comparison.php and without them, the table come out perfectly(Take note that I am using rnd me code, refer to the previous reply of my Comparison.php)

    Could it be something to do with the ajax itself? Or do I miss a comma or something? I just can't figure it out

  • #14
    Senior Coder
    Join Date
    Jan 2011
    Location
    Missouri
    Posts
    4,174
    Thanks
    23
    Thanked 601 Times in 600 Posts
    Back after hectic Father day week end.
    About this
    Code:
    $query = "SELECT * FROM school, course WHERE school.school_id = course.school_id";
    Does not work for a few reasons. You don't have a column called school_id in either table. Your columns are different in both tables nullifying the everything star.

    Trying to piece this together. See if this is correct:
    In the course table we name name = this is name of course like 'algebra', School Offered = the name of the school.

    In school table we have name = school name and is equal to School Offered in the course table. Plus a lot of info on the school.

    I'm thinking you want to get table information on the school that teaches the course the user wants to take. Or do you want to display the courses that a school is teaching and when? We need to know this before proceeding.

    This is how I would handle this for course. Code could be cleaned up a little, but this does work.
    Changed out table for div:
    Code:
    <!DOCTYPE html>
    <html>
    <head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
    <script type="text/javascript">
    function ChoiceSelect()
    {
    	var mylist=document.getElementById("myList");
    	var selectedString = mylist.options[mylist.selectedIndex].value;
    	if ((selectedString=="course")||(selectedString=="school")){
    
    		$.ajax({
    			type: "GET",
    			url: getComparison.php",
    			data: "subject=" + selectedString,
    			cache: false,
    			success: function(msg){
    				document.getElementById('comparetable').innerHTML = msg;
    			}
    		});
    	}
    }
    </script>
    </head>
    <body>
    <select id="myList" onchange="ChoiceSelect()">
      <option value =" ">Please select a value</option>
      <option value="school">School</option>
      <option value="course">Course</option>
    </select>
    
    <div id="comparetable"></div>
    </body>
    </html>
    And getComparison.php
    PHP Code:
     <?php
    include ('dbFunctions.php');

    $id 'course'// $_GET['subject'];

    //if ($id=="school"){
    // SQL query returns multiple database records.

    //}

    if($id=="course"){
        
    $query "SELECT * FROM $id";
        
    $result mysqli_query($link$query);
        
    $colCount mysqli_field_count($link);
        echo 
    "<br /><table id='myTable' border='1'>";
        echo 
    "<tr>";
        for(
    $colNumber 0$colNumber $colCount$colNumber++)
        {
            
    $fieldName mysqli_fetch_field($result); // FETCHES THE COLUMN NAMES
            
    echo "<th>$fieldName->name</th>";
        }
        echo 
    "</tr>";

        while(
    $row mysqli_fetch_row($result)){  // PUTS VALUES OF THE ROWS INTO THE CORRECT COLUMNS
            
    echo "<tr align=left VALIGN=TOP>";
            for(
    $colNumber 0$colNumber $colCount$colNumber++){
                echo 
    "<td>$row[$colNumber]</td>";
            }
            echo 
    "</tr>";
        }
    echo 
    "</table><br />";
    }
    ?>
    Evolution - The non-random survival of random variants.

    "If you leave hydrogen alone, for long enough, it begins to think about itself."

  • Users who have thanked sunfighter for this post:

    alucard786 (06-21-2013)

  • #15
    New Coder
    Join Date
    Jun 2013
    Posts
    14
    Thanks
    6
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by sunfighter View Post
    Back after hectic Father day week end.
    About this
    Code:
    $query = "SELECT * FROM school, course WHERE school.school_id = course.school_id";
    Does not work for a few reasons. You don't have a column called school_id in either table. Your columns are different in both tables nullifying the everything star.

    Trying to piece this together. See if this is correct:
    In the course table we name name = this is name of course like 'algebra', School Offered = the name of the school.

    In school table we have name = school name and is equal to School Offered in the course table. Plus a lot of info on the school.

    I'm thinking you want to get table information on the school that teaches the course the user wants to take. Or do you want to display the courses that a school is teaching and when? We need to know this before proceeding.

    This is how I would handle this for course. Code could be cleaned up a little, but this does work.
    Changed out table for div:
    Code:
    <!DOCTYPE html>
    <html>
    <head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
    <script type="text/javascript">
    function ChoiceSelect()
    {
    	var mylist=document.getElementById("myList");
    	var selectedString = mylist.options[mylist.selectedIndex].value;
    	if ((selectedString=="course")||(selectedString=="school")){
    
    		$.ajax({
    			type: "GET",
    			url: getComparison.php",
    			data: "subject=" + selectedString,
    			cache: false,
    			success: function(msg){
    				document.getElementById('comparetable').innerHTML = msg;
    			}
    		});
    	}
    }
    </script>
    </head>
    <body>
    <select id="myList" onchange="ChoiceSelect()">
      <option value =" ">Please select a value</option>
      <option value="school">School</option>
      <option value="course">Course</option>
    </select>
    
    <div id="comparetable"></div>
    </body>
    </html>
    And getComparison.php
    PHP Code:
     <?php
    include ('dbFunctions.php');

    $id 'course'// $_GET['subject'];

    //if ($id=="school"){
    // SQL query returns multiple database records.

    //}

    if($id=="course"){
        
    $query "SELECT * FROM $id";
        
    $result mysqli_query($link$query);
        
    $colCount mysqli_field_count($link);
        echo 
    "<br /><table id='myTable' border='1'>";
        echo 
    "<tr>";
        for(
    $colNumber 0$colNumber $colCount$colNumber++)
        {
            
    $fieldName mysqli_fetch_field($result); // FETCHES THE COLUMN NAMES
            
    echo "<th>$fieldName->name</th>";
        }
        echo 
    "</tr>";

        while(
    $row mysqli_fetch_row($result)){  // PUTS VALUES OF THE ROWS INTO THE CORRECT COLUMNS
            
    echo "<tr align=left VALIGN=TOP>";
            for(
    $colNumber 0$colNumber $colCount$colNumber++){
                echo 
    "<td>$row[$colNumber]</td>";
            }
            echo 
    "</tr>";
        }
    echo 
    "</table><br />";
    }
    ?>
    Hi thanks for the reply and welcome back :D

    Actually I have combined the two tables, school and course together which I didn't post(It's in another separate database server) and yes, the thing that is joining them together is actually the school_id itself(Since when the user wants to do a course comparison he wants to see the school that is offering it).

    I haven't tried your code yet(since the files are stored in another separate location) and I will most probably try it somehow later the day. I will keep you posted afterwards, thanks again!


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

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