Getting error while submit form with ajax - javascript

When I was submitting post method form, given input fields values, not getting while submitting. If i using Ajax call in Jquery the form values serialize and submit it correctly, but in a javascript, Ajax call using FormData I'm getting error.
Can anyone resolve my problem.
Error:
Error: Can't set headers after they are sent. at
ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:356:11)
apollo.model.save.unsetkey: Primary Key Field: name must have a value
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form id="myForm" method="post" action="">
<div>
<label for="name">Enter name:</label>
<input type="text" id="name" name="name">
</div>
<div>
<label for="surname">SurName:</label>
<input type="text" id="surname" name="surname">
</div>
<div>
<label for="age">Age:</label>
<input type="text" id="age" name="age">
</div>
<input type="submit" value="Submit!" onclick="loadForm()">
</form>
<p id="demo"></p>
<script>
function loadForm() {
var xhttp = new XMLHttpRequest();
var myForm = document.getElementById('myForm');
var formData = new FormData(myForm);
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("POST", "http://127.0.0.1:8080/user", true);
xhttp.setRequestHeader('Accept', 'application/json');
xhttp.setRequestHeader('Content-Type', 'application/json');
var data = JSON.stringify(formData);
console.log('data = ', data);
xhttp.send(data);
}
</script>
</body>
</html>

You don't stop the default submission of the form, so when someone clicks the submit button the form will submit normally as well as through using Ajax. The solution is to bind a listener to the form submission and prevent the default behaviour.
Try this:
document.querySelector("#myForm").addEventListener("submit", function (event) {
event.preventDefault();
// ... Ajax call here ...
})

Related

Form submit Ajax - vanilla js - JSON string instead element message

After submitting the form, I want to display success or error message by removing element id (id value display:none). Element contains the message text.
I can submit the form with this script, but instead showing me the element, new page is opened with JSON string.
What should be corrected in the script?
vanilla Javascript
<script type="text/javascript">
var form = document.getElementById("leadcontact");
var sent = document.getElementById('sent');
var notsent = document.getElementById('notsent');
form.onsubmit = function(event) {
event.preventDefault();
var formData = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.open("POST", form.action, true);
xhr.send(formData);
xhr.onload = function(e) {
if (xhr.status === 200) {
sent.removeAttribute('id');
form.reset();
} else {
notsent.removeAttribute('id');
}
};
};
</script>
the Form
<form id="leadcontact" action="xxxxxxxxxxx" method="POST" enctype="multipart/form-data">
<div class="form-field-container">
<label for="name">name</label>
<input type="text" name="name">
</div>
<div class="form-field-container">
<label for="tel">phone</label>
<input type="text" name="phone">
</div>
<div class="form-field-container">
<label for="email">email</label>
<input type="email" name="email">
</div>
<div class="form-field-container">
<label for="message">message</label>
<textarea name="message"></textarea>
</div>
<p id="notsent" class="message-status error">Error! Not sent</p>
<p id="sent" class="message-status success">Message sent</p>
<button type="submit">Send</button>
</form>
JSON output page - the page shows after submission
{"success":true,"given_params":{"name":"","phone":"","email":"","message":""}}
You need to place the onload event handler before you send the request.
This is because the event handler is then attached to the request bwdire it is sent.
See Item 5
https://xhr.spec.whatwg.org/#the-send()-method
for more information on how send() works.

Change HTML element using XHttpRequest from HTML form

I want to be able to enter a name into a form and have a message sent back underneath saying "Your name is" [name] ", right?" I built this little test program that I plan on incorporating back into the main code but haven't had much luck with it. I am using the POST method.
<HTML XMLns="http://www.w3.org/1999/xHTML">
<head>
<title>A Simple Ajax Example</title>
<script type="text/javascript" src="xhr.js"></script>
<script type="text/javascript" src="simpleajax.js"> </script>
</head>
<body>
<h1>Fetching data with Ajax</h1>
<iframe name="iFrame" style="display: none;"></iframe>
<form method="post" action="data.php" target="iFrame">
<label>User Name:</label>
<input id="namefield" type="text" name="namefield">
<input type="submit" name="submit" value="Fetch" onclick="loadDoc(namefield.value);">
</form>
<div>
<p id="targetDiv">The fetched data will go here.</p>
</div>
</body>
</HTML>
And the javascript...
function loadDoc(name) {
var xhttp = new XMLHttpRequest();
var firstName = name;
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("targetDiv").innerHTML = this.responseText;
}
};
xhttp.open("POST", "data.php?namefield=" + firstName, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send();
}
Here is what input type submit does from MDN :
<input> elements of type "submit" are rendered as buttons.
When the click event occurs (typically because the user clicked the button),
the user agent attempts to submit the form to the server.
So to change that, one of the ways is to return false in the onclick handler ex:
<input type="submit" name="submit" value="Fetch" onclick="loadDoc(namefield.value);return false;">
Or you can use Button Element instead of submit which will give more meaning for what you need to do:
<button type="button" onclick="loadDoc(namefield.value);">Fetch</button>

