AJAX not working when pressing submit button - javascript

I am practicing the basics of AJAX.
When I click Submit nothing happens.
Here’s my code.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>FIRST AJAX!</title>
<script>
function alertMe(){
var field1 = document.getElementById("Field1").value;
var parser = "parse.php";
var values = "name="+filed1;
var xml = new XMLHttpRequest();
xml.open("POST", parser, true);
xml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xml.onreadystatechange = function(){
if(xml.readyState == 4 && xml.status == 200){
document.getElementById('output').innerHTML = xml.responseText;
}
}
xml.send(values);
document.getElementById('output').innerHTML = " Loading ... ";
}
</script>
</head>
<body>
<input type="text" name="Field1" id="Field1"/>
<input type="submit" name="Fsend" onClick="alertMe();"/>
<p id="output"></p>
</body>
</html>
Thank you.

The problem is you are declaring a variable called field1, and then calling it as fiLEd1.
Try checking the console for errors, it's always useful

var values = "name="+filed1;
has a typo, should be...
var values = "name="+field1;
Also, input elements should be within a form and you probably want to use type="button" since you are not submitting the form. Finally, all standard attributes should be in lowercase, should be onclick, not onClick.
<!doctype html> <html> <head> <meta charset="utf-8"> <title>FIRST AJAX!</title> <script>
function alertMe(){
var field1 = document.getElementById("Field1").value;
var parser = "parse.php";
var values = "name="+field1;
var xml = new XMLHttpRequest();
xml.open("POST", parser, true);
xml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xml.onreadystatechange = function(){
if ( xml.readyState == 4 && xml.status == 200){
document.getElementById('output').innerHTML = xml.responseText;
}
}
xml.send(values);
document.getElementById('output').innerHTML = " Loading ... ";
}
</script>
</head>
<body><form>
<input type="text" name="Field1" id="Field1"/>
<input type="button" value="Submit" name="Fsend" onclick="alertMe();"/>
</form> <p id="output"></p>
</body> </html>

Related

How to get the value of a checkbox using getelementbyID inside a form

I have a code which worked fine while I was testing it now I decided it to include it inside a form and it just does not want to work. If I remove the form tag it works and with the form tag it does not.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
<script>
function action() {
var checkBox = document.getElementById("UPCheck");
if (checkBox.checked == true){
window.localStorage['username'] = document.getElementById('username').value;
window.localStorage['password'] = document.getElementById('password').value;
window.localStorage['unpwchecked'] = "yes";
alert("Saved!");
}
else
{
window.localStorage['username'] = "";
window.localStorage['password'] = "";
window.localStorage['unpwchecked'] = "";
}
}
function action2() {
document.getElementById('username').value = window.localStorage['username'];
document.getElementById('password').value = window.localStorage['password'];
}
</script>
</head>
<body>
<form>
<input type="text" id="username" name="username" value="">
<input type="text" id="password" name="password" value="">
Save username / password in cookies: <input type="checkbox" id="UPCheck" name="savelocalunpw">
<p><button onclick="action()" type="button">Save values!</button></p>
<p><button onclick="action2()" type="button">Load values!</button></p>
</form>
<script>
var alerted = localStorage.getItem('unpwchecked');
if (alerted == 'yes') {
document.getElementById('username').value = window.localStorage['username'];
document.getElementById('password').value = window.localStorage['password'];
document.getElementById("UPCheck").checked = true;
}
</script>
</body>
</html>
Remove the form tag and values are properly saved in localstorage.
The problem comes from the function name. If you rename
function action()
to
function action1()
and also modify
<button onclick="action1()" type="button">Save values!</button>
then your code will work.
I notices that without the form tag, the code works ok. If you add the form element, then you will get a console error, stating that action() is not a function. I'm just guessing that there is a conflict between the function name action() and the form attribute action
Try:
var isChecked = document.getElementById("UPCheck").checked;
Probably better practice to add an event handler for the buttons, that works with the form tags. Kind of interesting that it works with renaming the function.
JS
document.getElementById("save").addEventListener("click", function(){
var checkBox = document.getElementById("UPCheck");
if (checkBox.checked == true){
window.localStorage.username = document.getElementById('username').value;
window.localStorage.password = document.getElementById('password').value;
window.localStorage.unpwchecked = "yes";
alert("Saved!");
}
else
{
window.localStorage.username = "";
window.localStorage.password = "";
window.localStorage.unpwchecked = "";
}
});
document.getElementById("load").addEventListener("click", function(){
document.getElementById('username').value = window.localStorage.username;
document.getElementById('password').value = window.localStorage.password;
});
var alerted = localStorage.getItem('unpwchecked');
if (alerted == 'yes') {
document.getElementById('username').value = window.localStorage.username;
document.getElementById('password').value = window.localStorage.password;
document.getElementById("UPCheck").checked = true;
}
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<body>
<form>
<input type="text" id="username" name="username" value="">
<input type="text" id="password" name="password" value="">
Save username / password in cookies: <input type="checkbox" id="UPCheck" name="savelocalunpw">
<p><button id = "save" type="button">Save values!</button></p>
<p><button id = "load" type="button">Load values!</button></p>
</form>
</body>
</html>
You can use "dot" notation for localStorage.

