why statement xmlhttp.onreadystatechange cause this program work once only? - javascript

i make a simple REST web service consumer using HTML and javascript. here's the code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script language="javascript">
var xmlhttp;
function getdetails() {
var empno = document.getElementById("empno");
var url = "http://localhost:8080/TestWS1/rest/hello/" + empno.value;
xmlhttp = new XMLHttpRequest(); //#slaks: i put it here
xmlhttp.open('GET',url,true);
xmlhttp.send(null);
xmlhttp.onreadystatechange = function() {
var empname = document.getElementById("empname");
var age = document.getElementById("age");
if (xmlhttp.readyState == 4) {
//alert(xmlhttp.status);
if ( xmlhttp.status == 200) {
var det = eval( "(" + xmlhttp.responseText + ")");
if (det.age > 0 ) {
empname.value = det.name;
age.value = det.age;
}
else {
empname.value = "";
age.value ="";
alert("Invalid Employee ID");
}
}
else
alert("Error ->" + xmlhttp.responseText);
}
}
}
</script>
</head>
<body>
<h1>Call Employee Service </h1>
<table>
<tr>
<td>Enter Employee ID : </td>
<td><input type="text" id="empno" size="10"/> <input type="button" value="Get Details" onclick="getdetails()"/>
</tr>
<tr>
<td>Enter Name : </td>
<td><input type="text" readonly="true" id="empname" size="20"/> </td>
</tr>
<tr>
<td>Employee Age : </td>
<td><input type="text" readonly="true" id="age" size="10"/> </td>
</tr>
</table>
</body>
</html>
that code only show an employee name and age from the REST web service on the HTML textbox when a getDetail button is pressed. the parameter is employee number (empNo).
the main problem is, why this code only works once??
for example, if i put 1 on the empNo textbox and i pressed getDetail button, for the first time only, it will display the name and the age of the employee based on employee number that i was entered before. but for the second or third i press the getDetail button, it not works anymore. i've tried to give some alert to help me for debugging that code but the result is xmlhttp.onreadystatechange = function() only works once on the first time i pressed the getDetail button.
has anyone know how to solve this problem?? really stuck in here.. thanks a lot for helping me..
FYI: here's my web service code:
package com.webservices.TestWS1;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
//#Path("/hello")
#Path("/hello/{empno}")
public class Hello {
#GET // this method process GET request from client
#Produces("application/json") // sends JSON
public String getJson( #PathParam("empno") int empno) { // empno represents the empno sent from client
switch(empno) {
case 1 :
return "{'name':'George Koch', 'age':58}";
case 2:
return "{'name':'Peter Norton', 'age':50}";
default:
return "{'name':'unknown', 'age':-1}";
} // end of switch
} // end of
}

You can't re-use XMLHttpRequests.
You need to create a new XMLHttpRequest for each request.
Get rid of your init() function.

Put this between the script tag
function getdetails() {
xmlhttp = new XMLHttpRequest();
var empno = document.getElementById("empno");
var url = "http://localhost:8080/TestWS1/rest/hello/" + empno.value;
xmlhttp.open('GET',url,true);
xmlhttp.send(null);
xmlhttp.onreadystatechange = function() {
var empname = document.getElementById("empname");
var age = document.getElementById("age");
if (xmlhttp.readyState == 4) {
//alert(xmlhttp.status);
if ( xmlhttp.status == 200) {
var det = eval( "(" + xmlhttp.responseText + ")");
if (det.age > 0 ) {
empname.value = det.name;
age.value = det.age;
}
else {
empname.value = "";
age.value ="";
alert("Invalid Employee ID");
}
}
else
alert("Error ->" + xmlhttp.responseText);
}
}
}

A bit late this answer, but to whom it may concern ...
One need to to assign the callback function before one send the request.
So it should be likes this
var url = "http://localhost:8080/TestWS1/rest/hello/" + empno.value;
xmlhttp.open('GET',url,true);
xmlhttp.onreadystatechange = function() {
... some code here
}
xmlhttp.send(null);

Related

Stop submitting form if user doesn't exist in Database