Submit a form and get a JSON response without jQuery

I have a simple HTML form like this:
<div class="border-little text-center grey">
<form action="https://www.THIS IS MY URL.php" method="get">
<input name="player" id="player" value="1" class="hidden">
<label for="number">Enter a number</label>
<input type="text" id="number" name="number" placeholder="">
<input type="submit" value="Submit">
</form>
</div>
The operation is as follows:
The player enters a number, and the server answers using a JSON format.
My issue:
When I press "submit" My webpage leaves and redirects to the server page display a JSON formatted answer.
What I want to do:
I want to stay on my page and be able to receive the answer in JSON format and display them below my form instead of being redirected to the server page.
More details:
example of JSON answer I get from the server:
{"guess": "lower"}
I cannot use any kind of JavaScript library so JQuery is forbidden.
you just use ajax method of js
function r_submit() {
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "https://www.THIS IS MY URL.php", true);
var params = {"player":document.getElementById("player").value};
xhttp.send(params);
xhttp.onload = function() {
alert(xhttp.responseText);
}
}
and execute r_submit() function button when you click button
here your html code will be like
<div class="border-little text-center grey">
<input name="player" id="player" value="1" class="hidden">
<label for="number">Enter a number</label>
<input type="text" id="number" name="number" placeholder="">
<input type="submit" value="Submit" onsubmit='r_submit()'>
</form>
</div>
i've written years ago a simple js part, that allows you to send XHR requests easily. it's a little deprecated but it is a simple template to understand how you CAN go on.
you could modernize it by using webworkers and make it closer to your setup. if you wish i could post an old prototype in JS from me with webworkers and so on (but some names of variables are in german..)
function getElement(inp)
{
return document.getElementById(inp);
}
function put(data,div)
{
getElement(div).innerHTML = data;
}
//information: autoput means: do you wish to write the raw response in a div? [0,1] - when 1 then put the id of the div in var div at the call of the function
function get(url,data,method,autoput,div)
{
var req;
if(window.XMLHttpRequest)
{
req = new XMLHttpRequest();
}
else
{
req = new ActiveXObject("Microsoft.XMLHTTP");
}
req.onreadystatechange = function()
{
if(req.readyState == 4 && req.status == 200)
{
if(autoput == 1)
{
put(req.responseText, div);
}
}
}
if(method.toLowerCase() == "get")
{
req.open("GET",url+data,true);
req.send();
}
else
{
if(method.toLowerCase() == "post")
{
if(data !== "")
{
req.open("POST", url, true);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.send(data);
}
}
}
}
It's possible to use iframe technique when jQuery is forbidden. Submit the form to the named iframe and wait for onload event. Modified html and js code will look like:
<div class="border-little text-center grey">
<form action="https://www.THIS IS MY URL.php" method="get" target="myframe">
<input name="player" id="player" value="1" class="hidden">
<label for="number">Enter a number</label>
<input type="text" id="number" name="number" placeholder="">
<input type="submit" value="Submit">
</form>
</div>
<iframe id="myframe" name="myframe"></iframe>
<script>
var myframe = document.getElementById("myframe");
myframe.onload = function() {
var iframeDocument = myframe.contentDocument || myframe.contentWindow.document; // get access to DOM inside the iframe
var content = iframeDocument.textContent || iframeDocument.body.textContent; // get text of iframe
var json = JSON.parse(content);
if (json && json.guess) {
// process the json here
alert(json.guess);
}
}
</script>

Send HTTP Post request to a server with a specified CSRF token