How to output only the string input of the JSON that's returned?

I am struggling to get just the data that is input to display into the span for my AJAX request, it's showing the full object by the looks of it. How do I adjust this so it outputs only the string that is input?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Random Input</title>
</head>
<body>
<form>
<fieldset>
<legend>Data Lookup</legend>
<label for="data"></label>
<input type="data" name="firstData" id="firstData" placeholder= "Input">
<input type="submit" id="inputSubmit">
</fieldset>
</form>
<h2>Output</h2>
<ul>
<li>
<span>Data Output: </span><span id="newData"></span></li>
</ul>
<script src="input.js"></script>
</body>
</html>
Javascript
document.addEventListener('DOMContentLoaded', bindButtons);
function bindButtons(){
document.getElementById('inputSubmit').addEventListener('click', function(event){
var req = new XMLHttpRequest();
var payload = {firstData:null};
payload.firstData = document.getElementById('firstData').value;
req.open('POST', 'http://httpbin.org/post', true);
req.setRequestHeader('Content-Type', 'application/json');
req.addEventListener('load',function(){
if(req.status >= 200 && req.status < 400){
var response = JSON.parse(req.responseText);
document.getElementById('firstData').textContent = response.firstData;
document.getElementById('newData').innerHTML = response.data;
} else {
console.log("Error in network request: " + req.statusText);
}});
req.send(JSON.stringify(payload));
event.preventDefault();
});
}
Replace the following:
document.getElementById('newData').innerHTML = response.data; with
document.getElementById('newData').innerHTML = JSON.parse(response.data).firstData;.
Hope this will help!

Javascript can't get form to validate

I'm having problems getting my form to validate with Javascript. I've tried a bunch of different things, but I just can't get it to work. It's possible I'm missing something completely basic, I am pretty new at this. Please let me know what I could possibly change.
<!DOCTYPE html>
<html lang = "en">
<head>
<title> </title>
<meta charset = "utf-8" />
</head>
<body>
<script lang = "text/javascript">
document.getElementById("myForm").onsubmit = validateForm();
function zipcheck(sZip)
{
var postalRegex = /^d{5}(-\d{4})?$/;
return postalRegex.test(sZip);
}
function validateForm()
{
if (zipcheck(document.getElementById("zip"))
return true;
else
{
alert(document.getElementById("zip") + " is not a valid zip code");
return false;
}
}
</script>
<form id = "myForm" action = "" >
<p>
<label> Zip Code
<input type = "text" id = "zip" />
</label>
<input type = "submit" name = "submit" />
</p>
</form>
</body>
</html>
The Problem your are, checking the HTML Element not the Value. It should be document.getElementById("zip").value
document.getElementById("myForm").onsubmit = validateForm;
function zipcheck(sZip)
{
var postalRegex = /^d{5}(-\d{4})?$/;
return postalRegex.test(sZip);
}
function validateForm()
{
if (zipcheck(document.getElementById("zip").value)){
return true;
}else
{
alert(document.getElementById("zip").value + " is not a valid zip code");
return false;
}
}
<!DOCTYPE html>
<html lang = "en">
<head>
<title> </title>
<meta charset = "utf-8" />
</head>
<body>
<form id = "myForm" action="/test" method="get" >
<p>
<label> Zip Code
<input type = "text" id = "zip" />
</label>
<input type = "submit" name = "submit" />
</p>
</form>
</body>
</html>
here is a working sample on jsfiddler https://jsfiddle.net/u9suy516/
Optional Information: when using addEventListener you would also have to use the preventDefault() function on the passed event Parameter, but not need the return statments.
function validateForm(event)
{
if (!zipcheck(document.getElementById("zip").value)) {
alert(document.getElementById("zip").value + " is not a valid zip code");
event.preventDefault();
}
}

Print value using GET or POST

My goal is to print the value entered in the Firstpage.html to basicform.html using GET or POST.
I need it to be done only using Html and JavaScript or Ajax.
Code for Firstpage.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
function result()
{
var x=document.forms["fom"]["name"].value;
$_GET[0]=x;
}
</script>
</head>
<body>
<form method="get" action="basicform.html" name="fom">
Your name: <input type="text" id="name" name="name" size="25" /> <br />
<input type="submit" value="submit" onclick="result()" />
</form>
</body>
</html>
This is the code in basicform.html
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<script>
function loaad()
{
var name = $_GET[x];
if(isset($_get(submit)))
{
document.write(name);
}
}
</script>
<body onload="loaad();">
</body>
</html>
You can only get the GET parameters using JavaScript. If JavaScript was able to access post variables, it would create security risks.
This is how you would get the GET parameters using JS.
var $_GET = {}, args = location.search.substr(1).split(/&/);
for (var i=0; i<args.length; ++i) {
var tmp = args[i].split(/=/);
if (tmp[0] != "") {
$_GET[decodeURIComponent(tmp[0])] = decodeURIComponent(tmp.slice(1).join("").replace("+", " "));
}
}
I Completed the Task Successfully using localStorage.
Code for Firstpage.html
<script>
function store()
{
if(localStorage)
{
document.getElementById("contactForm").addEventListener("submit",
function()
{
var name = document.getElementById("name").value;
localStorage.setItem('name',name);
var age = document.getElementById("age").value;
localStorage.setItem('age',age);
})
}
}
</script>
</head>
<body>
<form id="contactForm" action="result.html" method="POST" >
<label for="name">Name</label>
<input type="text" name="name" id="name">
<label for="Age">Age</label>
<input type="text" name="age" id="age">
<input type="submit" value="send" onclick="store()">
</form>
</body>
and the result.html is
<script>
window.onload= function()
{
var x =localStorage.getItem('name');
var y=localStorage.getItem('age');
if((x !="undefined") || (x!="NULL"))
{
document.getElementById("ret").innerHTML="hello "+x+" your are "+y+" years old";
}
}
</script>
</head>
<body>
<div id="ret" style="position:absolute; left:400px; top:200px; height:400px; width:400px; text-align:center">
Result
</div>
</body>
If you want to get GET parameter from Javascript use this function :
function getUrlParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
Reference:
Get url parameter jquery Or How to Get Query String Values In js
Then simply use this:
var name = getUrlParameter('x');
//assuming url: http://yoursite.copm/?x=test
document.write(name);
Your form is sending the data using get (different than PHP's $_GET). This means that the values sent will appear in the address of the web page the form is sent to - no need for JS on this page. For example, on submitting your firstpage.html form you may get to:
basicform.html?name=Bob
This works well since JavaScript can get those parameters (not very cleanly, but it can). Put this on basicform.html:
function getQueryParams(qs) {
qs = qs.split("+").join(" ");
var params = {}, tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])]
= decodeURIComponent(tokens[2]);
}
return params;
}
var query = getQueryParams(document.location.search);
Then, you'll use the query variable to print out the name value.
document.write(query.name);
getQueryParams function from here on SO.
Also, the reason using $_GET didn't cause errors is that it's formed like any other valid JavaScript variable name. However, it's just that - the same as any JS variable - and has no relation to PHP's $_GET variable.

