By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,818 Members | 2,121 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,818 IT Pros & Developers. It's quick & easy.

Need some AJAX/PHP/Array help

LuiePL
P: 24
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(Number=>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,FirstName,LastName,Location2,About FROM Users ORDER BY "Number" ASC';
$dbsql = mysql_query($sqlArr) 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'>$myarray[$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]
Sep 15 '06 #1
Share this Question
Share on Google+
23 Replies


ronverdonk
Expert 2.5K+
P: 4,258
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]
Sep 16 '06 #2

LuiePL
P: 24
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,FirstName,LastName,Location2,About FROM Users ORDER BY "Number" ASC';
$dbsql = mysql_query($sqlArr) or die(mysql_error());
$row = mysql_num_rows($dbsql);

?>
<script language='javascript'>
<!--
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.eastcoast911.com/member.php?name=$myarray[$j]'>$myarray[$j]</a></td>";
} else {
echo "<td valign='top'>$myarray[$j]</td>";
}
};
echo "</tr>\n";
};

echo "document.getElementById('nameArray').innerHTM L = NamesArray;";
?>
var TestVal = NamesArray;
document.getElementById("nameArray").innerHTML = "TestVal: "+TestVal;
-->
</script>
<?php
echo "</table>";
echo "<table width='590px' border=1 cellpadding=0 cellspacing=0>";
echo "<br /><div id='nameArray' style='width:100%;height:20'>";
echo "nameArray";
echo "</div>";
echo "</table>";[/PHP]
Sep 17 '06 #3

ronverdonk
Expert 2.5K+
P: 4,258
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:
Sep 17 '06 #4

LuiePL
P: 24
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!
Sep 17 '06 #5

LuiePL
P: 24
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.
Sep 17 '06 #6

P: 3
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.

