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 9 of 9
  1. #1
    Regular Coder MaDmiX's Avatar
    Join Date
    Feb 2012
    Location
    Charlotte, NC
    Posts
    191
    Thanks
    50
    Thanked 0 Times in 0 Posts

    Returning xmlhttp.responseText as an array

    Hi All,

    I am trying to create some dynamic drop lists using data from some tables as the options in my lists. I have List1 and List2. Basically when the user makes a selection in List1, I am querying my List2 table and returning all the records that match as an array that I will use for the options in List2. I have the following code:

    Code:
    <script type="text/javascript">
    //Script to populate the dynamic drop lists
    function gimmeList2(){
    
    var str = document.getElementById('List1').value;
    alert(str);
    var itemsList2=[];
    
      xmlhttp=new XMLHttpRequest();
      xmlhttp.onreadystatechange=function() {
    
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
          if (xmlhttp.responseText) {
            itemsList2 = [xmlhttp.responseText];
            //location.reload();
            alert(itemsList2);
          }
        }
      }
    
    xmlhttp.open("GET","query-list2-items.php?Loc="+str,true);
    xmlhttp.send();
    
    document.forms['frmSupportRequest']['List2'].length = 1;
    document.forms['frmSupportRequest']['List2'].selectedIndex = 0;
    
      for (each in itemsList2) {
        var nOption = document.createElement('option'); 
        var nData = document.createTextNode(itemsList2[each]); 
        nOption.setAttribute('value',itemsList2[each]); 
        nOption.appendChild(nData); 
        currList.appendChild(nOption); 
      } 
    }
    </script>
    Here is my query:

    PHP Code:
    <?php require_once("../includes/connection.php"); ?>
    <?php 
    require_once("../includes/functions.php"); ?>
    <?php error_reporting 
    (E_ALL E_NOTICE); ?>
    <?php
        
    if(isset($_GET['Loc'])) {
            
    $tblLocationsID $_GET['Loc'];
        }

    ?>
    <?php
        $query 
    "SELECT `Equipment` FROM `tblequipment` WHERE `tblLocationsID` LIKE '$tblLocationsID'";
        
    $result=mysql_query($query);
        
    $row=mysql_fetch_array($result);
        
    $items=$row['Equipment'];

        if(
    $items) {
            echo 
    $items;
        }
    ?>
    <?php mysql_close
    ($dbConnection); ?>
    My problem is that I am not getting anything in List2 when I make a selection in List1. When I use alert(itemsList2); to see what is coming back from my query I get "Array". I am not very familiar with AJAX and I am sure I made a ton of mistakes. Can someone help me get this code to work?

    Thanks in advance,

    Ken

  • #2
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    If $items is an array and you use echo $items; the PHP will simply advise you that the variable is an array (unlike JavaScript where it will give you all the entries as a commanseparated list).

    To have it return the content of the array you will need to echo all of the array entries in a format the JavaScript can read.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • Users who have thanked felgall for this post:

    MaDmiX (11-14-2013)

  • #3
    Supreme Master coder! glenngv's Avatar
    Join Date
    Jun 2002
    Location
    Philippines
    Posts
    11,068
    Thanks
    0
    Thanked 256 Times in 252 Posts
    Try:
    PHP Code:
    echo json_encode($items); 
    and set xmlhttp.responseType = "json";
    Glenn
    ____________________________________

    My Blog
    Tower of Hanoi Android app (FREE!)
    Tower of Hanoi Leaderboard
    Samegame Facebook App
    vBulletin Plugins
    ____________________________________

  • #4
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,398
    Thanks
    12
    Thanked 570 Times in 563 Posts
    .responseType is only available for XMLHttpRequest Level 2

  • #5
    Regular Coder MaDmiX's Avatar
    Join Date
    Feb 2012
    Location
    Charlotte, NC
    Posts
    191
    Thanks
    50
    Thanked 0 Times in 0 Posts
    Hi felgall,

    I tried this:
    PHP Code:
    <?php require_once("../includes/connection.php"); ?>
    <?php 
    require_once("../includes/functions.php"); ?>
    <?php error_reporting 
    (E_ALL E_NOTICE); ?>
    <?php
        
    if(isset($_GET['Loc'])) {
            
    $tblLocationsID $_GET['Loc'];
        }

    ?>
    <?php
        $query 
    mysql_query("SELECT `Equipment` FROM `tblequipment` WHERE `tblLocationsID` LIKE '$tblLocationsID'");

        
    $items = array();
        while (
    $listItems mysql_fetch_row($query)) {
            
    $items[] = $listItems[0];
        }
    $result=implode(","$items);

    echo 
    $result
    ?>
    <?php mysql_close
    ($dbConnection); ?>
    But I am getting a Warning: Implode(): Invalid arguements passed in...

    I have used this before in other scripts and not gotten the warning. Are there any errors in my usage. None that I can see from reading the PHP manual. Please help.

    TIA,

    Ken

    Also, glenngv... I had already tried
    PHP Code:
    echo json_encode($items); 
    but this didn't seem to work (nothing returned). I didn't know about
    PHP Code:
    set xmlhttp.responseType "json"
    though so I may try this again. Where would
    PHP Code:
    set xmlhttp.responseType "json"
    go in the script?

    Thanks all for your help!

    Ken

  • #6
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    As you are just expecting the one value to be retrieved from the database you could use:

    PHP Code:
    <?php 
        $query 
    "SELECT `Equipment` FROM `tblequipment` WHERE `tblLocationsID` LIKE '$tblLocationsID'"
        
    $result=mysql_query($query); 
        
    $row=mysql_fetch_array($result); 
        
    $items=$row['Equipment']; 

        if(
    $items) { 
            echo 
    $items[0]; 
        } 
    ?>
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #7
    Regular Coder MaDmiX's Avatar
    Join Date
    Feb 2012
    Location
    Charlotte, NC
    Posts
    191
    Thanks
    50
    Thanked 0 Times in 0 Posts
    Aaaarghh!

    PHP Code:
    <?php 
        $query 
    "SELECT `Equipment` FROM `tblequipment` WHERE `tblLocationsID` LIKE '$tblLocationsID'"
        
    $result=mysql_query($query); 
        
    $row=mysql_fetch_array($result); 
        
    $items=$row['Equipment']; 

        if(
    $items) { 
            echo 
    $items[0]; 
        } 
    ?>
    This worked... sort of. The only thing that got echoed back was the first character of the first record in the results "V". I know this because the first record is "VTR".

    I double checked my query, pasting it into PHPMyAdmin and got back what I expected. So close, yet...

    What could be causing my output to be truncated like this?

    Ken

    UPDATE:

    OK this finally worked:
    PHP Code:
    <?php
        $query 
    mysql_query("SELECT `Equipment` FROM `tblequipment` WHERE `tblLocationsID` LIKE '$tblLocationsID'");

        
    $items = array();
        while (
    $listItems mysql_fetch_row($query)) {
            
    $items[] = $listItems[0];
        }
    $result=implode("','"$items);

    echo 
    "'".$result."'";
    It's the same thing I had tried earlier but for some odd reason now it's working. I am a little concerned because my ouput, while it is comma separated, it didn't have the quotes separating the array items like so 'item1','item2','item3' etc...). So I added this via the code. I don't know if it will ultimately make a difference. Hopefully it won't break the javascript side of things.

    Thanks everyone!

    Kind regards,

    Ken
    Last edited by MaDmiX; 11-14-2013 at 10:37 PM. Reason: Resolved.

  • #8
    Regular Coder MaDmiX's Avatar
    Join Date
    Feb 2012
    Location
    Charlotte, NC
    Posts
    191
    Thanks
    50
    Thanked 0 Times in 0 Posts

    Dynamically populate select options from tables

    Sharing incase anyone has a need to do this. I found this helpful as I built a webform for my admins to add/remove items from the tables, thus changing the dynamic select lists that are populated by them without using having to change any code:

    Here is the javascript function. You need to call this function on the change event of the select list before the one that's changing (i.e. List1 if List2 is changing). For List1, create the function and call it from the doc's onload event.
    Code:
    <script type="text/javascript">
    //Script to populate the dynamic drop lists
    function gimmeList2(){
    
    var str = document.getElementById('List1').value;
    
    
      document.forms['frmSupportRequest']['List2'].length = 1;
      document.forms['frmSupportRequest']['List2'].selectedIndex = 0;
    
      xmlhttp=new XMLHttpRequest();
      xmlhttp.onreadystatechange=function() {
    
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
          if (xmlhttp.responseText) {
            var itemsList2 = xmlhttp.responseText.split(",");
            var sel = document.getElementById('List2');
            for(var i = 0; i < itemsList2.length; i++) {
              var opt = document.createElement('option');
              opt.innerHTML = itemsList2[i];
              opt.value = itemsList2[i];
              sel.appendChild(opt);
            }        
          }
        }
      }
    
    xmlhttp.open("GET","query-list2-items.php?Loc="+str,true);
    xmlhttp.send();
    }
    </script>
    And the "query-list2-items.php" script:
    PHP Code:
    <?php
        
    if(isset($_GET['Loc'])) {
            
    $tblLocationsID $_GET['Loc'];
        }

    ?>
    <?php

        $query 
    mysql_query("SELECT `Equipment` FROM `tblequipment` WHERE `tblLocationsID` LIKE '$tblLocationsID'");

        
    $items = array();
        while (
    $listItems mysql_fetch_row($query)) {
            
    $items[] = $listItems[0];
        }
    $result=implode(","$items);

    echo 
    $result
    ?>
    Hope it helps someone

    Ken
    Last edited by MaDmiX; 11-15-2013 at 05:09 PM.

  • #9
    Supreme Master coder! glenngv's Avatar
    Join Date
    Jun 2002
    Location
    Philippines
    Posts
    11,068
    Thanks
    0
    Thanked 256 Times in 252 Posts
    Quote Originally Posted by MaDmiX View Post

    Also, glenngv... I had already tried
    PHP Code:
    echo json_encode($items); 
    but this didn't seem to work (nothing returned). I didn't know about
    PHP Code:
    set xmlhttp.responseType "json"
    though so I may try this again. Where would
    PHP Code:
    set xmlhttp.responseType "json"
    go in the script?

    Thanks all for your help!

    Ken
    Did you put xmlhttp.responseType before xmlhttp.send()?

    If that still doesn't work, then try using JSON.parse method instead.

    Code:
      xmlhttp.onreadystatechange=function() {
    
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
    
          console.log('raw response: ', xmlhttp.responseText);
    
          var items;
    
          try {
              items = JSON.parse(xmlhttp.responseText);
          }
          catch(e) { }
    
          console.log('parsed response: ', items);
    
        }
      }
    Last edited by glenngv; 11-15-2013 at 01:16 AM.
    Glenn
    ____________________________________

    My Blog
    Tower of Hanoi Android app (FREE!)
    Tower of Hanoi Leaderboard
    Samegame Facebook App
    vBulletin Plugins
    ____________________________________


  •  

    Posting Permissions

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