-1

I am retrieving data from database using AJAX and PHP. In database one of the columns contains path of an image folder. I am saving the value of path in a PHP variable named as $folder. This can be seen in getuser.php code.
I want this variable to be visible/available in one.php so that my images using this variable could be populated. How would i do this. I have tried including php as well but no use.



getuser.php

   <?php
$q=$_GET["q"];

$con = mysql_connect('localhost', 'san', '123');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("holidayNet", $con);

$sql="SELECT * FROM image WHERE id = '".$q."'";

$result = mysql_query($sql);

echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Picture</th>
</tr>";

while($row = mysql_fetch_array($result))
  {
    $folder = $row['FirstName'];
  echo "<tr>";
 echo "<td>" . $row['FirstName'] . "</td>";
  echo "<td>" . $row['LastName'] . "</td>";
  echo "<td>" . $row['Age'] . "</td>";
  echo "<td>" . $row['Hometown'] . "</td>";


  /*echo "<td>" . $row['Job'] . "</td>";*/
  echo "</tr>";
  }
echo "</table>";

mysql_close($con);


?> 



one.php

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script type="text/javascript">
function showUser(str)
{
if (str=="")
  {
  document.getElementById("txtHint").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Sn Qb</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
</form>
<br />
<div id="txtHint"><b>Person info will be listed here.</b></div><br />

<img src="<?php echo $folder;?>/pic1.jpg" />
<img src="<?php echo $folder;?>/pic2.jpg" />
<img src="<?php echo $folder;?>/pic3.jpg" />
<img src="<?php echo $folder;?>/pic4.jpg" />


</body>
</html> 
hakre
  • 193,403
  • 52
  • 435
  • 836
Femme Fatale
  • 870
  • 7
  • 27
  • 56

3 Answers3

2

Hey you are creating a variable name $folder in the PHP file (getuser.php) which is getting called by AJAX. But its not available in the file name one.php.

Only what you echo from getuser.php will be available in the JS variable xmlhttp.responseText

So you will get all the Person Info echoed in the getuser.php, but wont get the $folder variable.

Since you have specifically hardcoded 4 images. I suggest you to echo the img tags too in the getuser.php along with the other information from the database of the person selected.

while($row = mysql_fetch_array($result))
{
    $folder = $row['FirstName'];
    echo "<tr>";
    echo "<td>" . $row['FirstName'] . "</td>";
    echo "<td>" . $row['LastName'] . "</td>";
    echo "<td>" . $row['Age'] . "</td>";
    echo "<td>" . $row['Hometown'] . "</td>";


    /*echo "<td>" . $row['Job'] . "</td>";*/
    echo "</tr>";
}
echo "</table>";

for($i = 0; $i < 4; $i++)
{
    echo '<img src="'.$folder.'/pic'.($i+1).'.jpg" />';
}

And remove those image tags from the one.php page

The other Solution: Suggestion which I can give is to add some separator to differentiate between the 2 things. One is the table which you want to print and the $folder variable value. For eg: consider separator ####

Step 1: So now your code from the getuser.php will be

while($row = mysql_fetch_array($result))
{
    $folder = $row['FirstName'];
    echo "<tr>";
    echo "<td>" . $row['FirstName'] . "</td>";
    echo "<td>" . $row['LastName'] . "</td>";
    echo "<td>" . $row['Age'] . "</td>";
    echo "<td>" . $row['Hometown'] . "</td>";


    /*echo "<td>" . $row['Job'] . "</td>";*/
    echo "</tr>";
}
echo "</table>####".$folder;

Step 2: Changes in the one.php to separate the 2 values

    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
// split is the function which breaks the string with the value provided and then creates an array of the parts.
        var arrResponse = (xmlhttp.responseText).split("####");
        // added || below to validate the index 1 of arrResponse. if xmlhttp.responseText does not have #### it wont break the string and hence wont have the folderName part, in such cases javascript will give undefined value, by adding || we tell if value is present take the present value otherwise take it as an empty string ''
    var folderName = arrResponse[1] || ''
        document.getElementById("txtHint").innerHTML=arrResponse[0];

        // we will fetch all the image tags from your html page
        var arrImgs = document.getElementsByTagName('img');
        var imgCount = arrImgs.length;
        for(i = 0; i < imgCount; i++)
        {
            arrImgs[i].setAttribute('src', folderName+'/pic'+(i+1)+'.jpg');
        }
    }
swapnilsarwe
  • 1,290
  • 1
  • 8
  • 13
  • ok, how would i get result from xmlhttp.responseText in AJAX. Code will be appreciated. – Femme Fatale May 05 '12 at 20:26
  • edited the solution, please check the other solution. – swapnilsarwe May 05 '12 at 20:34
  • Thanks sir ! is it possible that i get to print the values from table on my page by AJAX. (assuming that there is only one row). I am only interested in fetching the $folder value and placing it in the IMG tag like this rest of the values can be ignored. – Femme Fatale May 05 '12 at 20:52
  • @Namelus You are already printing the value of the table on your page using the AJAX. So no question of possibility. I apologize but possibly I am not getting your requirement. Requirement 1: you want to use AJAX Requirement 2: AJAX for printing the info from the DB table OR AJAX to get the value of the folder OR both of them. Please confirm. – swapnilsarwe May 05 '12 at 21:00
  • I want the $folder value in one.php. I want to display the images not the value of $folder. – Femme Fatale May 05 '12 at 21:11
  • simplified my getuser.php – Femme Fatale May 05 '12 at 21:11
  • @Namelus we are not displaying the value of the $folder, we are using its value for constructing the SRC of the IMG tag with it. hence when HTML finds the image tag it will fetch the image from the constructed value of SRC and display on HTML – swapnilsarwe May 05 '12 at 21:17
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/10921/discussion-between-swapnilsarwe-and-namelus) – swapnilsarwe May 05 '12 at 21:19
0

