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"}]';
?>
Related
I'm a newbie on Ajax, I have tried the tutorial Book, but it did not work. The code is for searching.
This is the script search.htm
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>AJAX + MySQL I</title>
<script type="text/javascript" src="search.js"></script>
</head>
<body onload='process()'>
<h1>Student Search</h1>
<form name="form1">
Masukkan Nama Mahasiswa: <input type="text" id="namaMhs" />
</form>
<p><strong>Hasil Pencarian :</strong></p>
<div id="hasil" />
</body>
</html>
and the JS script search.js
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject()
{
var xmlHttp;
if(window.ActiveXObject)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
xmlHttp = false;
}
}
else
{
try
{
xmlHttp = new XMLHttpRequest();
}
catch (e)
{
xmlHttp = false;
}
}
if (!xmlHttp) alert("Obyek XMLHttpRequest tidak dapat dibuat");
else
return xmlHttp;
}
function process()
{
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
{
nama =
encodeURIComponent(document.getElementById("namaMhs").value);
xmlHttp.open("GET", "search.php?namaMhs=" + nama, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}
else
setTimeout('process()', 1000);
}
function handleServerResponse()
{
if (xmlHttp.readyState == 4)
{
if (xmlHttp.status == 200)
{
var xmlResponse = xmlHttp.responseXML;
xmlRoot = xmlResponse.documentElement;
nimArray = xmlRoot.getElementsByTagName("nim");
namaMhsArray = xmlRoot.getElementsByTagName("namamhs");
alamatArray = xmlRoot.getElementsByTagName("alamat");
if (nimArray.length == 0)
{
html = "Data tidak ditemukan";
}
else
{
// membentuk tabel untuk menampilkan hasil pencarian
html = "<table border='1'><tr><th>NIM</th><th>Nama
Mhs</th><th>Alamat</th></tr>";
for (var i=0; i<nimArray.length; i++)
{
html += "<tr><td>" + nimArray.item(i).firstChild.data +
"</td><td>" +
namaMhsArray.item(i).firstChild.data +
"</td><td>" +
alamatArray.item(i).firstChild.data +
"</td></tr>";
}
html = html + "</table>";
}
document.getElementById("hasil").innerHTML = html;
setTimeout('process()', 1000);
}
else
{
alert("Ada masalah dalam mengakses server: " +
xmlHttp.statusText);
}
}
}
and the last script in php search.php
<?php
header('Content-Type: text/xml');
echo '<hasil>';
$namaMhs = $_GET['namaMhs'];
mysql_connect("localhost","root","*******");
mysql_select_db("mahasiswa");
$query = "SELECT * FROM mhs WHERE namamhs LIKE '%$namaMhs%'";
$hasil = mysql_query($query);
while ($data = mysql_fetch_array($hasil))
{
echo "<mhs>";
echo "<nim>".$data['NIM']."</nim>";
echo "<namamhs>".$data['NAMAMHS']."</namamhs>";
echo "<alamat>".$data['ALAMAT']."</alamat>";
echo "</mhs>";
}
echo '</hasil>';
?>
Please help me to fix this script. The XML on search.php is already running but my searching is not. Any help is appreciated.
You are submitting the script on load, before there is even a value in the text field:
<body onload='process()'>
<h1>Student Search</h1>
<form name="form1">
Masukkan Nama Mahasiswa: <input type="text" id="namaMhs" />
</form>
You should either add a value to the text field as such:
<input type="text" value="testname" id="namaMhs" />
Or as a better option, add a submit button and don't run the function on load, but rather on submit:
<body>
<h1>Student Search</h1>
<form name="form1">
Masukkan Nama Mahasiswa: <input type="text" id="namaMhs" />
<input type="button" value="Search" onclick="process();" />
</form>
There may be more or even many more problems with your code, I am not looking through it all, but this should get you off to a good start.
I am trying to send ID and sent from ajax_form.php to ajax_test.php()
my ajax_form.php is:
<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();
e.returnValue=false;
var xmlhttp;
var submit = form.getElementsByClassName('submit')[0];
//var sent = document.getElementsByName('sent')[0].value || '';
//var id = document.getElementsByName('id')[0].value || '';
var sent = form.elements['sent'].value;
var id = form.elements['id'].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" />
<input type="" name="id" style="display: none"/>
</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:<input type="text" name="sent"></label><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
$s = $_POST['sent'];
echo "Entered sentence : $s";
if (isset($_POST['insert']) && $_POST['insert'] !== '') {
echo "Operation: Insert","<br>";
$s = $_POST['sent'];
$flag = 0;
echo "Entered sentence : $s";
//database stuff
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";
//database stuff
mysqli_close($con);
}
?></html > </body >
Neither content outside if() get executed correctly nor if
I get error:
Notice: Undefined index: sent in /opt/lampp/htdocs/test/ajax_test.php on line 6
Just Entered sentence : get printed.
Where is the problem in post? Ideally I should able fetch id and sent !
You need to set the Content-Type on the request before sending it to application/x-www-form-urlencoded. See documentation.
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>
I want to load data from MySql database to a HTTP form
When I type the in the text it should load the name of the person
<html>
<head>
<script type="text/javascript">
function FetchUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var data = JSON.parse(xmlhttp.responseText);
}
}
xmlhttp.open("GET","finduser.php?q="+str,true);
xmlhttp.send();
}
this.form.name.value=data.name;
this.form.age.value=data.age;
</script>
</head>
<body>
<form method="post" >
Id<input type="text" name="id" size="5" /> </br>
Name<input type="text" id="name" name="name" onclick="Fetchuser(this.form.id.value)" ></br>
Age<input type="text" id="age" name="" size="2" /></br>
</form>
</body>
</html>
The PHP code for that.
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'root', '125');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test", $con);
$sql="SELECT * FROM wow WHERE id = '".$q."'";
$resul = json_encode(mysql_query($sql));
echo $resul;
?>
My question is how can I get both, name and age, to the text boxes.
i tried this but still i cant load data
You can use json_encode to return a json with all your relevant fields, and in javascript put each field where it belongs.
$result = json_encode(mysql_query($sql));
echo $result; // don't forget to push the output or responseText is null.
And in the javascript:
var data = JSON.parse(xmlhttp.responseText);
Then you access your data with data.name_of_the_field
<?php
$rs=mysql_fetch_object($result );
$name=$rs->name;
$age=$rs->age;
?>
Name<input type="text" name="name" value="<?php echo $name;?>" />
Age<input type="text" name="" size="2" value="<?php echo $age;?>" />
put an id like <input id="name", <input id="age" in your text boxes, so you can assign them via the document.getElementById("name"), document.getElementById("age")
I want to set a group of post button that can send each value with ajax. How to modify the js part?
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="javascript">
function saveUserInfo()
{
var msg = document.getElementById("msg");
var f = document.user_info;
var userName = f.user_name.value;
var url = "value.php";
var postStr = "user_name="+ userName;
var ajax = false;
if(window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
if (ajax.overrideMimeType) {
ajax.overrideMimeType("text/xml");
}
}
else if (window.ActiveXObject) {
try {
ajax = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!ajax) {
window.alert("wrong");
return false;
}
ajax.open("POST", url, true);
ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
ajax.send(postStr);
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
msg.innerHTML = ajax.responseText;
}
}
}
</script>
</head>
<body >
<div id="msg"></div>
<form name="user_info" id="user_info" method="post">
<input name="user_name" type="hidden" value="abc" /><br />
<input type="button" value="abc" onClick="saveUserInfo()">
<input name="user_name1" type="hidden" value="def" /><br />
<input type="button" value="def" onClick="saveUserInfo()">
<input name="user_name2" type="hidden" value="ghi" /><br />
<input type="button" value="ghi" onClick="saveUserInfo()">
</form>
</body>
Try
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="javascript">
function saveUserInfo(custom_value)
{
var msg = document.getElementById("msg");
var f = document.user_info;
var userName = f.user_name.value;
var url = "value.php";
var postStr = "user_name="+ userName + "&custom_value=" + custom_value;
var ajax = false;
if(window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
if (ajax.overrideMimeType) {
ajax.overrideMimeType("text/xml");
}
}
else if (window.ActiveXObject) {
try {
ajax = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!ajax) {
window.alert("wrong");
return false;
}
ajax.open("POST", url, true);
ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
ajax.send(postStr);
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
msg.innerHTML = ajax.responseText;
}
}
}
</script>
</head>
<body >
<div id="msg"></div>
<form name="user_info" id="user_info" method="post">
<input name="user_name" type="hidden" value="abc" /><br />
<input type="button" value="abc" onClick="saveUserInfo('abc')">
<input name="user_name1" type="hidden" value="def" /><br />
<input type="button" value="def" onClick="saveUserInfo('def')">
<input name="user_name2" type="hidden" value="ghi" /><br />
<input type="button" value="ghi" onClick="saveUserInfo('ghi')">
</form>
</body>
What i have done is i have added a parameter to the saveUserInfo function and sent it with the post request.