Why image does not display only characters appears - php

I can record and display images from the database. However I'm trying to do a search through a dropdown, and then show images, but only appears characters.
Could you possibly help me saying where I am failing please?
I apologize for the inconvenience.
Thank you all very much.
TEST.PHP
<?php
mysql_connect("localhost","root","****");
mysql_select_db("Database");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script>
function showdetails(str)
{
var xmlhttp;
if (str==0)
{
alert("Please select an Id");
}
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("showresult").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test2.php?id="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
Image id:<select name="id" id="id" onchange="showdetails(this.value)">
<option value="0">Select Image id</option>
<?php
$sql="select idImage from images";
$qry=mysql_query($sql);
$num=mysql_num_rows($qry);
if($num>0)
{
while($res=mysql_fetch_array($qry))
{
?>
<option value="<?php echo $res['idImage'];?>"><?php echo $res["idImage"];?></option>
<?php
}
}
?>
</select>
<div id="showresult" align="justify"></div>
</body>
</html>
TEST2.PHP
<?php
mysql_connect("localhost","root","***");
mysql_select_db("Database");
$id = $_REQUEST["id"];
$sql="select * from images where idImage='$id'";
$qry=mysql_query($sql);
$num=mysql_num_rows($qry);
if($num>0)
{
while($res=mysql_fetch_array($qry))
{
$image = $res['image'];
header("Content-type:image/jpeg");
echo $image;
}
}
?>
But if I do a search in database with a specific id, the image shows on screen.
I can't understand where i'm failling.
I tried encode and decode 64 bur the result is the same.
mysql_connect("localhost","root","***");
mysql_select_db("database");
$sql="select * from images where idImage='201400040'";
$qry=mysql_query($sql);
$num=mysql_num_rows($qry);
if($num>0)
{
while($res=mysql_fetch_array($qry))
{
$image = $res['image'];
header("Content-type:image/jpeg");
echo $image;
}
}
?>

You need to replace this
<div id="showresult" align="justify"></div>
with this
<img id="showresult" align="justify" SRC='emptyimage.jpg'/>
and change showdetails function to
function showdetails(str){
document.getElementById('showresult').src = "test2.php?id="+str;
}
I am not tested this code but should work.

You need to tell the browser it's an image. We use the <img> tag for that.
The image tag also needs a source. In your case. It's data:
<img src="data:$ActualData" />
$actualData should be replaced with that string. In your code that would be:
<div id="showresult" align="justify">
<img id="my-image" src="" />
</div>
and then your javascript would change the src:
document.getElementById("my-image").src = 'data:'+xmlhttp.responseText;
wrong solution
I think however this is the wrong solution. At this moment you are handling all the fetching of the image. something the browser can do for you... So let it handle all that.
Simply change the src of the image. and the browser will do the rest.
function showdetails(str) {
var xmlhttp;
if (str==0) {
alert("Please select an Id");
}
document.getElementById("my-image").src = 'test2.php?id='+str;
}

try this just add one column before your idImage(dont forget)
just copy this and paste this...
TEST.php
<?php
mysql_connect("localhost","root","");
mysql_select_db("Database");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script>
function showdetails(str)
{
var xmlhttp;
if (str==0)
{
alert("please select an Id");
}
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("showresult").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","details.php?id="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
Hero Name:<select name="id" id="id" onchange="showdetails(this.value)">
<option value="0">Select Hero Name</option>
<?php
$sql="select id,name from images";
$qry=mysql_query($sql);
$num=mysql_num_rows($qry);
if($num>0)
{
while($res=mysql_fetch_array($qry))
{
?>
<option value="<?php echo $res['id'];?>"><?php echo $res["name"];?></option>
<?php
}
}
?>
</select>
<div id="showresult" align="justify"></div>
</body>
</html>
and in TEST2.php like this
<?php
mysql_connect("localhost","root","");
mysql_select_db("Database");
$id = $_REQUEST["id"];
$sql="select * from images where id='$id'";
$qry=mysql_query($sql);
$num=mysql_num_rows($qry);
if($num>0)
{
while($res=mysql_fetch_array($qry))
{
?>
<img src="foldername/<?php echo $res['photo'];?>" height="300" width="300"/>
<?php
}
}
?>

Related

PHP setting JSON values to Textboxes

This is the html file.
<html>
<head>
<script>
function showUser(str) {
if (str == "") {
return;
} else {
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)
{
var doc = window.document.createElement("doc");
var a = JSON.parse(xmlhttp.responseText);
document.getElementById("stuname").value=a.first;
document.getElementById("branch").value=a.second;
document.getElementById("year").value=a.third;
document.getElementById("category").value=a.four;
}
}
xmlhttp.open("GET","test2.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form>
Roll Number:<br>
<input type="text" name="rollno" id="rollno" onblur="showUser(this.value)">
<br>
Student Name:<br>
<input type="text" name="stuname" id="stuname" value="">
Branch:<br>
<input type="text" name="branch" id="branch" value="">
Year:<br>
<input type="text" name="year" id="year" value="">
Category:<br>
<input type="text" name="category" id="category" value="">
</form>
<br>
</body>
</html>
test2.php file
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
$q = $_GET['q'];
$con=mysqli_connect("localhost","root","neel","sitams");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT rollno,stuname,branch,category FROM studet where rollno='".$q."' and academic='2014-2015'";
if ($result=mysqli_query($con,$sql))
{
while ($obj=mysqli_fetch_object($result))
{
$queryResult[] = $obj->rollno;
$queryResult[] = $obj->stuname;
$queryResult[] = $obj->branch;
$queryResult[] = $obj->category;
}
}
$textboxValue1 = $queryResult[0];
$textboxValue2 = $queryResult[1];
$textboxValue3 = $queryResult[2];
$textboxValue4 = $queryResult[3];
echo json_encode(array('first'=>$textboxValue1,'second'=>$textboxValue2,'third'=>$textboxValue3,'four'=>$textboxValue4));
?>
</body>
</html>
I could not able to load values to the text boxes where is fault. Even I have seen stackoverflow but I could not able to get it. when I type test2.php by passing rollno value to q it will display data but when I pass a value from html it could not able to set the values to the textbox fields.
Remove any html tags from test2.php . An ajax document does not need any html tags.
Hi this one will be helpful to you .
<html>
<head>
</head>
<body>
<input type="button" onclick="showUser('ok');" value="click to ru me" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function showUser(str)
{
if (str=="")
{
return;
}
else
{
if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); }
else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
//var doc = window.document.createElement("doc");
var parsed = JSON.parse(xmlhttp.responseText);
for(var x in parsed)
{
var First=parsed[x].first;
var Second=parsed[x].second;
var Third=parsed[x].third;
var Fourth=parsed[x].fourth;
console.log("first="+First+" second="+Second+" third="+Third+" fourth="+Fourth);
document.getElementById("stuname").value=parsed[x].first;
document.getElementById("branch").value=parsed[x].second;
document.getElementById("year").value=parsed[x].third;
document.getElementById("category").value=parsed[x].fourth;
}
}
}
xmlhttp.open("GET","phpex.php?q="+str,true);
xmlhttp.send();
}
}
</script>
<input type="text" id="stuname" />
<input type="text" id="branch" />
<input type="text" id="year" />
<input type="text" id="category" />
</body>
</html>
Ajax File Name phpex.php . ajax page code is below
<?php
echo '[{"first":"1111","second":"2222","third":"3333","fourth":"4444"}]';
?>

