check form requirements and then send data with ajax - javascript

I am trying to send form data as json to my device (with XMLHttpRequest).
My form have multiple required fields, and should not submit if mandatory fields are empty. But form data sends even field empty!
I searched, and add event.preventDefault(); but it's not work.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>first assignment</title>
<script>
function curlcheck() {
event.preventDefault();
event.stopImmediatePropagation();
var user_id = document.getElementById("user_id").value;
var pass = document.getElementById("password").value;
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
var theUrl = "/submit_test";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({ "ProgMode": user_id, "pass": pass }));
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//document.getElementById("ajax_res").innerHTML = this.responseText;
console.log("success");
}
}
}
</script>
</head>
<body>
<div class="somebox"></div>
<ul>
<h3>Team 1 Online Exam System</h3>
</ul>
<form action="" method="POST">
<div name="form header" class="formhead">
<h1>Welcome</h1>
<p><span id="loginerr" class="err_alert"></span></p>
</div>
<div class="login_box">
<lable for="user_id">User ID</lable>
<input type="text" placeholder="Enter User ID" id="user_id" required>
<label for="password">Password</label>
<input type="password" placeholder="Enter Password" id="password" required>
<button id="but" type="submit" onclick="curlcheck(); return false">Login</button>
</div>
</form>
<div class="footer">
</div>
</body>
</html>

In HTML5, you do not need to check it by yourself, you can call the reportValidity() method to do the validation.
function curlcheck(form){
var user_id = document.getElementById("user_id");
var pass = document.getElementById("password");
if (user_id.reportValidity() && pass.reportValidity()){
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
var theUrl = "/submit_test";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({ "ProgMode": user_id.value, "pass": pass.value }));
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//document.getElementById("ajax_res").innerHTML = this.responseText;
console.log("success");
}
}
}
return false;
}
<form action="" method="POST" onclick="return curlcheck(this);">
<div name="form header" class="formhead">
<h1>Welcome</h1>
<p><span id="loginerr" class="err_alert"></span></p>
</div>
<div class="login_box">
<lable for="user_id">User ID</lable>
<input type="text" placeholder="Enter User ID" id="user_id" required>
<label for="password">Password</label>
<input type="password" placeholder="Enter Password" id="password" required>
<button>Login</button>
</div>
</form>

If required data empty then return false from curlcheck function.
<script>
function curlcheck(event) {
event.preventDefault();
event.stopImmediatePropagation();
var user_id = document.getElementById("user_id").value;
var pass = document.getElementById("password").value;
if (user_id === "" || pass === "") {
return false; //or show required message
}
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
var theUrl = "/submit_test";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({ "ProgMode": user_id, "pass": pass }));
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//document.getElementById("ajax_res").innerHTML = this.responseText;
console.log("success");
}
}
}
</script>

Related

Failed to load resource 405 (Method Not Allowed)

//i write a code to send message from form to my gmail but i get the following error failed to load resource the server responded with a status of 405
//(method not allowed)
HTML
<form class="contact-form">
<input type="text" name="" id="name" /> <br />
<input type="email" name="" id="email" /> <br />
<input type="text" name="" id="subject" /> <br />
<textarea name="" id="message" cols="30" rows="10"></textarea> <br />
<input type="submit" class="submit" value="Submit" />
</form>
JS
const contactForm = document.querySelector(".contact-form");
let fullName = document.getElementById("name");
let email = document.getElementById("email");
let subject = document.getElementById("subject");
let message = document.getElementById("message");
contactForm.addEventListener("submit", (e) => {
e.preventDefault();
let formData = {
name: fullName.value,
email: email.value,
subject: subject.value,
message: message.value,
};
let xhr = new XMLHttpRequest();
xhr.open("POST", "/");
xhr.setRequestHeader("content-type", "application/json");
xhr.onload = function () {
// error happens here
console.log(xhr.responseText);
if (xhr.responseText == "success") {
alert("email sent");
fullName.value = "";
email.value = "";
subject.value = "";
message.value = "";
} else {
alert("Something went wrong!");
}
};
xhr.send(JSON.stringify(formData));
});