Get input value if values is pregiven

This gives me back the original value of the input not the edited one.
<input type='text' value='test'>
this.parentNode.getElementsByTagName('input')[0].value
The js event in on onchage
I have it like this right now and I am not getting the input of it...
var inputs=document.getElementById('wrap').getElementsByTagName('input');
for (var i = inputs.length - 1; i >= 0; i--) {
inputs[i].onchange=function(){
var x=this.parentNode.appendChild(document.createElement("a"));
x.innerHTML="upravit";
x.onclick=function(){
var hr = new XMLHttpRequest();
console.log(this.parentNode.getElementsByTagName('input')[0].value);
Even the console.log itself gives me back the default value instead of the new one...
var vars = "menu=1&name=";
hr.open("POST", "Ajax/UpdateCategory.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function(){
if(hr.readyState==4&&hr.status==200){
var return_data = hr.responseText;
if(return_data!="ok"){
alert(return_data);
}
}
}
hr.send(vars);
}
}
};
Please try this demo to learn onchange handler: http://www.w3school.com.cn/tiy/t.asp?f=hdom_onchange
and compare with this demo: http://www.w3school.com.cn/tiy/t.asp?f=hdom_onkeyup
Then you will know that, just use onkeyup() instead will work.
=== edited content ===
html:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
window.onload = function () {
var inputs=document.getElementById('wrap').getElementsByTagName('input');
var x=document.createElement("a");
var data;
x.innerHTML="upravit";
x.onclick=function(){
alert(data);
}
for (var i = inputs.length - 1; i >= 0; i--) {
inputs[i].onchange=function(){
this.parentNode.appendChild(x);
data = this.value;
}
}
};
</script>
</head>
<body>
<div id="wrap">
<input type='text'>
<input type='text'>
<input type='text'>
</div>
</body>
</html>
Please run this html in your local environment, I think this meet your needs.
you can do like this
html
<input type='text' value='test' onchange="dostuff(this)" />
js
function dostuff(s) {
alert(s.value);
}
here is a fiddle
If this doesn't suit your case, please tell us how you are binding the js code in your question with the input in the html code.
<input type='text' value='test' onchange="dostuff(this.value)" />
function dostuff(value) {
alert(value);
}

Categories

Resources