Onchange() for AJAX - ajax

I am trying to display the onchange value of a textbox using ajax. My code is as follows :
ajaxquery.php
<html>
<head>
<title>Changing textbox value based on dropdown list using Ajax and PHP</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script>
//fuction to return the xml http object
function getXMLHTTP() {
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getCurrencyCode(strURL)
{
var req = getXMLHTTP();
if (req)
{
//function to be called when state is changed
req.onreadystatechange = function()
{
//when state is completed i.e 4
if (req.readyState == 4)
{
// only if http status is "OK"
if (req.status == 200)
{
document.getElementById('cur_code').value=req.responseText;
}
else
{
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
<body style="font: 12px Verdana, Arial, Helvetica, sans-serif;">
<form style="text-align:center" method="post" action="" name="form1">
<p>Country : <input type="text" name="country" onChange="getCurrencyCode('code.php?country='+this.value)">
</form>
</body>
</html>
code.php
<?php
$country=$_REQUEST['country'];
echo $country;
?>
The value is not displaying. Where am I going wrong?
P.s. I am completely new to ajax and have no knowledge about it. Appreciate any help :)

<p>Country : <input type="text" name="country" onblur="getCurrencyCode('code.php?country='+this.value)">
<p>Country Code : <input type="text" name="cur_code" id='cur_code' ">
Changed the onchange function to onblur and added another input type. It is working perfectly now!

Related

Dropdown using Ajax

I wrote the below code; when I select India/America in the dropdown related text files with some contents, has to be read and displayed inside a div element, but am getting an error in the line xhr.send()
can anyone explain why??
<html>
<head>
<script>
function getcity()
{
var a=document.getElementById("country");
var b=a[a.selectedIndex].value;
alert(b);
var xhr=new XMLHttpRequest();
if(b=="India")
{
xhr.onreadystatechange=function()
{
if((xhr.readystate==4)&&(xhr.status==200||xhr.status==304))
{
document.getElementByID("display").innerHTML=xhr.responseText;
}
}
xhr.open("GET","india.txt",true);
}
else
{
xhr.onreadystatechange=function()
{
if((xhr.readystate==4)&&(xhr.status==200||xhr.status==304))
{
document.getElementByID("display").innerHTML=xhr.responseText;
}
}
xhr.open("GET","america.txt",true);
}
xhr.send(null);
}
</script>
</head>
<body>
<select id="country" onchange="getcity()">
<option>India</option>
<option>America</option>
</select>
<div id="display"></div>
</body>
</html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function getcity()
{
var a=document.getElementById("country");
var b=a[a.selectedIndex].value;
alert(b);
var xhr=new XMLHttpRequest();
if(b=="India")
{
xhr.onreadystatechange=function()
{
if((xhr.readystate==4)&&(xhr.status==200||xhr.status==304))
{
document.getElementByID("display").innerHTML=xhr.responseText;
}
}
xhr.open("GET","india.txt",true);
}
else
{
xhr.onreadystatechange=function()
{
if((xhr.readystate==4)&&(xhr.status==200||xhr.status==304))
{
document.getElementByID("display").innerHTML=xhr.responseText;
}
}
xhr.open("GET","america.txt",true);
}
xhr.send(null);
}
</script>
</head>
<body>
<select id="country" onchange="getcity()">
<option>India</option>
<option>America</option>
</select>
<div id="display"></div>
</body>
</html>

Ajax ready state not stuck on 1

after searching the internet I was unable to find an answer as to why my AJAX code is not working. My assignment is to retrieve a text file and display it to the browser using AJAX but the ready state stops at 1. an example file is canada.txt and is located in the directory http://157.201.194.254/~ercanbracks. The .html and .js files are below:
HTML file:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>AJAX</title>
<link rel="stylesheet" type="text/css" href="assign09.css" />
<script type="text/javascript" src="assign09.js"></script>
</head>
<body>
<h1>Ten Largest Cities</h1>
<h3>Select a Country:</h3>
<form action="">
<select id="country">
<option value="canada">Canada</option>
<option value="mexico">Mexico</option>
<option value="russia">Russia</option>
<option value="usa">USA</option>
</select>
<input type="submit" value="Submit"
onclick="makeRequest(document.getElementById('country').value)" />
<div id="error"> </div>
</form>
<h3>Cities:</h3>
<div id="cities">
<pre>
City Population
------------------ ---------------
<span id="cityList"></span>
</pre>
</div>
</body>
</html>
.js file:
var httpRequest;
var countryOption;
function makeRequest(option)
{
countryOption = option;
if (window.XMLHttpRequest) // Modern Browsers
{
httpRequest = new XMLHttpRequest();
}
else // older IE browsers
{
try
{
httpRequest = new ActiveXObject("Msxm12.XMLHTTP");
}
catch (e)
{
try
{
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert('ERROR - Unable to make XMLHttpRequest');
}
}
}
if (!httpRequest)
{
alert('ERROR: httpRequest failed -- try a different browser');
return false;
}
else
{
var url = "http://157.201.194.254/~ercanbracks/" + option + ".txt";
alert('Ready State = ' + httpRequest.readyState);
httpRequest.onreadystatechange = getCities;
httpRequest.open("GET", url, true)
httpRequest.send(null);
}
}
function getCities()
{
alert('Ready State = ' + httpRequest.readyState);
if (httpRequest.readyState == 4)
{
alert('Ready State = ' + httpRequest.readyState);
if (httpRequest.status == 200)
{
var response = httpRequest.responseText;
document.getElementById("cities").innerHTML = response;
}
else
{
alert('problem with request');
alert('Ready State = ' + httpRequest.statusText);
}
}
}

AJAX can't connect with sql database

I try to create a form that will check if the user exist in database but i'm having problem connecting AJAX with sql, if you can help me finding out this problem i would be very appreciated, sorry my english is not great. these are my code:
<!DOCTTYPE html>
<html lang="en">
<head>
<mete charset="UTF-8">
<title>Email client</title>
<script type="text/javascript">
function load(){
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200 ){
document.getElementById('info').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'checkuser.php', true);
xmlhttp.send();
}
</script>
</head>
<body>
<form name="loginform" onclick="load();">
Username : <input name="userID" type="text" id="userID"><br />
Password : <input name="password" type="password" id="passWD"><br />
<input type="submit" id="button" value="Get in there"> <br />
<p>Don't have an account? please register </p>
</form>
<div id="info"></div>
</body>
</html>
my php (checkuser.php):
<?php
$dbhost = 'localhost';
$dbuser = 'xxxx';
$dbpass = 'xxxx';
$dbname = 'xxxx';
$dbtable = 'xxxx';
$q=$_GET["userID"];
$p=$_GET["passWD"];
$con = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$dbselect = mysql_select_db($dbname,$con);
$sql="SELECT * FROM $dbtable WHERE userID='$q'";
$result = mysql_query($sql);
if (mysql_num_rows($result)==0) {
echo "not registered";
} else {
while($row = mysql_fetch_array($result))
{
if (($row['passWD'])==$p) {
echo "registered";
} else { echo "not registered";}
}
}
mysql_close($con);
?>
Your PHP expects to have two query string parameters passed to it (don't send passwords in query strings, they might get logged, use a POST request) but your JavaScript is just requesting the URL of the script without any query string at all.
Presumably you want to extend load to get data from the form, and to call load in the submit event for the form and not the load event of the document.

ajax json form submit

I have this code for form submit:
index.php
<html>
<head>
<title>My Form</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#myForm").submit(function(){
var tvyalner = $("#myForm").serialize();
$.ajax({
type: "POST",
url: "postForm.ajax.php",
data: tvyalner,
dataType: "json",
success: function(data){
$("#formResponse").removeClass('error');
$("#formResponse").addClass(data.status);
$("#formResponse").html(data.message);
if(data.status === 'success'){$("#myForm table").hide();}
},
error: function(){
$("#formResponse").removeClass('success');
$("#formResponse").addClass('error');
$("#formResponse").html("There was an error submitting the form. Please try again.");
}
});
//make sure the form doens't post
return false;
});
});
</script>
<style type="text/css">
.success{
border: 2px solid #009400;
background: #B3FFB3;
color: #555;
font-weight: bold;
}
.error{
border: 2px solid #DE001A;
background: #FFA8B3;
color: #000;
font-weight: bold;
}
</style>
</head>
<body>
<div class="mfm">
<form id="myForm" name="myForm" method="post" action="" style="margin: 0 auto; width: 300px;">
<div id="formResponse"></div>
<table>
<tr><td>Name:</td><td><input name="name" type="text" value=""></td></tr>
<tr><td>Email:</td><td><input name="email" type="text" value=""></td></tr>
<tr><td>Message:</td><td><textarea name="message" rows="5" cols="20"></textarea></td></tr>
<tr><td> </td><td><input type="submit" name="submitForm" value="Submit Form"></td></tr>
</table>
</form>
</div>
</body>
</html>
postForm.ajax.php
<?php
//function to validate the email address
//returns false if email is invalid
function checkEmail($email){
if(eregi("^[a-zA-Z0-9_]+#[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$]", $email)){
return FALSE;
}
list($Username, $Domain) = split("#",$email);
if(#getmxrr($Domain, $MXHost)){
return TRUE;
} else {
if(#fsockopen($Domain, 25, $errno, $errstr, 30)){
return TRUE;
} else {
return FALSE;
}
}
}
//response array with status code and message
$response_array = array();
//validate the post form
//check the name field
if(empty($_POST['name'])){
//set the response
$response_array['status'] = 'error';
$response_array['message'] = 'Name is blank';
//check the email field
} elseif(!checkEmail($_POST['email'])) {
//set the response
$response_array['status'] = 'error';
$response_array['message'] = 'Email is blank or invalid';
//check the message field
} elseif(empty($_POST['message'])) {
//set the response
$response_array['status'] = 'error';
$response_array['message'] = 'Message is blank';
//form validated. send email
} else {
//send the email
$body = $_POST['name'] . " sent you a message\n";
$body .= "Details:\n\n" . $_POST['message'];
mail($_POST['email'], "SUBJECT LINE", $body);
//set the response
$response_array['status'] = 'success';
$response_array['message'] = 'Email sent!';
}
echo json_encode($response_array);
?>
After first submit displaying:
Name is blank.
Filling field and submitting again. displaying
There was an error submitting the form. Please try again.
and that's all.
Code not working in localhost.
What is the problem?
I suggest using this error-function to see what the error is:
$.ajax({
/* ... */
error: function(jqXHR, textStatus, errorThrown){
console.log(errorThrown); // Or use alert()
console.log(textStatus);
$("#formResponse").removeClass('success');
$("#formResponse").addClass('error');
$("#formResponse").html("There was an error submitting the form. Please try again.");
}
});

Username availability checking using Ajax in JSP and stopping form submission

I am new to ajax and I am trying to create a gmail type username availability check by using Ajax and JavaScript in JSP.
My code works well for username availability check but I am not able to stop the form submission when a username is not available.
For checking username availability I used onkeyup() which checks each character, but for preventing the form submission I used onsubmit() in form tag.
For execution flow check I used alert statements in this code:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" language="javascript">
function returnFunction(str)
{
alert("1");
var flag = new Boolean(false);
usernameValidation(str);
alert("2");
function usernameValidation(str)
{
alert("3");
var xmlHttpRequest;
if(window.XMLHttpRequest)
{
alert("4");
xmlHttpRequest = new XMLHttpRequest();
alert("5");
}
else
{
alert("6");
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttpRequest.onreadystatechange = function()
{
alert("7");
if(xmlHttpRequest.readyState==4 && xmlHttpRequest.status==200)
{
alert("8");
if(xmlHttpRequest.responseText=="available")
{
flag=new Boolean(true);
alert("9 flag:"+flag);
document.getElementById("myDiv").innerHTML="username is available";
}
else
{
flag=new Boolean(false);
alert("10 flag:"+flag);
document.getElementById("myDiv").innerHTML="username is already taken";
}
}
};
xmlHttpRequest.open("POST", "UsernameCheck", true);
xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttpRequest.send("uname="+str);
};
alert("before return flag is:"+flag);
return flag;
};
function formValidation(){
if(returnFunction(document.f1.username.value))
{
alert("caught flage:true");
return true;
}
else{
alert("caught flage:false");
return false;
}
}
</script>
</head>
<body>
<form method="post" action="register" name="f1" onsubmit="return formValidation()">
User Name:<div id="myDiv1"><input type="text" name="username" size="20" onkeyup="returnFunction(this.value)"></div>
<span id="myDiv" style="color: red"></span>
<input type="submit" value="register">
</form>
</body>
</html>
Ajax is asynchronous so your call to returnFunction , need not return the correct flag, it will return false always as most probably success function will be triggered only after method is completed(onresponse).
So you need to ensure that response of Ajax cal is recieved using a completed boolean, and continuously checking it until it is true.
<script type="text/javascript" language="javascript">
function returnFunction(str)
{
alert("1");
var flag = new Boolean(false);
var completed = new Boolean(false);
usernameValidation(str);
alert("2");
function usernameValidation(str)
{
alert("3");
var xmlHttpRequest;
if(window.XMLHttpRequest)
{
alert("4");
xmlHttpRequest = new XMLHttpRequest();
alert("5");
}
else
{
alert("6");
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttpRequest.onreadystatechange = function()
{
alert("7");
if(xmlHttpRequest.readyState==4 && xmlHttpRequest.status==200)
{
alert("8");
if(xmlHttpRequest.responseText=="available")
{
flag=new Boolean(true);
alert("9 flag:"+flag);
document.getElementById("myDiv").innerHTML="username is available";
}
else
{
flag=new Boolean(false);
alert("10 flag:"+flag);
document.getElementById("myDiv").innerHTML="username is already taken";
}
}
};
xmlHttpRequest.open("POST", "UsernameCheck", true);
xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttpRequest.send("uname="+str);
};
alert("before return flag is:"+flag);
return flag;
};
function formValidation(){
returnFunction(username);
while(!completed) {
//wait for ajax response
}
if(flag)
{
alert("caught flage:true");
return true;
}
else{
alert("caught flage:false");
return false;
}
}
</script>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" language="javascript">
var flag = new Boolean(false);
function returnFunction(str)
{
alert("1");
usernameValidation(str);
alert("2");
function usernameValidation(str)
{
alert("3");
var xmlHttpRequest;
if(window.XMLHttpRequest)
{
alert("4");
xmlHttpRequest = new XMLHttpRequest();
alert("5");
}
else
{
alert("6");
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttpRequest.onreadystatechange = function()
{
alert("7");
if(xmlHttpRequest.readyState==4 && xmlHttpRequest.status==200)
{
alert("8");
if(xmlHttpRequest.responseText=="available")
{
flag=new Boolean(true);
alert("9 flag:"+flag);
document.getElementById("myDiv").innerHTML="username is available";
}
else
{
flag=new Boolean(false);
alert("10 flag:"+flag);
document.getElementById("myDiv").innerHTML="username is already taken";
}
}
};
xmlHttpRequest.open("POST", "UsernameCheck", true);
xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttpRequest.send("uname="+str);
};
alert("before return flag is:"+flag);
return flag;
};
function formValidation(){
if(returnFunction(document.f1.username.value))
{
alert("caught flage:true");
document.f1.submit();
}
else{
alert("caught flage:false");
alert("Username chossen by u is already taken.Please choose different Username");
}
}
</script>
</head>
<body>
<form method="post" action="register" name="f1" >
User Name:<div id="myDiv1"><input type="text" name="username" size="20" onkeyup="returnFunction(this.value)"></div>
<span id="myDiv" style="color: red"></span>
<input type="submit" value="register">
</form>
</body>
</html>
make changes like this it will work .if any prob let be know.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" language="javascript">
function getXMLHttpRequest(){
var xmlHttpReq = false;
// to create XMLHttpRequest object in non-Microsoft browsers
if (window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
try {
// to create XMLHttpRequest object in later versions
// of Internet Explorer
xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
} catch (exp1) {
try {
// to create XMLHttpRequest object in older versions
// of Internet Explorer
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (exp2) {
xmlHttpReq = false;
}
}
}
return xmlHttpReq;
};
function usernameValidation(str)
{
if (str.length==0)
{
document.getElementById("uname").innerHTML="should not be empty";
return false;
}
else if(str.length<=4)
{
document.getElementById("uname").innerHTML="need more than 4 charachers";
return false;
}
else{
var xmlHttpRequest = getXMLHttpRequest();
xmlHttpRequest.onreadystatechange =function()
{
if (xmlHttpRequest.readyState < 4 && xmlHttpRequest.readyState > 0)
{
document.getElementById("uname").innerHTML = "<img src='images/load.gif' alt='checking...' width=16 height=16/>";
}
if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200)
{
if(xmlHttpRequest.responseText=="available")
{
document.getElementById("uname").innerHTML = "<img src='images/ok.png' alt='username available' width=16 height=16/>";
document.getElementById("uname1").innerHTML = ".";
}
else
{
document.getElementById("uname").innerHTML = "username not available";
}
}
};
xmlHttpRequest.open("POST", "UsernameCheck", true);
xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttpRequest.send("uname="+str);
};
};
function userSubmitValidation(){
var msg = document.getElementById("uname1").innerHTML;
if(msg=='.'){
return true;
}
else{
return false;
}
};
</script>
</head>
<body>
<form method="post" action="register" name="f1" onsubmit="return userSubmitValidation()">
User Name:<div id="myDiv1"><input type="text" name="username" size="20" onkeyup="usernameValidation(this.value)" onblur="usernameValidation(this.value)"></div>
<span id="uname" style="color: red"></span><span id="uname1" style="color: white"></span>
<input type="submit" value="register">
</form>
</body>
</html>
i am new at ajax too and i am kind of trying to do the same thing as you are doing. I have successfully checked the username availability using ajax and jsp. Then the thing i stuck at that even if a username is not available the page still submit after clicking submit button. Then I used javascript to solve this problem. I compared the returned text with another text declared before. If check successful then it will go to next page otherwise not. For details please check this page->"Ajax based username availablity checking and then generating some username to use in jsp". There check out the sample.jsp code. In that code a i did the checking part in the function named "conditions()". In that function the variable "checkvalue" hold the returned text which is generated by availability check. Then i compare it with the text "available". If matches then the page will submit other wise not. I am not sure is this what you wanted to know or not and if it is then my answer helps you or not. Thank you and good luck..

Resources