Expand|Select|Wrap|Line Numbers
  1.  
  2. for ($i=0; $i < $row; $i++) {
  3.  
  4.     $myFields = mysql_fetch_row($dbsql);
  5.  
  6.         for ($j=0; $j < count($myFields); $j++) {
  7.  
  8.             $myArr[$i][$j] = $myFields[$j];
  9.  
  10.             echo "NamesArray[$i][$j] = '" . $myArr[$i][$j] . "';";  // build the JS array
  11.  
  12.      }
  13.  
  14.  
  15.  
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.
Sep 18 '06 #7

LuiePL
P: 24
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.
Sep 19 '06 #8

LuiePL
P: 24
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.

Expand|Select|Wrap|Line Numbers
  1. var ajax = new sack();
  2. var currentMemberID = false;
  3.  
  4. function getMemberData()
  5. {
  6.     var indexThis = ajax.length;
  7.     ajax[indexThis] = new sack();
  8.     var memID = document.getElementById('memberID').value; <!--.replace(/[^0-9]/g,'');-->
  9.     if(memID != currentMemberID){
  10.         currentMemberID = memID;
  11.         ajax[indexThis].requestFile = 'http://beta.eastcoast911.com/getMember.php?getMemberId='+memID;
  12.         ajax[indexThis].onCompletion = function(){ showMemberData(indexThis); } ;
  13.         ajax[indexThis].runAJAX();
  14.         document.getElementById('info').innerHTML = "Member: "+memID;
  15.     }
  16. }
  17.  
  18. function showMemberData(indexThis)
  19. {
  20.     var formObj = document.forms['memberInfo'];
  21.     document.getElementById('info').innerHTML = "function showMemberData";
  22.     eval(ajax[indexThis].response);
  23.     document.getElementById('info').innerHTML = "ajax.response: "+ajax.response;
  24. }
  25.  
  26. function initFormEvents()
  27. {
  28.     document.getElementById('memberID').onchange = getMemberData;
  29.     document.getElementById('memberID').onblur = getMemberData;
  30.     document.getElementById('memberID').focus();
  31. }
  32.  
  33. window.onload = initFormEvents;
Sep 21 '06 #9

P: 2
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="change(this.selectedIndex)">
<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>
Sep 21 '06 #10

ronverdonk
Expert 2.5K+
P: 4,258
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:
Sep 21 '06 #11

LuiePL
P: 24
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(ajaxObjects[indexThis].response);
Sep 21 '06 #12

ronverdonk
Expert 2.5K+
P: 4,258
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:
Sep 21 '06 #13

LuiePL
P: 24
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.
Sep 22 '06 #14

LuiePL
P: 24
I just added "Array()" around ajaxObjects[indexThis] and it's now working, a little. I now get it showing what the "ajaxObjects[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:

Expand|Select|Wrap|Line Numbers
  1. var ajaxObjects = new Array();
  2. var currentMemberID = false;
  3.  
  4. function getMemberData()
  5. {
  6.   var indexThis = ajaxObjects.length;
  7.   ajaxObjects[indexThis] = new sack();
  8.   var memberID = document.getElementById('memberID').value.replace(); <!--.replace(/[^0-9]/g,'');-->
  9.   if(memberID != currentMemberID){
  10.     currentMemberID = memberID;
  11.     ajaxObjects[indexThis].requestFile = 'http://beta.eastcoast911.com/getMember.php?getMemberId='+memberID;
  12.     ajaxObjects[indexThis].onCompletion = function(){ showMemberData(indexThis); } ;
  13.     ajaxObjects[indexThis].runAJAX();
  14.     document.getElementById('info').innerHTML = "Member: "+memberID;
  15.   }
  16. }
  17.  
  18. function showMemberData(indexThis)
  19. {
  20.   var formObj = document.forms['memberInfo'];
  21.   document.getElementById('info').innerHTML = "function showMemberData indexThis: "+indexThis;
  22.   eval(Array(ajaxObjects[indexThis]).response);
  23.   document.getElementById('info').innerHTML = "ajax.response: "+ajaxObjects[indexThis].response;
  24. }
This is the output from the getMember.php page for pa370:

formObj.firstname.value = 'Luie'; formObj.lastname.value = 'Lugo'; formObj.location.value = 'Pennsylvania';

So it should work, but it's not setting the values when it runs the eval().
Sep 22 '06 #15

ronverdonk
Expert 2.5K+
P: 4,258
In my opinion the eval should be without the Array() as in:
[PHP]eval(ajaxObjects[indexThis].response);[/PHP]
Suggest you put an alert in front of the eval
[PHP]alert (ajaxObjects[indexThis].response);[/PHP]
and the alert should also show:
Expand|Select|Wrap|Line Numbers
  1. formObj.firstname.value='Luie';
  2. formObj.lastname.value='Lugo';
  3. formObj.location.value='Pennsylvania';
Ronald :cool:
Sep 22 '06 #16

LuiePL
P: 24
Well this is interesting... I threw in the alert and it shows this:

[HTML]<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>

<body>

formObj.firstname.value = 'Luie';
formObj.lastname.value = 'Lugo';
formObj.location.value = 'Pennsylvania';
formObj.about.value = 'Web Team, Dispatcher 370, Author';

</body>
</html>[/HTML]

However, on the page it only shows:

[HTML]formObj.firstname.value = 'Luie';
formObj.lastname.value = 'Lugo';
formObj.location.value = 'Pennsylvania';
formObj.about.value = 'Web Team, Dispatcher 370, Author';[/HTML]

When I throw in Array() around ajax response it shows it as undefined. So there's a problem somewhere only getting the formObj information from the getMember page.
Sep 22 '06 #17

LuiePL
P: 24
OK I got rid of the HTML tags in the getMember.php file (something that shouldn't have been there to begin with), so it's no longer giving me all the code, however, it's still not populating the fields as it should.
Sep 23 '06 #18

LuiePL
P: 24
YES!!! OK, well I was looking through the code some more, and tried to display the whole eval(Array()) thing and it was showing as undefined, so I dropped the Array() and now it's working. So I guess it had to do with the HTML tags, now that they're gone, it's working!

I just have to fiddle with the Location a little, since it's a drop down right now, but at least it's working. Thanks for the help guys!
Sep 23 '06 #19

ronverdonk
Expert 2.5K+
P: 4,258
As I said in my entry yesterday, you had to get rid of the array() because the eval() function accepts only a code string!

I am still confused about the reason why you use arrays and indexes. I thought this really was a straight-forward application like: you type in a number and I will get the associated data from the database. But it obviously is not.
Anyway, good luck!

Ronald :cool:
Sep 23 '06 #20

LuiePL
P: 24
As I said in my entry yesterday, you had to get rid of the array() because the eval() function accepts only a code string!

I am still confused about the reason why you use arrays and indexes. I thought this really was a straight-forward application like: you type in a number and I will get the associated data from the database. But it obviously is not.
Anyway, good luck!

Ronald :cool:
I went through my test page and got rid of the Array it it works with out it. So I got rid of it on my live page, and it works there also, so I'm thinking it was only necessary when I had the HTML tag issue.

Now the only issue I've run into is it not working in firefox. Throughout the testing it never worked, so it's not something that I suddenly changed that stopped it. I threw up a message on the live page telling the people that they have to use IE for it to work properly, so I'm too concerned about it.
Sep 23 '06 #21

ronverdonk
Expert 2.5K+
P: 4,258
I am not knowledeable enough to advise you on your Firefox/Ajax issue, but you could visit the Round-up of 30 AJAX Tutorials link and see if anyone of those authors can help you out here.

Good luck!

ROnald :cool:
Sep 24 '06 #22

LuiePL
P: 24
OK, I'll look through those when I get some time. Thanks for all your help in getting this to work.
Sep 24 '06 #23

P: 1
I know that this is a little late in the ballgame considering the date you posted your last reply, but Firefox and other Mozilla based browsers don't use the ActiveXObject (which is the only thing your ajax.js is looking for).

For Firefox and other Mozilla based browsers, you want to use:

XMLHttpRequest

as in

Expand|Select|Wrap|Line Numbers
  1. request = new XMLHttpRequest;
Not sure if you needed this or not, but thought it would be helpful

*Edit: Nevermind, I see where the XMLHttpRequest is. I was looking at the original one posted on htmlgoodies.
Jul 11 '07 #24

Post your reply

Sign in to post your reply or Sign up for a free account.