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();
} );
}
I have 2 divs in my html page. Using AJAX, JavaScript, I send my query parameters to a php file, which returns combined results for the 2 divs. I want to know how to separate the result in JavaScript and display in their respective divs.
<script>
function fetchData() {
var yr = document.getElementById('entry').value;
if (yr.length==0) {
document.getElementById("result1").innerHTML="";
document.getElementById("result2").innerHTML="";
return;
}
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var content = xmlhttp.responseText;
if (content == "%<searchword>%")
document.getElementById("result1").innerHTML = content;
else
document.getElementById("result2").innerHTML = content;
}
}
xmlhttp.open("GET","db.php?q="+ yr ,true);
xmlhttp.send();
}
</script>
<body>
<form>
Enter year: <input type="text" id="entry" />
<input type="button" value="check here" onclick="fetchData()" />
</form>
<div id="result1">result 1 here</div>
<div id="result2"> result 2 here</div>
</body>
Return json as PHP output, that is best for Javascript (do not forget json php headers, use json_encode), like this:
{
"div1": "Content for div 1",
"div2": "DIV 2 content"
}
Easy with jQuery getJSON method, or jQuery $.ajax:
$.ajax({
dataType: "json",
url: urlToPHPFile,
data: dataToSend,
success: function( jsonResponse ) {
$('#result1').html( jsonResponse.div1 );
$('#result2').html( jsonResponse.div2 );
}
});
To send request with pure Javascript take a look at this article.
To parse JSON just read this article.
So, with pure Javascript you get something like this:
function alertContents(httpRequest){
if (httpRequest.readyState == 4){
// everything is good, the response is received
if ((httpRequest.status == 200) || (httpRequest.status == 0)){
var obj = JSON.parse(httpRequest.responseText);
var div1 = getElementById('result1');
var div2 = getElementById('result2');
div1.innerHTML = obj.div1;
div2.innerHTML = obj.div2;
}else{
alert('There was a problem with the request. ' + httpRequest.status + httpRequest.responseText);
}
}
};
function send_with_ajax( the_url ){
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() { alertContents(httpRequest); };
httpRequest.open("GET", the_url, true);
httpRequest.send(null);
};
function fetchData() {
var yr = document.getElementById('entry').value;
if (yr.length == 0) {
document.getElementById("result1").innerHTML = "";
document.getElementById("result2").innerHTML = "";
return;
}
send_with_ajax( "db.php?q=" + yr );
};
fetchData();
In my application i'am making two ajax call for getting some data from database based on another variable value.
code part:
var xmlHttp;
var redirect;
function populate_site(obj, passedselect) {
xmlHttp = GetXmlHttpObject();
var site_type;
if (obj.value) {
site_type = obj.value
}else {
site_type = document.app.site_type.value;
}
var url="/cgi-bin/Web/Begin.cgi";
url=url+"?redirect=Get_Site_List";
url=url+"&site_type=" + site_type;
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function stateChanged() {
if (xmlHttp.readyState == 4){
document.getElementById('site_id').innerHTML = xmlHttp.responseText;
}
}
function Populate_Process_List(obj, process_id_param) {
var action_id;
if (obj.value) {
action_id = obj.value
}else {
action_id = document.app.action_id.value;
}
xmlHttp = GetXmlHttpObject();
if (obj.value == '') {
document.getElementById('process_id').innerHTML = ' ';
return false;
}
var url="/cgi-bin/Web/Begin.cgi";
url=url+"?redirect=Fetch_User_Process_List";
url=url+"&action_id=" + action_id;
url=url+"&process_id=" + process_id_param;
url=url+"&gp_flag=" + 'YES';
xmlHttp.onreadystatechange= Process_Data_StateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function Process_Data_StateChanged() {
if(xmlHttp.responseText != 'NA') {
if (xmlHttp.readyState == 4){
document.getElementById('process_id').innerHTML = xmlHttp.responseText;
}
}
}
function GetXmlHttpObject(){
var xmlHttp1=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp1=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp1=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp1=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp1;
}
And validating site_id and process_id variable using JavaScript.
Problem facing is whenever user press the submit button before ajax call loading is not completed (since me passing async parameter of the open() method has as true). Even while validating the site_id and process_id variable using JavaScript is not getting captured.
Validation code:
var siteaddindex = document.app.site_id[document.app.site_id.selectedIndex].value;
if(siteaddindex == "null"){
alert("Please select site location.");
document.app.site_id.focus();
return false;
}
var process_id = document.app.process_id.value;
if (process_id == '') {
alert("Please select process");
return false;
}
Please let me know how to perform validation of above fields, since those fields are mandatory.
i am trying to auto submit form when the input reaches 7 characters. i have tried few java script codes, but it is spoiling my script functioning.
can any one please help me in this.....
<script type="text/javascript">
var url = "GetCustomerData.php?id="; // The server-side script
function handleHttpResponse() {
if (http.readyState == 4) {
if(http.status==200) {
var results=http.responseText;
document.getElementById('divCustomerInfo').innerHTML = results;
}
}
}
function requestCustomerInfo() {
var sId = document.getElementById("txtCustomerId").value;
http.open("GET", url + escape(sId), true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
}
function getHTTPObject() {
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject){
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
if (!xmlhttp){
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}
}
return xmlhttp;
}
var http = getHTTPObject(); // We create the HTTP Object
</script>
<form id="form_home">
<p>Enter customer ID number to retrieve information:</p>
<p>Customer ID: <input type="text" maxlength="7" id="txtCustomerId" value="" /></p>
<p><input type="submit" value="Submit" onclick="requestCustomerInfo()" /></p>
</form>
<div id="divCustomerInfo"></div>
Here is the code that will submit the form when the text box reaches 7 chars:
document.getElementById('txtCustomerId').addEventListener('keyup', function(e) {
if(this.value.length === 7) {
document.getElementById('form_home').submit();
}
});
Here is a demo of it working:
http://jsfiddle.net/TuVN2/1/
Looking at your markup, I guess you want to run requestCustomerInfo() and not submit. If you submit the response will never be handled. To do this you would move the function call into the keyup handler:
document.getElementById('txtCustomerId').addEventListener('keyup', function(e) {
if(this.value.length === 7) {
requestCustomerInfo();
}
});
I would also not recommend hand rolling your ajax handler. Consider using a library like jQuery.
I'm working with a form for which the mark-up I can't change & can't use jQuery.
Currently the form post the results to a new window. Is it possible to change this to an ajax form so that the results displays on submit instead without altering any mark-up?
Pulling the results (mark-up) from the results page back to the form page.
Here is the mark-up for the form.
<form class="form-poll" id="poll-1225962377536" action="/cs/Satellite" target="_blank">
<div class="form-item">
<fieldset class="form-radio-group">
<legend><span class="legend-text">What mobile phone is the best?</span></legend>
<div class="form-radio-item">
<input type="radio" class="radio" value="1225962377541" name="option" id="form-item-1225962377541">
<label class="radio" for="form-item-1225962377541">
<span class="label-text">iPhone</span>
</label>
</div><!-- // .form-radio-item -->
<div class="form-radio-item">
<input type="radio" class="radio" value="1225962377542" name="option" id="form-item-1225962377542">
<label class="radio" for="form-item-1225962377542">
<span class="label-text">Android</span>
</label>
</div><!-- // .form-radio-item -->
<div class="form-radio-item">
<input type="radio" class="radio" value="1225962377543" name="option" id="form-item-1225962377543">
<label class="radio" for="form-item-1225962377543">
<span class="label-text">Symbian</span>
</label>
</div><!-- // .form-radio-item -->
<div class="form-radio-item">
<input type="radio" class="radio" value="1225962377544" name="option" id="form-item-1225962377544">
<label class="radio" for="form-item-1225962377544">
<span class="label-text">Other</span>
</label>
</div><!-- // .form-radio-item -->
</fieldset>
</div><!-- // .form-item -->
<div class="form-item form-item-submit">
<button class="button-submit" type="submit"><span>Vote now</span></button>
</div><!-- // .form-item -->
<input type="hidden" name="c" value="News_Poll">
<input type="hidden" class="pollId" name="cid" value="1225962377536">
<input type="hidden" name="pagename" value="Foundation/News_Poll/saveResult">
<input type="hidden" name="site" value="themouth">
Any tips/tutorial is much appreciated. :)
The following is a far more elegant solution of the other answer, more fit for modern browsers.
My reasoning is that if you need support for older browser you already most likely use a library like jQuery, and thus making this question pointless.
/**
* Takes a form node and sends it over AJAX.
* #param {HTMLFormElement} form - Form node to send
* #param {function} callback - Function to handle onload.
* this variable will be bound correctly.
*/
function ajaxPost (form, callback) {
var url = form.action,
xhr = new XMLHttpRequest();
//This is a bit tricky, [].fn.call(form.elements, ...) allows us to call .fn
//on the form's elements, even though it's not an array. Effectively
//Filtering all of the fields on the form
var params = [].filter.call(form.elements, function(el) {
//Allow only elements that don't have the 'checked' property
//Or those who have it, and it's checked for them.
return typeof(el.checked) === 'undefined' || el.checked;
//Practically, filter out checkboxes/radios which aren't checekd.
})
.filter(function(el) { return !!el.name; }) //Nameless elements die.
.filter(function(el) { return el.disabled; }) //Disabled elements die.
.map(function(el) {
//Map each field into a name=value string, make sure to properly escape!
return encodeURIComponent(el.name) + '=' + encodeURIComponent(el.value);
}).join('&'); //Then join all the strings by &
xhr.open("POST", url);
// Changed from application/x-form-urlencoded to application/x-form-urlencoded
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//.bind ensures that this inside of the function is the XHR object.
xhr.onload = callback.bind(xhr);
//All preperations are clear, send the request!
xhr.send(params);
}
The above is supported in all major browsers, and IE9 and above.
Here's a nifty function I use to do exactly what you're trying to do:
HTML:
<form action="/cs/Satellite">...</form>
<input type="button" value="Vote now" onclick="javascript:AJAXPost(this)">
JS:
function AJAXPost(myself) {
var elem = myself.form.elements;
var url = myself.form.action;
var params = "";
var value;
for (var i = 0; i < elem.length; i++) {
if (elem[i].tagName == "SELECT") {
value = elem[i].options[elem[i].selectedIndex].value;
} else {
value = elem[i].value;
}
params += elem[i].name + "=" + encodeURIComponent(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.open("POST",url,false);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
return xmlhttp.responseText;
}
Nowadays using FormData is the easiest method. You construct it with a reference to the Form element, and it serializes everything for you.
MDN has an example of this here -- roughly:
const form = document.querySelector("#debarcode-form");
form.addEventListener("submit", e => {
e.preventDefault();
const fd = new FormData(form);
const xhr = new XMLHttpRequest();
xhr.addEventListener("load", e => {
console.log(e.target.responseText);
});
xhr.addEventListener("error", e => {
console.log(e);
});
xhr.open("POST", form.action);
xhr.send(fd);
});
and if you want it as an object (JSON):
const obj = {};
[...fd.entries()].forEach(entry => obj[entry[0]] = entry[1]);
Expanding on Madara's answer: I had to make some changes to make it work on Chrome 47.0.2526.80 (not tested on anything else). Hopefully this can save someone some time.
This snippet is a modification of that answer with the following changes:
filter !el.disabled,
check type of input before excluding !checked
Request type to x-www-form-urlencoded
With the following result:
function ajaxSubmit(form, callback) {
var xhr = new XMLHttpRequest();
var params = [].filter.call(form.elements, function (el) {return !(el.type in ['checkbox', 'radio']) || el.checked;})
.filter(function(el) { return !!el.name; }) //Nameless elements die.
.filter(function(el) { return !el.disabled; }) //Disabled elements die.
.map(function(el) {
return encodeURIComponent(el.name) + '=' + encodeURIComponent(el.value);
}).join('&'); //Then join all the strings by &
xhr.open("POST", form.action);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = callback.bind(xhr);
xhr.send(params);
};
The strategy is to serialise the form and send the data using XHR, then do what you want with the response. There is a good set of utilities and help at Matt Krus's Ajax Toolbox and related Javascript Toolbox.
If you are just serialising the form posted, then the following will do the trick. It can easily be extended to include other form control types:
var serialiseForm = (function() {
// Checkboxes that have already been dealt with
var cbNames;
// Return the value of a checkbox group if any are checked
// Otherwise return empty string
function getCheckboxValue(cb) {
var buttons = cb.form[cb.name];
if (buttons.length) {
for (var i=0, iLen=buttons.length; i<iLen; i++) {
if (buttons[i].checked) {
return buttons[i].value;
}
}
} else {
if (buttons.checked) {
return buttons.value;
}
}
return '';
}
return function (form) {
var element, elements = form.elements;
var result = [];
var type;
var value = '';
cbNames = {};
for (var i=0, iLen=elements.length; i<iLen; i++) {
element = elements[i];
type = element.type;
// Only named, enabled controls are successful
// Only get radio buttons once
if (element.name && !element.disabled && !(element.name in cbNames)) {
if (type == 'text' || type == 'hidden') {
value = element.value;
} else if (type == 'radio') {
cbNames[element.name] = element.name;
value = getCheckboxValue(element);
}
}
if (value) {
result.push(element.name + '=' + encodeURIComponent(value));
}
value = '';
}
return '?' + result.join('&');
}
}());
A modern way using fetch would be:
const formData = new FormData(form);
fetch(form.action, {
method: 'POST',
body: formData
});
Note browser support and use this polyfil if IE-support is needed
function ajaxSubmit(form, callback) {
var xhr = new XMLHttpRequest();
var params = [].filter.call(form.elements, function (el) {return !(el.type in ['checkbox', 'radio']) || el.checked;})
.filter(function(el) { return !!el.name; }) //Nameless elements die.
.filter(function(el) { return !el.disabled; }) //Disabled elements die.
.map(function(el) {
if (el.type=='checkbox') return encodeURIComponent(el.name) + '=' + encodeURIComponent(el.checked);
else return encodeURIComponent(el.name) + '=' + encodeURIComponent(el.value);
}).join('&'); //Then join all the strings by &
xhr.open("POST", form.action);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = callback.bind(xhr);
xhr.send(params);
};
I just took Coomie's answer above and made it work for Radio/Checkboxes. I can't believe how simple and clear this is. With a few exceptions, I'm done using frameworks.
var params = "";
var form_elements = form.elements;
for (var i = 0; i < form_elements.length; i++)
{
switch(form_elements[i].type)
{
case "select-one":
{
value = form_elements[i].options[form_elements[i].selectedIndex].value;
}break;
case "checkbox":
case "radio":
{
if (!form_elements[i].checked)
{
continue; // we don't want unchecked data
}
value = form_elements[i].value;
}break;
case "text" :
{
value = form_elements[i].value;
}break;
}
params += encodeURIComponent(form_elements[i].name) + "=" + encodeURIComponent(value) + "&";
}
var xhr = new XMLHttpRequest();
xhr.open('POST', "/api/some_url");
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200)
{
console.log("xhr.responseText");
}
else
{
console.log("Error! Status: ", xhr.status, "Text:", xhr.responseText);
}
}
};
console.log(params);
xhr.send(params);
Here's the simplest method I came up with. I haven't found an example that uses this exact approach. The code submits the form using a non-submit type button and places the results into a div, if the form is not valid (not all required fields filled), it will ignore the submit action and the browser itself will show which fields are not filled correctly.
This code only works on modern browsers supporting the "FormData" object.
<script>
function ajaxSubmitForm() {
const form = document.getElementById( "MyForm" );
if (form.reportValidity()) {
const FD = new FormData( form );
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("content_area").innerHTML = this.responseText; } };
xhttp.open("POST","https://example.com/whatever.php",true);
xhttp.send( FD );
}
}
</script>
<div id="content_area">
<form id="MyForm">
<input type="hidden" name="Token" Value="abcdefg">
<input type="text" name="UserName" Value="John Smith" required>
<input type="file" accept="image/jpeg" id="image_uploads" name="ImageUpload" required>
<button type="button" onclick="ajaxSubmitForm()">
</form>
</div>