Explanation:
I am trying to create a CSRF POC, but the problem is that a CSRF-token is required on www.example.com in order to prevent CSRF attacks.
Luckily, I managed to create a CSRF-Token that is always valid; lets say "abcdef". So now I can create a working CSRF POC if only I could send the CSRF-Token with it.
Is this possible with for instance AJAX? I searched for half an hour but couldn't find any answers on this, but that's on me I guess.
This is my POC until now:
<form action="http://www.example.com/change-mail" method="post">
<input type="submit">
<input type="hidden" name="email" value="newemail#gmail.com">
<!-- TODO: Send the CSRF-Token "abcdef" with it too! -->
</form>
Help is appreciated.
Edit #Daniƫl
Would something like this work?
HTML Part:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<b>Email</b><br><br>
<form id="email">
<label for="email"> Email : </label>
<input type="text" id="email" />
<br><br>
<input type="button" id="email" value="email"/>
</form>
</body>
</html>
Javascript PART:
<script>
window.addEventListener('DOMContentLoaded', function() {
var email = document.querySelector('input#email');
email.addEventListener('click', function() {
var emailStr = email.value,
url="http://www.example.com/change-mail";
if (window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttpReq.open('POST', url, true);
xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttpReq.setRequestHeader('X-CSRF-Token', abcdef);
xmlHttpReq.send("email="+emailStr);
</script>
Thanks in advance, do I have to handle the response too?
Right now, when I hit the email button, nothing happens when I log the HTTP requests... too bad.
There are a number of issues with your current code, I have corrected it below.
window.addEventListener('DOMContentLoaded', function() {
var email = document.querySelector('input#submit');
email.addEventListener('click', function() {
var emailStr = email.value,
url="http://www.example.com/change-mail";
if (window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttpReq.open('POST', url, true);
xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttpReq.setRequestHeader('X-CSRF-Token', 'abcdef');
xmlHttpReq.send("email="+emailStr);
});
});
<!DOCTYPE html>
<html>
<body>
<b>Email</b><br><br>
<form id="emailform">
<label for="email"> Email : </label>
<input type="text" id="email" />
<br><br>
<input type="button" id="submit" value="email"/>
</form>
</body>
</html>
ORIGINAL ANSWER:
You can add a header to your XMLHttpRequest (ajax) call:
xhr.setRequestHeader('X-CSRF-Token', csrf_token);

preventDefault and JSONP

We have a form that should post data to an external domain. We are aware of the cross-domain limitations, therefore we want to use JSONP.
All parts are working fine, except for the part that should prevent a default form submission that reloads the page. Below is the form.
The html page:
<html lang="en">
<head>
<meta charset="utf-8">
<title>test</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://gateway.wildfx.com/test.js"></script>
</head>
<body>
<form method="POST" id="wild">
<fieldset>
<label for="email">Your email:</label>
<input type="text" name="email" id="wild">
<p class="wild_err">invalid</p>
<p>
<input type="hidden" id="wild_v" name="v" value="test2">
<input type="hidden" id="wild_l" name="l" value="">
<input type="hidden" id="wild_i" name="i" value="identifier">
<input type="hidden" id="wild_s" name="s" value="10612">
<input type="submit" id="wild_button" value="Check">
</p>
</fieldset>
</form>
</body>
</html>
Below is the Javascript. However, if the wild form is submitted, the page reloads instead of transfering the data with JSONp. In addition even the submission2 log isn't logged.
If tried to replace the .submit() with .click for the from button with correct ID but it isn't working either. What is wrong with the script?
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
console.log('submission1');
$("#wild").submit(function(e) {
console.log('submission2');
e.preventDefault();
if (isValidEmailAddress(e["e"])) {
var e = {};
e["e"] = $("#wild_email").val();
e["v"] = $("#wild_v").val();
e["i"] = $("#wild_i").val();
e["s"] = $("#wild_s").val();
e["l"] = $("#wild_l").val();
(function() {
var wildAPI = "https://gateway.wildfx.com/testjsonp.php?jsoncallback=?";
$.getJSON( wildAPI, {
tagmode: e,
format: "json"
})
.done(function( data ) {
$(".wild_message_container").text('Success. you are in');
setTimeout(function() {
$("#wildnotifier-container").hide();
$("#wildnotifier-overlay").hide();
}, 5000);
});
})();
} else {
$(".wild_error").show();
$("#wild_email").addClass("wild_input_error");
}
});
You load jQuery
You load your script
Your script tries to add an event handler to the form
You add the form to your page
Step 3 fails because the form doesn't exist. Move the script so it is after the form. (Or put it in a function and call it with the DOM is ready).

Categories

Resources