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.
Related
I am not sure what I am missing. Is there anything wrong with my syntax on the below? I am trying to request an answer using an HTML form and then check the answer against a value with a PHP script.
<!DOCTYPE html>
<html>
<head>
<title>Verify Identity</title>
</head>
<script>
function verify(e) {
if((e && e.keyCode == 13) || e == 0) {
document.forms.verifyForm.submit();
var golfer = document.getElementById("mgolf").value;
// window.alert("You answered: " + golfer);
//adding the ajax php call attempt 1
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("servRes").innterHTML = this.responseText;
}
};
xmlhttp.open("GET", "checkanswer.php?q=", true);
// xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
}
}
</script>
<body>
<h2>Welcome Ben</h2>
<div onKeyPress="return verify(event)">
<form id="verifyForm" onsubmit="return false;">
Question 1 text:</br> <input type="text" id="mgolf">
</form>
</div>
<div id="test">
<p id="servRes">replace</p>
</div>
</body>
</html>
And the PHP
<?php
//create correct answer for test question
$answer = "Ben";
$q = $_REQUEST["q"];
if($q == $answer) {
echo "correct answer";
} else {
echo "incorrect answer";
}
?>
It's not working, because you are calling .submit(); on form element, which in result refreshes a page and you don't see a result of XMLHttpRequest. Removing this line and fixing 'innterHTML' make your code working.
<!DOCTYPE html>
<html>
<head>
<title>Verify Identity</title>
</head>
<script>
function verify(e) {
if((e && e.keyCode == 13) || e == 0) {
// document.forms.verifyForm.submit();
var golfer = document.getElementById("mgolf").value;
// window.alert("You answered: " + golfer);
//adding the ajax php call attempt 1
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("servRes").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "checkanswer.php?q=", true);
// xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
}
}
</script>
<body>
<h2>Welcome Ben</h2>
<div onKeyPress="return verify(event)">
<form id="verifyForm" onsubmit="return false;">
Question 1 text:</br> <input type="text" id="mgolf">
</form>
</div>
<div id="test">
<p id="servRes">replace</p>
</div>
</body>
</html>
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 perform live search in php using ajax. This is my code for performing task
googleajax.php
<?php
$id=$_GET['id'];
if(isset($_POST['submit']))
{
$temp=$_POST['name'];echo $temp;
}
?>
<html>
<head>
<script language="javascript" type="text/javascript">
function getXMLHTTP() { //function to return the xml http object
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getValue(id)
{
var strURL="googledata.php?id="+id;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('div1').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
</head>
<body>
<form method="post">
<?php
/*$query="Select * from tblcountry where country_id='".$id."'";
echo $
$res=mysql_query($res);
while($row=mysql_fetch_assoc($res))
{
extract($row);*/
?>
<input type="text" id="name" name="name" onKeyUp="getValue(this.value)" value="<?php echo $id;?>" />
<input type="submit" id="submit" name="submit" value="serch">
<div id="div1" name="div1">
</div>
<?php
/*<!--}-->*/
?>
</form>
</body>
</html>
and googledata.php
<?php
$con=mysql_connect("localhost","root","");
if(!$con)
{
die("error in connection");
}
else
{
mysql_select_db("hms2012",$con);
}
$id= $_GET['id'];
if($id=="")
{
}
else
{
$result=mysql_query("select * from tblcountry where country_name like '$id%'");
while($row=mysql_fetch_assoc($result))
{
extract($row);
echo "<option value='$country_id'><a href='googleajax.php?id=$country_id'>".$country_name."</a><br></option>";
}
}
?>
Performing this code I can not select value for press key.
What was the use that I can select the value?
You have no <select></select> around your <options> tags list.
You should take a look on using jQuery for your Ajax stuff.
what is $country_id and $country_name. I have changed it by assumption. Please check.
echo '<select name="somename">';
while($row=mysql_fetch_assoc($result))
{
extract($row);
echo "<option value='".$row['country_id']."'><a href='googleajax.php?id=".$row['country_id']."'>".$row['country_name']."</a><br></option>";
}
echo "</select>";
I want to check if a user exists in DB, and if exist display some error without reload the page (modify a div). Any idea what is wrong in this code? Or any other idea how to do it? Thank you
HTML:
<div style="width:510px; height:500px;">
<div class="message">
<div id="alert"></div>
</div>
<form id="signup_form" method="post" action="register.php">
<label class="label">username</label>
<p><input class="signup_form" type="text" name="username"></p>
<label class="label">parola</label>
<p><input class="signup_form" type="text" name="password"></p>
<label class="label">name</label>
<p><input class="signup_form" type="text" name="name"></p>
<label class="label">telefon</label>
<p><input class="signup_form" type="text" name="phone"></p>
<label class="label">email</label>
<p><input class="signup_form" type="text" name="email"></p>
<p><input class="signup_button" type="submit" value="inregistrare">
</form>
<div class="clear"></div>
</div>
register.php
<?php
include "base.php";
$usertaken = '<li class="error">username used</li><br />';
$alert = '';
$pass = 0;
if(!empty($_POST['username']) && !empty($_POST['password']))
{
$username = mysql_real_escape_string($_POST['username']);
$password = md5(mysql_real_escape_string($_POST['password']));
$name = mysql_real_escape_string($_POST['username']);
$phone = mysql_real_escape_string($_POST['phone']);
$email = mysql_real_escape_string($_POST['email']);
$checkusername = mysql_query("SELECT * FROM details WHERE user = '".$username."'");
if(mysql_num_rows($checkusername) == 1)
{
$pass = 1;
$alert .="<li>" . $usertaken . "</li>";
}
else
{
$registerquery = mysql_query("INSERT INTO details (user, pass, name, phone, email) VALUES('".$username."', '".$password."','".$name."','".$phone."', '".$email."')");
if($registerquery)
{
echo "<h1>Success</h1>";
echo "<p>Your account was successfully created. Please click here to login.</p>";
}
else
{
echo "<h1>Error</h1>";
echo "<p>Sorry, your registration failed. Please go back and try again.</p>";
}
}
if($pass == 1) {
echo '<script>$(".message").hide("").show(""); </script>';
echo "<ul>";
echo $alert;
echo "</ul>";
}
}
?>
SOLUTION (add this in head and hide .message div)
<script type="text/javascript" src="jquery-latest.pack.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var options = {
target: '#alert',
beforeSubmit: showRequest,
success: showResponse
};
$('#signup_form').ajaxForm(options);
});
function showRequest(formData, jqForm, options) {
var queryString = $.param(formData);
return true;
}
function showResponse(responseText, statusText) {
}
$.fn.clearForm = function() {
return this.each(function() {
var type = this.type, tag = this.tagName.toLowerCase();
if (tag == 'form')
return $(':input',this).clearForm();
if (type == 'text' || type == 'password' || tag == 'textarea')
this.value = '';
else if (type == 'checkbox' || type == 'radio')
this.checked = false;
else if (tag == 'select')
this.selectedIndex = -1;
});
};
</script>
You need to use AJAX to do a dynamic page update.
Take a look here: http://api.jquery.com/jQuery.ajax/ for how to do it with jQuery.
Your current code uses a form submit, which always reloads the page.
You need to use ajax. Write something like this as a JavaScript:
var xmlHttp;
function checkUser(user) {
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null) {
alert ("Browser does not support HTTP Request.");
return;
}
var url = "check.php"; //This is where your dynamic PHP file goes
url = url + "?u=" + user;
url = url + "&sid=" + Math.random();
xmlHttp.onreadystatechange = getData;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function getData () {
if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
if (xmlHttp.responseText == 1) {
alert('Username free'); //action if username free
} else {
alert('This username is taken'); //action if its not
}
}
}
function GetXmlHttpObject() {
var xmlHttp=null;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
} catch (e) {
//Internet Explorer
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
And in your check.php file, just check against your database if the username is taken or not, if not and simply echo('1') if its free, else echo('0') o whatever you want. that single number will be handled as the xmlHttp.responseText. you can also do something fancy instead of the alerts, like an image. also you need to run the check() fumction either when the user is typing, or when the form is submitted, with the username form field as a parameter. Hope this helps.
EDIT: Oh, also I forgot that in the check.php file, the $_GET['u'] variable contains the the entered username. Check that against the database.
If that's all in a single page, you'll have to structure it like this:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... do form retrieval/database stuff here ...
if (error) {
$message = 'Something dun gone boom';
}
}
if ($message != '') {
echo $message;
}
?>
form stuff goes here
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.