Why is php POST array empty for me in one instance and populated in another, both using XHR POST?

I am trying to write code that will check if username is already used, and I wrote some test code where my php $_POST array was populated. However, I modified the test code slightly for the 'production' code I am developing, and my $_POST array is empty. My first set of code, that is working, html file is
<!DOCTYPE html>
<html lang="en">
<head>
<title>Testing XMLHttpRequest</title>
<meta charset="utf-8">
</head>
<body>
<header>
<h1>Testing XMLHttpRequest</h1>
</header>
<main>
<form name="newUser">
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<p id="serverResponse"></p>
<label for="password">Password:</label>
<input type="password" name="password">
</br>
<label for="confirm">Retype Password:</label>
<input type="password" name="confirm">
</form>
</main>
<script src="index.js"></script>
</body>
</html>
First set of code javascript file
(function () {
let usernameInput = document.querySelector("#username");
let serverResponse = document.querySelector("#serverResponse");
usernameInput.addEventListener("blur", function (event) {
let username = event.target.value;
if (username !== "") {
let request = new XMLHttpRequest();
request.open("POST",'validator.php',true);
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.onreadystatechange = function() {
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
serverResponse.innerHTML = this.responseText;
}
}
request.send(`username=${username}`);
}
else {
serverResponse.innerHTML = "";
}
});
}());
First set of code php file
<?php
$username = $_POST['username'];
echo $username;
?>
My modified code that does not work is below. The html file is
<!DOCTYPE html>
<html lang="en">
<head>
<title>Lunch Decider - New User Registration</title>
<meta charset="utf-8">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>Lunch Decider</h1>
</header>
<nav>
<ul>
<li>Home/Cancel</li>
</ul>
</nav>
<main>
<form action="newUser.php" method="POST" name="newUser">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<button type="button" id="checkAvailabilityButton">Check Availability</button>
<p id="availabilityResponse"></p>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
</br>
<label for="checkPassword">Repeat Password:</label>
<input type="password" id="checkPassword" name="checkPassword" required>
</br>
<button type="submit">Submit</button>
<button type="reset">Reset</button>
</form>
</main>
<script src="newUser.js"></script>
</body>
</html>
The javascript file for the code that does not work is
(function () {
let checkAvailabilityButton = document.querySelector("#checkAvailabilityButton");
let username = document.querySelector("#username");
let availabilityResponse = document.querySelector("#availabilityResponse");
checkAvailabilityButton.addEventListener("click", function(event) {
if (username.value === "") {
alert("You must first enter a username.");
}
else {
let xhr = new XMLHttpRequest();
xhr.open("POST","checkAvailability.php",true);
xhr.setRequestHeader("Content-type","application/x-www-url-formencoded");
xhr.onreadystatechange = function() {
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
availabilityResponse.innerHTML = this.responseText;
}
};
xhr.send(`username=${username.value}`);
}
});
}());
and finally my php code that does not work is
<?php
$username = $_POST['username'];
echo $username;
?>
Not sure where I have gone wrong in the second set of code. I have tried putting my data in a FormData object and passing that to the XHR.send() method. I realize I have switched in my first set of code from a 'blur' event on the input I am interested in directly, to my second set of code where my main event is clicking on a 'checkAvailability' button, but I can't see where that would make my $_POST array not accept the sent value. In both cases I can see where in the request there is username=nameEntryFromInputTextBox.
Please take a look and advise.
Not sure if xhr.send sends in JSON format, but in any case, try catching the post with:
$post = json_decode(file_get_contents("php://input"));
// will make an object - $post->var
$post = json_decode(file_get_contents("php://input"), true);
// will make an array - $post['var']
PHP "php://input" vs $_POST
I had a typo, in my code that was not working I had Content-type set to x-www-url-formencoded. It should have been x-www-form-urlencoded.

Can´t send form information