xmlhttp and PHP not working?

So I've been learning to use xmlhttp and I couldn't get this simple script working:
<!DOCTYPE html>
<html>
<head>
<script>
function print_stuff(){
document.getElementById("two").innerHTML="working";
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("one").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","index.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("email=" + document.getElementByName("email").value + "&name="+ document.getElementByName("name").value);
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
Name: <input type="text" name="name"/></br>
Email:<input type="text" name="email"/></br>
<button onclick="print_stuff()">Button</button></br>
<span id="one"></span>
<div id="two"></div>
</body>
</html>
And the index.php:
<?php
$name = $_POST["name"];
$email = $_POST["email"];
echo "Name: ",$name,"</br> Email: ", $email;
?>
The idea behind this is very simple: you get user's name and email and print it out using "POST" method. I have a sense it's a very simple mistake, though I can't find it... Any help appreciated!
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
Name: <input type="text" name="name" id="name"/></br>
Email:<input type="text" name="email" id="email"/></br>
<button onclick="print_stuff()">Button</button></br>
<span id="one"></span>
<div id="two"></div>
</body>
</html>
<script>
function print_stuff(){
var email = document.getElementById("email").value;
var name = document.getElementById("name").value;
if (window.XMLHttpRequest)
{
var xmlhttp=new XMLHttpRequest();
}
else
{
var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
array = new Array(4);
array = xmlhttp.responseText.split("##"); //slicing string into array to get separate result
document.getElementById("one").innerHTML = array.slice(0,1);
document.getElementById("two").innerHTML = array.slice(1,2);
}
}
xmlhttp.open("GET","index.php?email="+email+"&name="+name,true);
xmlhttp.send();
}
</script>
index.php:
<?php
$name = "Name: ".$_GET["name"];
$email = "Email: ".$_GET["email"];
echo $name."##".$email;
?>

