<!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
?>
Related
how to work with php variable without jQuery?
My test.php file:
<?php
session_start();
$language = 'zzz';
?>
<!DOCTYPE html>
<html lang="en">
<body>
<button onclick = "setCookie()">test</button>
<p id="demo"></p>
<script>
function setCookie() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("POST", "setCookie.php", true);
xhttp.send();
}
</script>
<?php
echo 'session: ' . $_SESSION['xxx'];
?>
</body>
</html>
and my setCookie.php file is:
<?php
session_start();
$_SESSION['xxx'] = $language;
?>
If I put some simple echo statement in setCookie.php, it works and appears on my website. But why it can`t assign $language value to session['xxx']?
Beacuse ajax will be new request when its call so you have to pass value with it.
try this:
test.php
<?php
session_start();
$language = 'zzz';
?>
<!DOCTYPE html>
<html lang="en">
<body>
<button onclick = "setCookie()">test</button>
<p id="demo"></p>
<script>
function setCookie() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
language = '<?=$language?>'; //get value
xhttp.open("POST", "setCookie.php", true);
xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhttp.send("language=" + language); //send as post params
xhttp.send();
}
</script>
<?php
echo 'session: ' . $_SESSION['xxx'];
?>
</body>
</html>
setCookie.php
<?php
session_start();
$language = $_POST['language']; //retrive value
$_SESSION['xxx'] = $language; //assign to session
?>
Just Change your setCookie.php file like below.
<?php
session_start();
$_SESSION['xxx'] = $_POST['language'];
?>
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"}]';
?>
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
}
}
?>
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>        </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;
}
}
I am facing a small problem regarding this topic.I had write a code to autofill textboxes from database values when I type a id value in the previous textfield.i.e.if I type userid,the next textfields will autofill from database without refresh in ajax and php.my problem is that I cant find the error in my code.help me to find out.Here is my code:
**a.html**
<!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=iso-8859-1" />
<title>Untitled Document</title>
<script type="text/javascript">
var url = "getagentids.php?param=";
function handleHttpResponse() {
if (http.readyState == 4) {
results = http.responseText.split(",");
document.getElementById('agfn').value = results[0];
document.getElementById('agsal').value = results[1];
document.getElementById('agtel').value = results[2];
document.getElementById('agid').value = results[3];
}
}
function getagentids() {
var idValue = document.getElementById("agid").value;
var myRandom=parseInt(Math.random()*99999999); // cache buster
http.open("GET", url + escape(idValue) + "&rand=" + myRandom, true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
}
function getHTTPObject() {
var xmlhttp;
/*#cc_on
#if (#_jscript_version >= 5)
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
#else
xmlhttp = false;
#end #*/
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
var http = getHTTPObject(); // We create the HTTP Object
</script>
</head>
<body>
<form name="schform">
<table>
<tr>
<td>Contact ID:</td>
<td><input id="agid" type="text" name="contactid" onKeyUp="getagentids();"></td>
</tr><tr>
<td>Tel Number:</td> <td><input id="agtel" type="text" name="contacttel"></td>
</tr><tr>
<td>Name:</td> <td><input id="agfn" type="text" name="contactfullname"></td>
</tr><tr>
<td>Salutation:</td> <td><input id="agsal" type="text" name="contactsalutation"></td>
</tr>
<tr> <td><input type="reset" value="Clear"></td>
<td></td>
</tr>
</table>
</form>
</body>
</html>
**getagentids.php**
<?php
$link = mysql_connect('localhost', 'arbiocua_mita', 'asd123$');
if (!$link)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('arbiocua_monomita');
//$param=intval($_GET['contactid']);
if(strlen($param)>0)
{
$result = mysql_query("SELECT ContactFullName, ContactSalutation, ContactTel FROM contact WHERE ContactID LIKE '$param%'");
if(mysql_num_rows($result)==1)
{
while($myrow = mysql_fetch_array($result))
{
$agentname = $myrow["ContactFullName"];
$agenttel = $myrow["ContactTel"];
$agentsal = $myrow["ContactSalutation"];
$agentid = $myrow["ContactID"];
$textout = $agentname.",".$agentsal.",".$agenttel.",".$agentid;
} }
else { $textout=" , , ,".$param;
} }
echo $textout;
?>
**database**:
table name 'contact'
ContactID ContactFullName ContactSalutation ContactTel
$textout=json_encode($textout)
Then echo $textout