I have this form and I want to use its information to create a product using my API but it creates a empty object in my Mongo database. I´ve tried to enter pre defined information and it worked
<form id="form">
<label>Nome do Produto</label> <br />
<input type="text" id="name" name="name" required /><br />
<label>Quantidade do Produto</label> <br />
<input type="number" id="quantity" name="quantity" required /><br />
<label>Descricao</label><br /><br />
<input type="textbox" id="description" name="description" required /><br />
<button id="button">Criar</button>
<div id="result"></div>
</form>
<script>
var button = document.getElementById("button");
button.addEventListener("click", (event) => {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log("Test");
}
};
xhttp.open("POST", `http://localhost:3000/apiv1/products`, true);
xhttp.setRequestHeader("Accept", "application/json");
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.send(
JSON.stringify({
name: req.body.name,
description: req.body.description,
quantity: req.body.quantity,
})
);
});

Form submitting without refresh not working

I am trying to submit a form without doing a hard refresh but my page is refreshing. I tried putting action=“javascript:void(0);" in the form tag but that didn't work. I also cannot use jquery.
Work Flow that causes error:
Submitting a form that is supposed to send some information to a php file.
Page gets directed to another page that doesn't exist.
function toggle_visibility(id){
var e = document.getElementById(id);
if(e.style.visibility == 'hidden'){
e.style.visibility = 'visible';
}
else{
e.style.visibility = 'hidden';
}
}
function createAjaxRequestObject() {
var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
if (httpRequest.overrideMimeType) {
httpRequest.overrideMimeType('text/xml');
}
}
else if (window.ActiveXObject) { // IE
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
// Create the object
return httpRequest;
}
function sendTicket() {
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var email = document.getElementById("email").value;
var subject = document.getElementById("subject").value;
var msg = document.getElementById("msg").value;
var encFirst = encodeURIComponent(firstName);
var encLast = encodeURIComponent(lastName);
var encEmail = encodeURIComponent(email);
var encsubject = encodeURIComponent(subject);
var encmsg = encodeURIComponent(msg);
var info = "firstName="+encFirst+"&lastName="+encLast+"&email="+encEmail+"&subject="+encsubject+"&msg="+encmsg;
var http3 = createAjaxRequestObject();
if (http3.readyState == 4) {
if (http3.status == 200){
var result = JSON.parse(http3.responseText);
console.log(result);
}
}
http3.open("POST", "send_mail.php", true);
http3.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http3.send(info);
}
</script>
Welcome!
View My Tickets
Submit Ticket
Change my Password
Full Name
Email
Subject
Your Message *
You should change the type of you input from submit to button so the sendTicket() will be triggered, else the form will be submited before reached your sendTicket() function so it should be :
<input type="button" value="Submit" onclick="sendTicket();" />
Instead of :
<input type="submit" value="Submit" onclick="sendTicket();" />
Hope this helps.
function sendTicket() {
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var email = document.getElementById("email").value;
var subject = document.getElementById("subject").value;
var msg = document.getElementById("msg").value;
var encFirst = encodeURIComponent(firstName);
var encLast = encodeURIComponent(lastName);
var encEmail = encodeURIComponent(email);
var encsubject = encodeURIComponent(subject);
var encmsg = encodeURIComponent(msg);
var info = "firstName="+encFirst+"&lastName="+encLast+"&email="+encEmail+"&subject="+encsubject+"&msg="+encmsg;
console.log(info);
}
<h1>Welcome! </h1>
<div id="buttons">
<button class="myButton" onclick="showTickets(); toggle_visibility('table');">View My Tickets</button>
<button class="myButton" onclick="toggle_visibility('Submit');">Submit Ticket</button>
<button class="myButton" onclick="toggle_visibility('changePassword');">Change my Password</button>
</div>
<div id = "table"> </div>
<div id = "Submit">
<form id = "emailForm" action="javascript:void(0);">
<ul class="form-style-1">
<li><label>Full Name <span class="required">*</span></label><input type="text" name="firstName" class="field-divided" placeholder="First" id="firstName" /> <input type="text" name="field2" class="field-divided" placeholder="lastName" id = "lastName" /></li>
<li>
<label>Email <span class="required">*</span></label>
<input type="email" name="email" class="field-long" id= "email" />
</li>
<li>
<label>Subject</label>
<input type="text" name="subject" class="field-divided" placeholder="Subject" id="subject" />
</li>
<li>
<label>Your Message <span class="required">*</span></label>
<textarea name="msg" id="msg" class="field-long field-textarea"></textarea>
</li>
<li>
<input type="button" value="Submit" onclick="sendTicket();" />
</li>
</ul>
</form>
</div>
<br><br><br><br><br><br><br><br>