Go automatically to another page using html

I have two pages, a html that send value to a php page, and than, the php page returns the result in a div, in the html page.
In the first test it has only a message with error, and in the else clause it must redirect to another html page, so the script in the php page will be shown in html. I've used javascript but it doesn't do it for me.
This is all the codes that i've used:
if (mysqli_num_rows($result)==0)
{
echo" Code erroné ";
}
else
{
header('location:infosInt.html');
//echo "<script> window.open('infosInt.html')</script>";
//echo "<script> window.location = 'infosInt.html'</script>";
}
EDIT
my html page :
<!DOCTYPE html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script src="jquery-ui.js" charset="ISO-8859-1"></script>
<script src="jquery-1.9.1.js" charset="ISO-8859-1"></script>
<script type="text/javascript" src="jquery.crypt.js" ></script>
<LINK rel="stylesheet" type="text/css" href="android.css">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Login Form</title>
<script>
function connexion(evt)
{
var x=document.getElementById('code');
var cde = x.value;
var str = $().crypt({
method: "md5",
source: cde
});
if (cde=="")
{
// 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;
}
}
var url ="http://localhost/filename/page.php";
var params="q="+ str;
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
};
</script>
</head>
<body>
<div class="login">
<p></p>
<form method="" action="" id= "codeform" onsubmit="connexion();return false;">
<p> &nbsp &nbsp &nbsp &nbsp</p>
<input type="password" id="code" ></p>
<p class="submit"><input type="submit" id="connect" value="Connexion" ></p>
</form>
<div id ="txtHint"></div>
</div>
</body>
</html>
and this is page.php:
<?php
$host = "localhost";
$port = port;
$socket = "";
$user = "root";
$password = "";
$dbname = "base";
$con = new mysqli($host, $user, $password, $dbname, $port, $socket);
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
$q =$con->real_escape_string($_POST['q']);
mysqli_select_db($con,"ajax_demo");
$sql="query where column ='".$q."'"; // ex
$result = mysqli_query($con,$sql);
if (mysqli_num_rows($result)==0)
{
echo" Code erroné ";
}
else
{
echo"<head><meta http-equiv='refresh' content='5; URL=infosInt.html'></head>";}
mysqli_close($con);
?>
The thing is, you are calling your php script with ajax, so you can't use header('Location: ...') or an html redirection. You should return a flag in your php script and test it when you get the response with javascript :
PHP (at the end of page.php):
if (mysqli_num_rows($result)==0)
{
echo "Code erroné";
}
else
{
echo "redirect"; // the flag
}
Javascript (on the xmlhttp.onreadystatechange event) :
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
if (xmlhttp.responseText == 'redirect') { // if flag is sent we redirect
document.location.href = 'infosInt.html';
} else {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}