I am developing a code in JSP using Ajax to verify the user in DB (means there is one input box where user provides the email id then code checks whether user exists or not using ajax), if user doesn't exist on DB then user should not be able to submit the form. In below code, Ajax is working. It shows true/false according to returning from JSP user check file (user_exist_function.jsp) but I am not able to control to user to stop submitting if user doesn't exist on DB. Please help.
js
var MyApp = {};
function check() {
xmlHttp = GetXmlHttpObject()
var url = "user_exist_function.jsp";
value = document.getElementById('email1').value;
url = url + "?username=" + value;
xmlHttp.onreadystatechange = stateChanged
xmlHttp.open("GET", url, true)
xmlHttp.send(null)
}
function stateChanged() {
if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
var showdata = xmlHttp.responseText;
document.getElementById("mydiv").innerHTML = showdata;
MyApp.status = showdata;
}
}
function GetXmlHttpObject() {
var xmlHttp = null;
try {
xmlHttp = new XMLHttpRequest();
} catch (e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
function check_submit() {
var var1 = MyApp.status.valueOf().toLocaleString();
if (var1 == 'true') {
return false;
} else {
return true;
}
}
html
<form name="form" onsubmit="return check_submit();">
Email Id: <input type="text" name="email" id="email1" onkeyup="check();">
<font color="red">
<div id="mydiv"></div>
</font>
<input type="submit">
</form>
user_exist_function.jsp
<%#page import="java.sql.*" %>
<%#include file="Database_connectivity.jsp" %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%
try{
String username = request.getParameter("username").toString();
PreparedStatement ps = conn.prepareStatement("SELECT * FROM V_USER_DATA WHERE " +
"EMAIL = ?");
ps.setString(1,username);
ResultSet res = ps.executeQuery();
if(res.next())
{
out.println("false");
}
else
{
out.println("true");
}
}catch (Exception e){
out.println(e);
}
%>
<input id="Mysubmit" type="submit">
<span id="msgNotInDB" style="display:none">You are not in the database</span>
if(res.next())
{
$("#Mysubmit").hide();
$("#msgNotInDB").show();
}
else
{
$("#Mysubmit").show();
$("#msgNotInDB").hide();
}
Note: this answer using jQuery, because any sensible attempt to use AJAX on a webpage would use jQuery (or at least a similar library). What I showed can be done without it (using document.getElementById()) but there's really not much sense in it.
UPDATE:
I noticed that I put the jQuery code in the server-side code. SO, let's expand our rewrite. This should replace all of the given Javascript:
function check()
{
$.get("user_exist_function.jsp", {username: $("email").val()},
function(data) {
if (data) {
$("#Mysubmit").show();
$("#msgNotInDB").hide();
} else {
$("#Mysubmit").hide();
$("#msgNotInDB").show();
} );
}

Controller not receiving data?

i'm trying to send data from a view to a controller using POST but i doesn't seems to work.
Here's my code (javascript function) :
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
var titre = str;
xmlhttp.open("POST", "CheckReturn", true);
//xmlhttp.send(titre);
xmlhttp.send({"titre":titre});
}
}
the html triggering it :
<div id="check-name" class="form-row">
<input id="name" type="text" name="name" placeholder="Titre de l'événement" onkeyup="showHint(this.value)">
<span id="txtHint"></span>
</div>
and finally, the controller SUPPOSED to get it :
[HttpPost]
public ActionResult CheckReturn(string titre)
{
var contexte = new intranetEntities();
var ajax = contexte.evenementiel.SqlQuery("Somequery" + titre);
ViewBag.ajax = ajax;
return PartialView();
}
i checked bit firebug, the data is sent, but with visual studio's debugger, i see that "titre" always stay null.
What can i do ?
I've run into something similar in the past with asp.net but I never really tried to understand what's happening. What fixed it for me was the following:
make a new class somewhere in your back-end (anywhere, doesn't matter for now)
class TitreWrapper {
public string titre {get; set;}
}
then in your controller
[HttpPost]
public ActionResult CheckReturn(TitreWrapper titreWrap)
{
string titre = titreWrap.titre;
}
this should work according to my previous experience
the top answer is wrong (but right in other circumstances I think)
for this problem the following worked:
xmlhttp.open("POST", "/CheckReturn?titre=" + titre, true);
and then just
xmlhttp.send();
OR
xmlhttp.open("POST", "CheckReturn", true);
then
xmlhttp.send("titre=" + titre);

Javascript validate username on PHP with realtime output

I want to use Javascript to validate my input username if it is correct or not showing result on realtime.
Here is index.html code:
<html>
<head>
<script>
function showHint(str){
if(str.length == 0){
document.getElementById("hint").innerHTML = "";
}else{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("hint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "demo3.php?input=" + str, true);
xmlhttp.send();
}
}
</script>
</head>
<body>
Type a username: <br>
<input id="hint" type="text" name="username" oninput="showHint(this.value)"><p id="hint"></p>
</body>
</html>
Here is the demo3.php code:
<html>
<head>
</head>
<body>
<?php
$mysqli = new mysqli("localhost","root","123456","mini");
$username = $mysqli->real_escape_string($_REQUEST['input']);
$sql = "SELECT username FROM `users` WHERE username='$username'";
$result = $mysqli->query($sql);
if($result->num_rows){
echo "Valid username";
}else{
echo "Invalid username";
}
?>
</body>
</html>
I use the oninput event example from w3cschools, and I am wondering why my result do not show what I expect?
And if I assign $username with static variable, demo3.php result seems to be correct feedback, not from index.html.
Plus, I am wondering how to validate multiple forms, such as password and email within the same validation php file.
Ex:
input1 -> check username ->output check result
input2-> check password ->output check result
input3-> check email->output check result
New to javascript.All the tutorial seems to provide only one demo, not multiple examples.
Since your input is being placed in the URL, you will need to use the GET parameter other than POST (which does not use the URL):
xmlhttp.open("GET", "demo3.php?input=" + str, true);
Now it should be able to pickup your input for $_REQUEST['input'] or $_GET['input']
The problem is that you are using the ID "hint" twice. ID is a unique identifier, so you NEVER should use it more than once in the same page. And you should avoid using inline handlers. You need to change your javascript to:
<script>
window.onload = function() {
function showHint(str){
if(str.length == 0){
document.getElementById("hint").innerHTML = "";
}else{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("hint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "demo3.php?input=" + str, true);
xmlhttp.send();
}
}
document.getElementById("hintInput").onkeyup = function() {
showHint(this.value)
}
}
</script>
and your HTML:
<input id="hintInput" type="text" name="username"><p id="hint"></p>
You can get rid of window.onload if you place your script tag before closing the body tag.

populating data from db and displaying in text box from a text box without submitting the form

please check the below code iam not getting output
I wanted to query database by typing in a text field and all the matching data related to the text field should be populated on the other empty fields by means of Ajax without submitting the form on the same page so i tried this code but it doesn't work.
The tutorial i saw was working perfectly i don't know what wrong i did as iam not getting the result....please check the below link for tutorial there u can understand what i exactly need...
I implemented this by seeing this tutorial http://www.crackajax.net/popform.php
Iam a newbie please help me with this issue.......
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" type="text/javascript"></script>
<script>
var url = "index.php?param=";
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 handleHttpResponse()
{
if (http.readyState == 3)
{
results = http.responseText.split(",");
document.getElementById('agtel').value = results[0];
document.getElementById('agfn').value = results[1];
document.getElementById('agid').value = results[2];
}
}
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>Person Name1:</td>
<td><input id="agtel" type="text" name="contacttel"></td>
</tr>
<tr>
<td>Person Name2:</td>
<td><input id="agfn" type="text" name="contactfullname"></td> </tr>
<td><input type="reset" value="Clear">
</td>
<td></td>
</tr>
</table>
</form>
<?php
// Create connection
$con=mysqli_connect("localhost","root","root","spikadb");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(strlen($param)>0)
{
$result = mysql_query("SELECT * FROM user WHERE flat_no LIKE '$param%'");
if(mysql_num_rows($result)==1) { while($myrow = mysql_fetch_array($result))
{
$personname1 = $myrow["name"];
$personname2 = $myrow["name2"];
$flatno = $myrow["flat_no"];
$textout .= $personname1.",".$personname2.",".$flatno;
}
}
else
{
$textout=" , , ,".$param;
}
}
echo $textout;
mysqli_close($con);
?>
</body>
</html>

Display PHP output in Ajax Popup

Hi All! So I'm a noob, and most of my code was done by a programmer for me. I can't get him to help me now.
I have a calculator that displays results (produced by calc.php) without relaoding the page. Demo is here: http://www.roofingcalculator.org/popup/popup.htm
Now I added Ajax popup (contact form) from here: http://dimsemenov.com/plugins/magnific-popup/ and it works.
What I want is to display the results of calc.php inside the Popop, but it does not work.
Details:
When user clicks "Calculate" button, the form sends info to CALC.JS using POST, which then sends info to CALC.PHP and diplays results back on the page with this tag:
<span id="CalcSum">Results:</span>
When I add the SPAN tag to popup, it does not display the result of PHP.
QUESTION How do I display results in AJAX Popup??
Please help - I really appreciate any help - Cheers!
Calc.js content:
var XmlHttp;
function GetXmlHttpObject() {
var XmlHttp = null;
try {
XmlHttp = new XMLHttpRequest();
} catch (e) {
try {
XmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
XmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return XmlHttp;
}
function StateChanged() {
if (XmlHttp.readyState == 4 || XmlHttp.readyState == "complete") {
document.getElementById("CalcSum").innerHTML = XmlHttp.responseText;
}
}
function ShowSum(url, params) {
XmlHttp = GetXmlHttpObject();
if (XmlHttp == null)
return;
XmlHttp.onreadystatechange = StateChanged;
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);
}
function GetInfo() {var str =
"size1=" + escape(encodeURI(document.getElementById("size1").value)) +
"&size2=" + escape(encodeURI(document.getElementById("size2").value));
ShowSum('http://www.website.com/calc.php', str);
}
calc.php
<?php
$size1_val = empty($_POST['size1']) ? '0' : $_POST['size1'];
$size2_val = empty($_POST['size2']) ? '0' : $_POST['size2'];
$total_size = $size1_val * $size2_val;
print "Result: ". round($total_size). "";
?>
HTML Form:
<table>
<script type="text/javascript" src="calc.js"></script>
<form id="formcalc" action="javascript:GetInfo();" accept-charset="UNKNOWN"
enctype="application/x-www-form-urlencoded" method="post">
<tr>
<td height="24" ><strong>Sizes:</strong>
</td>
<td height="24" valign="top" width="50%">
<input id="size2"/> x <input id="size1" s/> ft.
</td>
</tr>
<tr>
<td COLSPAN="2">
<input name="calc" type="submit" value="Calculate" />
<span id="CalcSum">Results:</span>
</form>
</td>
</tr>
</table>
Add $('.popup-with-form').magnificPopup('open'); to your stateChanged function as below. Works for me on your example. Changed both results spans and opens the pop up.
function StateChanged() {
if (XmlHttp.readyState == 4 || XmlHttp.readyState == "complete") {
$('.popup-with-form').magnificPopup('open');
document.getElementById("CalcSum").innerHTML = XmlHttp.responseText;
document.getElementById("CalcSumPopup").innerHTML = XmlHttp.responseText;
}
}
Update: more documentation here http://dimsemenov.com/plugins/magnific-popup/documentation.html if you need it.
Is the html for the Ajax popup on the same page as the form? If so, add
<span id="CalcSumPopup">Results:</span>
to the popup where you want the result to go and add
document.getElementById("CalcSumPopup").innerHTML = XmlHttp.responseText;
after document.getElementById("CalcSum").innerHTML = XmlHttp.responseText; in Calc.js.
If it is not on the same page this will not work.
EDIT:
This works because id's are meant to be unique. getElementById will find the first occurrence of the specified id and then stop, so if you want multiple places to be changed you need to give them unique id's.

Categories

Resources