I'm trying to use a form with a single input, that will ask for a 4-letter "secret" code (eg "a123"). The script will check if the corresponding page exists (eg: https://example.com/a123). If it exists, the page opens (in _self). If it does not, an error message is displayed.
The code below does not produce the expected result, it just refreshes the page regardless if my code is a match or not, although the url gets an appended parameter (eg: https://example.com/secret-code/?code=a123).
Functions in head:
function checkUrl(url) {
var request = false;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest;
} else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHttp");
}
if (request) {
request.open("GET", url);
if (request.status == 200) { return true; }
}
return false;
}
function validateCode() {
var x = document.forms["secret"]["code"].value;
if (x == "") {
document.getElementById("alertmsg").innerHTML = "Enter a code.";
}
if (checkUrl("https://www.example.com/" + x))
{
window.open("https://www.example.com/" + x,"_self");
} else {
document.getElementById("alertmsg").innerHTML = "Invalid Code. Try again.";
}
}
Form in body:
<form name="secret" onsubmit="validateCode()">
Code secret : <input type="text" name="code" size="4" maxlength="4" text-transform="uppercase"/>
<div id="alertmsg" style:"color:red;font-weight:bold"></div>
<input type="submit" value="Validate" />
</form>
I'm stumped. Thanks for helping me find the issue...
Adding another answer.
Removed form tag.
Changed the button type to button from submit.
Added onclick event on button to call validateCode() function.
Changed the way to get the secret code value x;
There was another issue with the blank data (empty string), which should be in the else case. Now handled.
function checkUrl(url) {
var request = false;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest;
} else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHttp");
}
if (request) {
request.open("GET", url);
request.send();
if (request.status == 200) {
return true;
}
}
return false;
}
function validateCode() {
var x = document.getElementById('code').value;
if (x == "") {
document.getElementById("alertmsg").innerHTML = "Enter a code.";
} else {
if (checkUrl("https://www.example.com/" + x)) {
window.open("https://www.example.com/" + x, "_self");
} else {
document.getElementById("alertmsg").innerHTML = "Invalid Code. Try again.";
}
}
return false;
}
Code secret : <input id="code" type="text" name="code" size="4" maxlength="4" text-transform="uppercase" />
<div id="alertmsg" style: "color:red;font-weight:bold"></div>
<input type="button" value="Validate" onclick="validateCode()" />
I have made few changes but not tested the code because having cross origin problem.
I hope it works for you.
Added return in <form name="secret" onsubmit="return validateCode()">
Added return false; in validateCode() function. As you were facing the page reload problem due to form submission.
Added request.send();, As you were just setting the to open the link, but not sending the request.
function checkUrl(url) {
var request = false;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest;
} else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHttp");
}
if (request) {
request.open("GET", url);
request.send();
if (request.status == 200) {
return true;
}
}
return false;
}
function validateCode() {
var x = document.forms["secret"]["code"].value;
if (x == "") {
document.getElementById("alertmsg").innerHTML = "Enter a code.";
}
if (checkUrl("https://www.example.com/" + x)) {
window.open("https://www.example.com/" + x, "_self");
} else {
document.getElementById("alertmsg").innerHTML = "Invalid Code. Try again.";
}
return false;
}
<form name="secret" onsubmit="return validateCode()">
Code secret : <input type="text" name="code" size="4" maxlength="4" text-transform="uppercase" />
<div id="alertmsg" style: "color:red;font-weight:bold"></div>
<input type="submit" value="Validate" />
</form>
Related
I'm trying to ad an event to a form in on my page. The problem is that on the first click the event fires once after twice and after that three times and go on. Also the innerHTML is not being replaced after onload. I'm pretty sure that is because of the multiple event firing tho.
<form name="search" id="getForm" oninput="requestData();">
Search customer:<br>
<input type="text" name="user" id="name"><br>
<input type="submit" value="submit">
</form>
</div>
<script>
function requestData(){
document.getElementById('getForm').addEventListener('submit', ev);
function ev(e){
e.preventDefault();
var user = document.getElementById('name').value;
if (user !== ""){
var url = 'http://localhost:3000/users/'+user;
var xhttp;
if (window.XMLHttpRequest){
xhttp=new XMLHttpRequest();
}
else{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onprogress = function(){
//this will print out on the 3rd ready state
//good for if the application is hanging
}
xhttp.onload = function() {
if (this.status == 200 || this.status == 304) {
var response = JSON.parse(xhttp.responseText);
var output = '';
if(response.data[0] != null){
for(var i in response.data){
output += '<ul>' +
'<li>Name: '+response.data[i].customer_name+'</li>' +
'<li>Parent: '+response.data[i].parent+'</li>' +
'</ul>';
}
document.getElementById('customer_name').innerHTML = output;
}
else {
alert('Customer does not exist.');
}
}
}
xhttp.onerror = function(){
console.log('Request error...');
}
xhttp.open("GET", url, true);
xhttp.send();
} else {
alert("Name must be filled out");
return false;
}
document.getElementById('getForm').removeEventListener('submit', ev);
}
}
</script>```
You're seeing the event fire multiple times because you're adding multiple event listeners - one every time the requestData() function runs as a result of the "oninput" event. And the removeEventListener command never fires because of the else { ... return... block just above it.
But I can't see why you need the "oninput" event at all. It doesn't do anything except add more and more event listeners. You can just declare the submit event directly, without this extra layer:
<form name="search" id="getForm">
Search customer:<br>
<input type="text" name="user" id="name"><br>
<input type="submit" value="submit">
</form>
</div>
<script>
document.getElementById('getForm').addEventListener('submit', ev);
function ev(e){
e.preventDefault();
var user = document.getElementById('name').value;
if (user !== ""){
var url = 'http://localhost:3000/users/'+user;
var xhttp;
if (window.XMLHttpRequest){
xhttp=new XMLHttpRequest();
}
else{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onprogress = function(){
//this will print out on the 3rd ready state
//good for if the application is hanging
}
xhttp.onload = function() {
if (this.status == 200 || this.status == 304) {
var response = JSON.parse(xhttp.responseText);
var output = '';
if(response.data[0] != null){
for(var i in response.data){
output += '<ul>' +
'<li>Name: '+response.data[i].customer_name+'</li>' +
'<li>Parent: '+response.data[i].parent+'</li>' +
'</ul>';
}
document.getElementById('customer_name').innerHTML = output;
}
else {
alert('Customer does not exist.');
}
}
}
xhttp.onerror = function(){
console.log('Request error...');
}
xhttp.open("GET", url, true);
xhttp.send();
} else {
alert("Name must be filled out");
return false;
}
}
</script>
Here's a little minimised working demo to show the event handling part of this in action:
document.getElementById('getForm').addEventListener('submit', ev);
function ev(e) {
e.preventDefault();
console.log(document.getElementById('name').value);
}
<form name="search" id="getForm">
Search customer:<br>
<input type="text" name="user" id="name"><br>
<input type="submit" value="submit">
</form>
I have form as follows, it require to sent an action to my java Servlet to do an update to the database.
How do I submit the form without the page get reloaded here?
Currently with action="myServlet" it keep direct me to a new page. And if I remove the action to myServlet, the input is not added to my database.
<form name="detailsForm" method="post" action="myServlet"
onsubmit="return submitFormAjax()">
name: <input type="text" name="name" id="name"/> <br/>
<input type="submit" name="add" value="Add" />
</form>
In the view of my Java servlet, request.getParameter will look for the name and proceed to add it into my db.
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
if (request.getParameter("add") != null) {
try {
Table.insert(name);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
In my JavaScript part, I have a submitFormAjax function
function submitFormAjax()
{
var xmlhttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
alert(xmlhttp.responseText); // Here is the response
}
var id = document.getElementById("name").innerHTML;
xmlhttp.open("POST","/myServlet",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("name=" + name);
}
A similar question was asked here
Submit form without reloading page
Basically, do "return false" after invoking the function. Something like this should work:
<form name="detailsForm"
method="post"
action="myServlet"
onsubmit="submitFormAjax();
return false;"
>
This is how I used to implement Ajax in JS without JQuery. As am a PHP and JS guy I cant possibly help you with Java Servlet side but yes heres my little help from JS side. This given example is a working example.See if it helps you.
// HTML side
<form name="detailsForm" method="post" onsubmit="OnSubmit(e)">
// THE JS
function _(x){
return document.getElementById(x);
}
function ajaxObj( meth, url )
{
var x = false;
if(window.XMLHttpRequest)
x = new XMLHttpRequest();
else if (window.ActiveXObject)
x = new ActiveXObject("Microsoft.XMLHTTP");
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/json");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
function OnSubmit(e) // call this function on submit
{
e.preventDefault();
var username = _("name").value;
if (username == "")
{
alert("Fill out the form first");
}
else
{
var all = {"username":username};
all = JSON.stringify(all);
var url = "Myservlet";
var ajax = ajaxObj("POST", url);
ajax.onreadystatechange = function()
{
if(ajaxReturn(ajax) == true)
{
// The output text sent from your Java side in response
alert( ajax.responseText );
}
}
//ajax.send("user="+username+");
ajax.send(all);
}
}
Thanks
Change the code in form
onsubmit="submitFormAjax(event)"
Change your JS code
function submitFormAjax(e)
{
e.preventDefault();
var xmlhttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xmlhttp = new XMLHttpRequest();
}
......
................
...............
return false; //at last line
I can't seem to stop my form from submitting, even when it is shown that it is returning false. Could someone please help me spot out the error?
Here is my html code:
<form role="form" onsubmit="return login()" action="03_select_survey.html">
<!-- Username -->
<div class="form-group">
<label for="user">Username:</label>
<input type="text" class="form-control" id="user" placeholder="Enter Username">
</div>
<!-- Password -->
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" placeholder="Enter password">
</div>
<!-- Submit button -->
<button type="submit" class="btn btn-primary btn-lg">Submit</button>
And here is my JavaScript code:
function login() {
"use strict";
// Variables
var username,
password,
xmlhttp,
isFound;
// Get username and password
username = document.getElementById("user");
password = document.getElementById("pwd");
// If username or password is empty
if (username.value === "" || password.value === "") {
window.alert("Incorrect username or password.");
return false;
} else {
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new window.ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
isFound = xmlhttp.responseText;
// Check if login info exists in database
if (isFound.value === "true") {
return true;
} else {
return false;
}
}
};
}
xmlhttp.open("GET", "login.php?user=" + username.value + "&pass=" + password.value, true);
xmlhttp.send();
if (xmlhttp.onreadystatechange === true) {
return true;
} else {
window.alert("Why won't you stop submitting?");
return false;
}
}
The code is reaching the "return false;" within the AJAX call, since it is alerting me with the message, but when I click OK, it proceeds to the next page instead of staying on the current page.
Show us at least the tag code as well. But the short answer it you're not stopping the form post. xmlHttp is asynchronus, so when you click your submit button, the command is fired off, but the function "login()" exits WITHOUT returning false. You need to return false from that function to stop the POST.
Here is a sample of what I would do....
function login() {
"use strict";
// Variables
var username,
password,
xmlhttp,
isFound;
// Get username and password
username = document.getElementById("user");
password = document.getElementById("pwd");
// If username or password is empty
if (username.value === "" || password.value === "") {
window.alert("Incorrect username or password.");
return false;
} else {
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new window.ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
alert('AJAX Response.....');
isFound = xmlhttp.responseText;
// Check if login info exists in database
if (isFound.value === "true") {
alert('We are good! Use JavaScript to navigate to new page...');
window.location = '03_select_survey.html';
return true;
} else {
alert('Not OK! They are not allowed in!');
return false;
}
} else {
alert('AJAX State Change we didn\'t expect.....');
return false; // In case we need to stop the form POST
}
};
}
xmlhttp.open("GET", "login.php?user=" + username.value + "&pass=" + password.value, true);
xmlhttp.send();
return false; // This false prevents FORM POST if we drop through before the async AJAX call finishes above
}
<form role="form" onsubmit="return login();">
<!-- The form doesn't need action="03_select_survey.html" -->
<!-- Username -->
<div class="form-group">
<label for="user">Username:</label>
<input type="text" class="form-control" id="user" placeholder="Enter Username">
</div>
<!-- Password -->
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" placeholder="Enter password">
</div>
<!-- Submit button -->
<button type="submit" class="btn btn-primary btn-lg">Submit</button>
</form>
Normally I'd use jQuery for this, but to cut a long story short, on this I can't.
I've successfully submitted a form via AJAX which has only one element of a form, like this:
<div id="response"></div>
<form onsubmit="submitStuff(this.datatosend.value);this.reset();return false;">
<input id="datatosend" type="text" />
<input type="submit" />
</form>
<script>
function submitStuff(e) {
if (e == "") {
document.getElementById("response").innerHTML = "";
return
}
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP")
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("response").innerHTML = xmlhttp.responseText
}
};
xmlhttp.open("GET", "sumbitData.php?data=" + e, true);
xmlhttp.send()
}
</script>
Now say I have this form:
<form onsubmit="????????????????????;this.reset();return false;">
<input id="datatosend1" type="text" />
<input id="datatosend2" type="text" />
<input type="submit" />
</form>
How do I do the same, submitting both values?
I'm a bit new to Javascript, especially 'pure' Javascript so please be a bit patient!
Build up the string
var data1 = encodeURIComponent(document.getElementById("datatosend1").value);
var data2 = encodeURIComponent(document.getElementById("datatosend2").value);
var url = "sumbitData.php?data1=" + data1 + "&data2=" + data2;
Read the form values and make a string to attach to the url:
var child=document.getElementById(form_id).getElementsByTagName('input');
var data=new Array();
for(var i=0;i<child.length;i++){
data.push(child[i].id + '='+ encodeURIComponent(child[i].value));
}
data='?' + data.join('&');
#themask
Hello and thanks for your help, I have tosed the php and now have just this code
<script>
document.forms[0].onsubmit =
function() {
var to = document.getElementById('myInput').value;
var ajax = new XMLHttpRequest;
ajax.onreadystate = function() {
if(this.readyState == 4 && this.status != 404) {
window.locaiton.replace(to);
} else {
window.location.replace('http://www.mysite.com/incontinence/protective_underwear/presto_protective_underwear/');
}
};
ajax.open('GET',to);
ajax.send(null);
};
</script>
<form onsubmit="location.href='http://www.mysite.com/coupons/' + document.getElementById('myInput').value; return false;" >
<input type="text" id="myInput" />
<input name="Submit" type="submit" id="Submit" />
</form>
But it is still sending me to incorrect urls if a bad code is used. Its like it is skipping the java all together.
Any additional help would be great.
Thank you,
Micah
Thank you,
Micah
Try using get_headers()
$headers = get_headers('http://www.activelifemed.com/incontinence/protective_underwear/presto_protective_underwear/')
if($headers[0] == 'HTTP/1.1 200 OK'){
//exists
}
else{
//doesn't exist
}
http://www.php.net/manual/en/function.get-headers.php
You can make this using JavaScript:
document.forms[0].onsubmit =
function() {
var to = document.getElementById('myInput').value;
var ajax = new XMLHttpRequest;
ajax.onreadystate = function() {
if(this.readyState == 4 && this.status != 404) {
window.locaiton.replace(to);
} else {
window.location.replace('http://www.mysite.com/incontinence/protective_underwear/presto_protective_underwear/');
}
};
ajax.open('GET',to);
ajax.send(null);
};