What you are doing wrong is that you are mixing things together, specially PHP and HTML, I can explain better if you would like, but for the moment I will only try to explain a solution to your problem, I hope this would be okay for you.

1/ the $folder will not be reachable from the one.php

2/ to get the information from the $folder you would better get it within the Ajax Query, and then you can use Javascript function to change the attribute

3/ another solution is, since you are generating the the html code for the table in the getuser.php, you can also generate some more lines with the images tages included

Did I explain well ? please if not, I'm ready to try again :)

Best of luck

Abu Romaïssae
  • 3,841
  • 5
  • 37
  • 59
  • Can you guide me with AJAX and JavaScript code. Moreover, i can't include tags in getuser.php as i am using one.php for interfacing. So i am bound to bring the variable result into one.php. Thanks – Femme Fatale May 05 '12 at 20:04
  • Yes, **Ajax** is also **JavaScript** well, I will try to write you a possible solution bellow – Abu Romaïssae May 05 '12 at 20:08
0

Upon your request, I will tell you a possible solution using the same way you did it before

first of all, you will need to change your both files

1/ go to getuser.php and remove all the echo, store the strings in a variable instead

2/ than, after the loop create an indexed array with your both variables ($folder and the new variable which contains the html string)

3/ after that you can encode the array in json format, with the "json_encode" function (available since PHP5)

4/ all what you still have to do, is in the one.php page, when getting the result you need to decode the string you get with the "eval" function (a native Javascript function), this function will return an indexed array (with the same indexs) and put the html string in the "txtHint" div, use the content of other variable in your images tags (using javascript functions)

was that clear enough to follow ? (sorry my english is not that good :( )

Abu Romaïssae
  • 3,841
  • 5
  • 37
  • 59
  • well i appreciate the effort, but using eval is not suggested and is considered to be evil. I will better suggest to add the folder name with some separator along with the HTML echoed. Then separate the HTML and the folderName in javascript. For eg: – swapnilsarwe May 05 '12 at 20:26
  • 1
    `var arrResponse = (xmlhttp.responseText).split("####"); document.getElementById("txtHint").innerHTML=arrResponse[0]; var folderName = arrResponse[1]; // we will fetch all the image tags from your html page var arrImgs = document.getElementsByTagName('img'); var imgCount = arrImgs.length; for(i = 0; i < imgCount; i++) { arrImgs[i].setAttribute('src', folderName+'/pic'+(i+1)+'.jpg'); }` – swapnilsarwe May 05 '12 at 20:28
  • yeah, thats absolution a way of doing things, but I don't understand why **eval** is not suggested or is considered to be evil, cuz I'm using it for more than 3 years now, and it never let me down !!! – Abu Romaïssae May 05 '12 at 20:30
  • please google the Pros and Cons of eval to learn more, its not evil until you fall for it. Precaution is always better than the cure. Go thru this link: [why-is-using-the-javascript-eval-function-a-bad-idea](http://stackoverflow.com/questions/86513/why-is-using-the-javascript-eval-function-a-bad-idea) – swapnilsarwe May 05 '12 at 20:37
  • ok, thanks for the information :) do you know if there is replacement ? I will search anyway :) – Abu Romaïssae May 05 '12 at 20:43
  • there are replacements but still even those are evil, my suggestion go through the jquery code [jquery cdn link](http://code.jquery.com/jquery-1.7.2.js) and check for the function named `parseJSON`. – swapnilsarwe May 05 '12 at 20:53
  • ok, thanks for the help :) that was nice to know thous precious information, but they say if the code isn't changed, and not user interacted, using the eval function is no harm, but still are existing other ways to hack javascript and include some evil in the eval function without permession :). Humm... I think the thread subject changed in those comments, so I must think **Namelus** for this occasion :) – Abu Romaïssae May 05 '12 at 20:57
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/10920/discussion-between-swapnilsarwe-and-madev) – swapnilsarwe May 05 '12 at 21:05