Textarea is null when posting via AJAX with plain javascript

When I try to post this textarea, it sends nothing and obviously returns nothing for that field.
All other input fields are fine.
I've read and everyone says to make sure .value is added after getelementid, which I was doing anyhow, so I'm not sure what is wrong.
I'm using Bootstrap 3, in case that matters.
Update: I just did a test and hard-coded text into the textarea field. That successfully passed. But any text that I type into the form does NOT get passed. I think this might be a Bootstrap 3 bug, perhaps.
Does anyone else know?
Javascript:
var http_request = false;
function show_hint(p_hint_text, p_span) {
document.getElementById(p_span).innerHTML = p_hint_text;
}
function makePOSTRequest(url, parameters, SpanName) {
http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/xml');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Cannot create XMLHTTP instance');
return false;
}
http_request.onreadystatechange = function () {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
//alert(http_request.responseText);
result = http_request.responseText;
document.getElementById(SpanName).innerHTML = result;
document.getElementById(StatusName).innerHTML = 'Ready';
} else {
alert('There was a problem with the request.');
}
}
};
http_request.open('POST', url, true);
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
alert(parameters);
http_request.send(parameters);
}
function Contact(obj, SpanName, StatusName) {
var curDateTime = new Date(); //For IE
var poststr = "gid=" + encodeURI(document.getElementById("gid").value) +
"&tid=" + encodeURI(document.getElementById("tid").value) +
"&cid=" + encodeURI(document.getElementById("cid").value) +
"&recid=" + encodeURI(document.getElementById("recid").value) +
"&item_ip=" + encodeURI(document.getElementById("item_ip").value) +
"&item_userid=" + encodeURI(document.getElementById("item_userid").value) +
"&item_author=" + encodeURI(document.getElementById("item_author").value) +
"&fromajax=" + encodeURI(document.getElementById("fromajax").value) +
"&action=" + encodeURI(document.getElementById("action").value) +
"&active=" + encodeURI(document.getElementById("active").value) +
"&message=" + encodeURI(document.getElementById("message").value);
var SpanName = SpanName;
var StatusName = StatusName;
//alert (SpanName);
alert(poststr);
makePOSTRequest('http://fakedomain.com', poststr, SpanName);
}
HTML
<span id="ContactFormSpanQXBIAHOBEU25">
<span id="statusQXBIAHOBEU25">
<form role="form" action="javascript:Contact(document.getElementById('ContactForm'),'ContactFormSpanQXBIAHOBEU25','statusQXBIAHOBEU25'); show_hint('Sending Data, Please Wait...', 'statusQXBIAHOBEU25');" method="post" name="ContactForm" id="ContactForm">
<input name="gid" id="gid" type="hidden" value="SDZOAYLTDV26">
<input name="tid" id="tid" type="hidden" value="ZBSAGNSCFM55">
<input name="cid" id="cid" type="hidden" value="2">
<input name="recid" id="recid" type="hidden" value="QXBIAHOBEU25">
<input name="item_IP" id="item_ip" type="hidden" value="555.555.555.555">
<input name="item_userid" id="item_userid" type="hidden" value="YCGLNBFZPD13">
<input name="item_author" id="item_author" type="hidden" value="YCGLNBFZPD13">
<input name="fromajax" id="fromajax" type="hidden" value="1">
<input name="action" id="action" type="hidden" value="add">
<input name="active" id="active" type="hidden" value="1">
<div class="form-group">
<textarea class="form-control" name="message" id="message" rows="5"></textarea>
</div>
<input name="Submit2" type="submit" class="btn btn-success btn-flat" value="Submit" />
</form>
</span>
</span>

Categories