Showing ajax content in same page without page load

My ajax_form.php page is:
<html><head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<script>
function showUser(form, e) {
e.preventDefault();
var xmlhttp;
var submit = form.getElementsByClassName('submit')[0];
var sent = document.getElementsByName('sent')[0].value || '';
var id = document.getElementsByName('id')[0].value || '';
if (sent==""){
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(e) {
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open(form.method, form.action, true);
xmlhttp.send('sent='+sent+'&id='+id+'&'+submit.name+'='+submit.value);
}
</script>
<form action="ajax_test.php" method="POST">
Enter the sentence: <input type="text" name="sent"><br>
<input type="submit" class="submit" name="insert" value="submit" onsubmit="showUser(this, event)">
</form>
<br>UPDATE <br>
<form action="ajax_test.php" method="POST" onsubmit="showUser(this, event)">
<pre>
Enter the ID : <input type="text" name="id"><br>
Enter the sentence: <input type="text" name="sent"><br>
</pre>
<input type="submit" class="submit" value="submit" name="update" >
</form> <br>
<div id="txtHint">
<b>Person info will be listed here.</b>
</div>
</body>
</html>
and ajax_test.php is:
<html><head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
</head> <body >
<?php
// $q = $_POST["q"];
// you never process the $q var so i commented it
if (isset($_POST['insert']) && $_POST['insert'] !== '') {
echo "Operation: Insert","<br>";
$s = $_POST['sent'];
$flag = 0;
echo "Entered sentence : $s";
if (preg_match_all('/[^=]*=([^;#]*)/',
shell_exec("/home/technoworld/Videos/LinSocket/client '$s'"),
$matches)){ //Values stored in ma.
$x = (int) $matches[1][0]; //optionally cast to int
$y = (int) $matches[1][1];
}
echo "<br>",
"Positive count :$x",
"<br>",
"Negative count :$y",
"<br>";
//---------------DB stuff --------------------
$con = mysqli_connect('127.0.0.1:3306', 'root', 'root', 'test');
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql1 = "INSERT INTO table2
(id,sent,pcount,ncount,flag)
VALUES
('','".$_POST['sent']."',' $x ','$y','$flag')";
if (mysqli_query($con, $sql1)) {
echo "1 record added";
} else {
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
}
// -------------------------------UPDATE --------------------------
if (isset($_POST['update']) && $_POST['update'] !== '') {
echo "Operation: update", "<br>";
// you say update but you are actually inserting below
$s = $_POST['sent'];
$flag = 1;
echo "Entered sentence : $s";
if (preg_match_all('/[^=]*=([^;#]*)/',
shell_exec("/home/technoworld/Videos/LinSocket/client '$s'"),
$matches)) //Values stored in ma.
{
$x = (int) $matches[1][0]; //optionally cast to int
$y = (int) $matches[1][1];
}
echo "<br>",
"Positive count :$x",
"<br>",
"Negative count :$y",
"<br>";
//---------------DB stuff --------------------
$con = mysqli_connect('127.0.0.1:3306', 'root', 'root', 'test');
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql1 = "INSERT INTO table2
(id,sent,pcount,ncount,flag)
VALUES
('','".$_POST['sent']."',' $x ','$y','$flag')"; // error here again $_POST[id] should be $_POST['id'] with quotes
if (mysqli_query($con, $sql1)) {
echo "1 record added";
} else {
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
}
?></html > </body >
In form1 I have put function call on button click event, which works fine. But on button click it load the page and redirects to ajax_test.php. can we say it proper use of ajax?
In second form I have kept function call in form itself and coded as required in script. But on button click on action takes place. Is it wrong function call or any other mistake?
How can I show result without page load(refresh) in both cases?
The problem is with your sent parameter - it's looking for an input named "sent", which doesn't exist. And then, if it's not set, it's exiting the showUser function.
Here's the offending snippet (which I removed below):
if (sent==""){
document.getElementById("txtHint").innerHTML="";
return;
}
In addition to that problem, you also had no close </head> or open <body> tags, which in themselves are not the problem, but a pretty major formatting issue. Also, always put a type on your <script> element. Finally, you should close <meta />, <input /> and <br /> elements inline. Formatting your code consistently (sibling elements on their own lines, 4-space tabs for each heirarchical level) helps you find little formatting issues like the missing open body, etc.
That said, this works for me:
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type" />
<meta content="utf-8" http-equiv="encoding" />
<script type="text/javascript">
function showUser(form, e) {
e.preventDefault();
var xmlhttp;
var submit = form.getElementsByClassName('submit')[0];
var sent = document.getElementsByName('sent')[0].value || '';
var id = document.getElementsByName('id')[0].value || '';
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(e) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open(form.method, form.action, true);
xmlhttp.send('sent=' + sent + '&id=' + id + '&' + submit.name + '=' + submit.value);
}
</script>
</head>
<body>
<form action="ajax_test.php" method="POST" onsubmit="showUser(this, event)">
<label>Enter the sentence: <input type="text" name="sent"></label><br />
<input type="submit" class="submit" name="insert" value="submit" onsubmit="showUser(this, event)" />
</form>
<h4>UPDATE</h4>
<form action="ajax_test.php" method="POST" onsubmit="showUser(this, event)">
<pre>
<label>Enter the ID:</label>
<input type="text" name="id"><br>
<label>Enter the sentence:</label>
<input type="text" name="sent"><br>
</pre>
<input type="submit" class="submit" value="submit" name="update" />
</form>
<br />
<div id="txtHint">
<b>Person info will be listed here.</b>
</div>
</body>
</html>

How to send variable to php with ajax?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script type="text/javascript">
function load(thediv, thefile)
{
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP)');
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById(thediv) .innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', thefile, true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
//connection to db and mysql query
$result = mysql_query($query) or die(mysql_error());
$options="";
while ($row=mysql_fetch_array($result)) {
$id=$row["idProducts"];
$thing=$row["country"];
$options.="<OPTION VALUE=\"$id\">".$thing.'</option>';
}
mysql_close();
?>
<SELECT id="countrySearch" NAME=countrySearch onchange="load('divtest', 'step2.search.php')";>
<OPTION VALUE=0>Choose
<?=$options?>
</SELECT>
<div id="divtest">
test
</div>
</body>
step2.search.php consists of:
<?php
echo "I want it to store the users selection as a variable for php to use";
?>
The problem I have is I want to store what the user selects from the drop down box and use it in php to do a mysql query using the variable from the user select form to form the WHERE part of the mysql statement. Then use ajax to put new data in "divtest".
How can I store the user selection into a variable then send it to be used in step2.search.php?
See Code Below
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script type="text/javascript">
function load(thediv, thefile,selectvalue)
{
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP)');
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById(thediv) .innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET",thefile+"?q="+selectvalue,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<?php
//connection to db and mysql query
$result = mysql_query($query) or die(mysql_error());
$options="";
while ($row=mysql_fetch_array($result)) {
$id=$row["idProducts"];
$thing=$row["country"];
$options.="<OPTION VALUE=\"$id\">".$thing.'</option>';
}
mysql_close();
?>
<SELECT id="countrySearch" NAME=countrySearch onchange="load('divtest', 'step2.search.php', this.value)";>
<OPTION VALUE=0>Choose
<?=$options?>
</SELECT>
<div id="divtest">
test
</div>
</form>
step2.search.php
<?php
Simple grab this variable
$id = $_GET['q'];
//do your query stuffhere
?>

Categories