Need some AJAX/PHP/Array help

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • LuiePL
    New Member
    • Sep 2006
    • 24

    Need some AJAX/PHP/Array help

    I'm looking to repopulate some fields when an administrator chooses a different user. I think this can be done through arrays, since by the time it gets to the end computer the PHP has already been parsed, and running a javascript funtion with PHP in it, would ultimately prove fruitless. But what I'm trying to figure out is how to take the array that was built in PHP and pass it (as a global variable?) to the javascript to use and read.

    The PHP array is built somewhat like this:

    Users(User1(Num ber=>number, FirstName=>name ),User2(Number= >number, FirstName=>name ))

    So, since I have the information array within the "Users" array, it makes it that much harder.

    If you go to http://beta.eastcoast911.com/ you can see what I'm trying to do. On the top right, when you select a different user, it updates the number with the value, but I'm trying to get it to update the name. On the bottom it has created the table based on the following code:

    [PHP]echo "<table width='590px' border=1 cellpadding=0 cellspacing=0>" ;
    echo "<tr><th width='5px'>#</th><th>Number</th><th>First Name</th><th>Last Name</th><th>Location </th><th>About</th></tr>";

    $dbh = mysql_connect ("localhost" , "name", "password") or die ('Database Connection Error: ' . mysql_error());
    mysql_select_db ("db", $dbh);

    $sqlArr = 'SELECT Number,FirstNam e,LastName,Loca tion2,About FROM Users ORDER BY "Number" ASC';
    $dbsql = mysql_query($sq lArr) or die(mysql_error ());
    $row = mysql_num_rows( $dbsql);

    for ($i=0; $i < $row; $i++) {
    $myarray = mysql_fetch_row ($dbsql);
    echo "<tr><td valign='top' align=right>$i. </td>";
    for ($j=0; $j < 10; $j++) {
    echo "<td valign='top'>$m yarray[$j]</td>";
    };
    echo "</tr>\n";
    };
    echo "</table>";[/PHP]

    I've used this code for creating the array, and it works as well:

    [PHP]for ($i=0; $i < $row; $i++) {
    $myArr = mysql_fetch_row ($dbsql);
    for ($j=0; $j < 10; $j++) {
    $myArr[$i][$j] = $myArr[$j];
    };
    };[/PHP]
  • ronverdonk
    Recognized Expert Specialist
    • Jul 2006
    • 4259

    #2
    I do not know if your JavaScript code is within the same routine that you build you PHP arrays. But if so, would it be possible to define and populate a JS table from within the PHP code (by echoing js statements) and use that in your JavaScript routine? Code such as:

    [php]echo "var NamesArray=new Array();"; // define the JS array
    for ($i=0; $i < $row; $i++) {
    $myArr = mysql_fetch_row ($dbsql);
    for ($j=0; $j < 10; $j++) {
    $myArr[$i][$j] = $myArr[$j];
    echo "NamesArray[$i][$j] = '" . $myArr[$j] . "';"; // build the JS array
    }
    }[/php]

    Comment

    • LuiePL
      New Member
      • Sep 2006
      • 24

      #3
      Below is the code as it is now. if you go to the page it is on here, you'll notice it doesn't fill the table, or change the <div> field. So there's got to be an error somewhere in there. But I understand where you're coming from with your idea.

      Do I need to represent the PHP data differently since it's within the Javascript maybe?

      [PHP]
      echo "<table width='590px' border=1 cellpadding=0 cellspacing=0>" ;
      echo "<tr><th width='5px'>#</th><th>Number</th><th>First Name</th><th>Last Name</th><th>Location </th><th>About</th></tr>";
      $dbh = mysql_connect ("localhost" , "name", "password") or die ('Database Connection Error: ' . mysql_error());
      mysql_select_db ("database", $dbh);

      $sqlArr = 'SELECT Number,FirstNam e,LastName,Loca tion2,About FROM Users ORDER BY "Number" ASC';
      $dbsql = mysql_query($sq lArr) or die(mysql_error ());
      $row = mysql_num_rows( $dbsql);

      ?>
      <script language='javas cript'>
      <!--
      var NamesArray = new Array();
      <?php

      for ($i=0; $i < $row; $i++) {
      $myarray = mysql_fetch_row ($dbsql);
      echo "<tr><td valign='top' align=right>$i. </td>";
      for ($j=0; $j < 10; $j++) {
      echo "NamesArray[$i][$j] = '" . $myArr[$j] . "';"; // build the JS array
      if ($j == 0) {
      echo "<td valign='top'><a href='http://members.eastcoa st911.com/member.php?name =$myarray[$j]'>$myarray[$j]</a></td>";
      } else {
      echo "<td valign='top'>$m yarray[$j]</td>";
      }
      };
      echo "</tr>\n";
      };

      echo "document.getEl ementById('name Array').innerHT ML = NamesArray;";
      ?>
      var TestVal = NamesArray;
      document.getEle mentById("nameA rray").innerHTM L = "TestVal: "+TestVal;
      -->
      </script>
      <?php
      echo "</table>";
      echo "<table width='590px' border=1 cellpadding=0 cellspacing=0>" ;
      echo "<br /><div id='nameArray' style='width:10 0%;height:20'>" ;
      echo "nameArray" ;
      echo "</div>";
      echo "</table>";[/PHP]

      Comment

      • ronverdonk
        Recognized Expert Specialist
        • Jul 2006
        • 4259

        #4
        Maybe it is a little late to introduce this, but have you ever thought of using Ajax to dynamically extract your user data from the data base? That will save you a lot of code. Maybe you don't want that, I don't know. If you do, you can see a description and the source of such a dynamic process in the "Dynamic Client lookup" entry at http://www.dhtmlgoodies.com/index.html?page=ajax

        and the demo of this at http://www.dhtmlgoodies.com/scripts/...nt-lookup.html

        Just a thought

        Ronald :cool:

        Comment

        • LuiePL
          New Member
          • Sep 2006
          • 24

          #5
          That is actually what I've been trying to find, but no one's been able to help point me in that direction. I'll have to look at how it works it hopefully get it to work. Thanks for the help!

          Comment

          • LuiePL
            New Member
            • Sep 2006
            • 24

            #6
            I tried it out, but no luck. At first I just copied everything over just changing the values for my database. Then I tried to customize it so it's more inline with what I'm trying to do.

            You can see my page at http://beta.eastcoast911.com/lookup.php. I saved the ajax.js file so that's not the problem. I threw in a line into each function on the lookup.php page to change the <div> whenever it was called, but it never changes.

            Comment

            • franks
              New Member
              • Sep 2006
              • 3

              #7
              Since the number of fields that you are selecting from the database is less than the limit on your loop statement (10), I suggest changing the limit so as not to reference undefined elements in the array and also to use different arrays for the rows and the fields. You appear to be sending all of the data from the select statement to your page. You could send the data as an array once and let the javascript use the array for all the sections of your page. In that way, the data will not need to be repeated. This implementation will not use AJAX but use all of the data as an array that is loaded once when the page is loaded. The following PHP code (untested) inserted as part of the code generating the head section should get you an array in your javascript when the page loads.

              Code:
              for ($i=0; $i < $row; $i++) {
              
                  $myFields = mysql_fetch_row($dbsql);
              
                      for ($j=0; $j < count($myFields); $j++) {
              
                          $myArr[$i][$j] = $myFields[$j];
              
                          echo "NamesArray[$i][$j] = '" . $myArr[$i][$j] . "';";  // build the JS array
              
                   }
              
              }
              Using view source, you should be able to see all of the javascript code that creates the array in the head part of the page if the code executes successfully.

              Note that the array index for all of the fields will be numeric, so you will need to translate the position in the array to the field that you desire.

              If you want to use an AJAX implementation so that you don't need to download all of the data (and have it exposed via view source), you will need to convert the field data from the select statement to a string (serialize the data) to send it to the page and then deserialize it in the AJAX callback function. This approach could get the data for only the selected user when it is needed.

              Comment

              • LuiePL
                New Member
                • Sep 2006
                • 24

                #8
                I'd rather use the method you suggested. It makes it easier that way, and plus I want to learn AJAX, so I'd like to get it working.

                Comment

                • LuiePL
                  New Member
                  • Sep 2006
                  • 24

                  #9
                  Originally posted by ronverdonk
                  Maybe it is a little late to introduce this, but have you ever thought of using Ajax to dynamically extract your user data from the data base? That will save you a lot of code. Maybe you don't want that, I don't know. If you do, you can see a description and the source of such a dynamic process in the "Dynamic Client lookup" entry at http://www.dhtmlgoodies.com/index.html?page=ajax

                  and the demo of this at http://www.dhtmlgoodies.com/scripts/...nt-lookup.html

                  Just a thought

                  Ronald :cool:
                  I actually go most if it working now. The code in the demo is different than the code they give you which I thought was interesting... Below is the code I'm using on this page. The getMember.php page puts out the information right, so it's got to be something in the AJAX function somewhere.

                  Code:
                  var ajax = new sack();
                  var currentMemberID = false;
                  
                  function getMemberData()
                  {
                  	var indexThis = ajax.length;
                  	ajax[indexThis] = new sack();
                  	var memID = document.getElementById('memberID').value; <!--.replace(/[^0-9]/g,'');-->
                  	if(memID != currentMemberID){
                  		currentMemberID = memID;
                  		ajax[indexThis].requestFile = 'http://beta.eastcoast911.com/getMember.php?getMemberId='+memID;
                  		ajax[indexThis].onCompletion = function(){ showMemberData(indexThis); } ;
                  		ajax[indexThis].runAJAX();
                  		document.getElementById('info').innerHTML = "Member: "+memID;
                  	}
                  }
                  
                  function showMemberData(indexThis)
                  {
                  	var formObj = document.forms['memberInfo'];
                  	document.getElementById('info').innerHTML = "function showMemberData";
                  	eval(ajax[indexThis].response);
                  	document.getElementById('info').innerHTML = "ajax.response: "+ajax.response;
                  }
                  
                  function initFormEvents()
                  {
                  	document.getElementById('memberID').onchange = getMemberData;
                  	document.getElementById('memberID').onblur = getMemberData;
                  	document.getElementById('memberID').focus();
                  }
                  
                  window.onload = initFormEvents;

                  Comment

                  • domg
                    New Member
                    • Sep 2006
                    • 2

                    #10
                    Hie,

                    Hope the code below may help


                    <?
                    $array_php1 = array
                    (
                    "name1",
                    "name2",
                    );
                    $array_php2 = array
                    (
                    "surname1",
                    "surname2",
                    );
                    ?>
                    <script>
                    function change(i)
                    {
                    var name = new Array(<?
                    $separator1="";
                    for ($i=0; $i<count($array _php1) ; $i++)
                    {
                    echo $separator1."'" .$array_php1[$i]."'";
                    $separator1="," ;
                    }
                    ?>
                    );

                    var surname = new Array(<?
                    $separator2="";
                    for ($i=0; $i<count($array _php2) ; $i++)
                    {
                    echo $separator2. "'".$array_ php2[$i]."'";
                    $separator2="," ;
                    }
                    ?>
                    );
                    list1.elements['champ1'].value=name[i];
                    list1.elements['champ2'].value=surname[i];
                    }
                    </script>
                    <form name="list1">
                    <select name="list" onchange="chang e(this.selected Index)">
                    <option value=0>Choice1 </option>
                    <option value=1>Choice2 </option>
                    </select>
                    <input type=text name="champ1" value="default1 ">
                    <input type=text name="champ2" value="default2 ">
                    </form>

                    Comment

                    • ronverdonk
                      Recognized Expert Specialist
                      • Jul 2006
                      • 4259

                      #11
                      The code on the demo page http://www.dhtmlgoodies.com/index.ht..._client_lookup is working ok.
                      So it must be in the changes you made in the JavaScript for your member processing.

                      Ronald :cool:

                      Comment

                      • LuiePL
                        New Member
                        • Sep 2006
                        • 24

                        #12
                        Originally posted by ronverdonk
                        The code on the demo page http://www.dhtmlgoodies.com/index.ht..._client_lookup is working ok.
                        So it must be in the changes you made in the JavaScript for your member processing.

                        Ronald :cool:
                        Could it have anything to do with the fact that my memberID contains letters? I copied all the files from the demo just changing it so it would connect to my database and allow letters, and it doesnt work.

                        So I added the clients table to my database, and I'm getting a Syntax error for this line:

                        eval(ajaxObject s[indexThis].response);

                        Comment

                        • ronverdonk
                          Recognized Expert Specialist
                          • Jul 2006
                          • 4259

                          #13
                          Can you tell me why you use the indexThis variable? [PHP]var indexThis = ajax.length;[/PHP]
                          From the code I cannot see any purpose for having an index number that equals the size of an sajax instance.

                          Anyway, if you don't get out of it I can send you the demo code I downloaded, and adapted only to my table) and that works.

                          Ronald :cool:

                          Comment

                          • LuiePL
                            New Member
                            • Sep 2006
                            • 24

                            #14
                            Originally posted by ronverdonk
                            Can you tell me why you use the indexThis variable? [PHP]var indexThis = ajax.length;[/PHP]
                            From the code I cannot see any purpose for having an index number that equals the size of an sajax instance.

                            Anyway, if you don't get out of it I can send you the demo code I downloaded, and adapted only to my table) and that works.

                            Ronald :cool:
                            I have the indexThis in there because it's the only way the code goes from the getData function to the showData. However it's stopping at the eval() part for some reason.

                            Connecting to the database isn't the problem, because when I go to the getMember.php page and define the member number explicitly it returns the proper values.

                            You can email your code if you want, that might help.

                            Comment

                            • LuiePL
                              New Member
                              • Sep 2006
                              • 24

                              #15
                              I just added "Array()" around ajaxObjects[indexThis] and it's now working, a little. I now get it showing what the "ajaxObject s[indexThis].response" is. So I know that the eval() is working to an extent. Also I'm not getting "Done, with errors on page" messages, so the syntax is good.

                              So my code looks like:

                              Code:
                              var ajaxObjects = new Array();
                              var currentMemberID = false;
                              
                              function getMemberData()
                              {
                                var indexThis = ajaxObjects.length;
                                ajaxObjects[indexThis] = new sack();
                                var memberID = document.getElementById('memberID').value.replace(); <!--.replace(/[^0-9]/g,'');-->
                                if(memberID != currentMemberID){
                                  currentMemberID = memberID;
                                  ajaxObjects[indexThis].requestFile = 'http://beta.eastcoast911.com/getMember.php?getMemberId='+memberID;
                                  ajaxObjects[indexThis].onCompletion = function(){ showMemberData(indexThis); } ;
                                  ajaxObjects[indexThis].runAJAX();
                                  document.getElementById('info').innerHTML = "Member: "+memberID;
                                }
                              }
                              
                              function showMemberData(indexThis)
                              {
                                var formObj = document.forms['memberInfo'];
                                document.getElementById('info').innerHTML = "function showMemberData indexThis: "+indexThis;
                                eval(Array(ajaxObjects[indexThis]).response);
                                document.getElementById('info').innerHTML = "ajax.response: "+ajaxObjects[indexThis].response;
                              }
                              This is the output from the getMember.php page for pa370:

                              formObj.firstna me.value = 'Luie'; formObj.lastnam e.value = 'Lugo'; formObj.locatio n.value = 'Pennsylvania';

                              So it should work, but it's not setting the values when it runs the eval().
                              Last edited by LuiePL; Sep 22 '06, 02:49 AM. Reason: Switched some text

                              Comment

                              Working...