Submit a form and get a JSON response without jQuery - javascript

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>

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.

Getting error while submit form with ajax

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 ...
})

Redirect page after form submitting a form

<body onload="document.action.submit()">
<form name="action" method="post" action="https://en.educaplay.com/en/registrar.php" >
<input type="hidden" name="action" value='loginTicket'>
<input name="ticket" type="text" id="ticket" value="<%= session[:educa_key] %>">
<input type="submit" name="entrar" id="entrar2" value="Sign in" class="btn">
</form>
Now, I want to redirect the submitter to any page of my choice after the form data has been submitted, but the action resides on another website where I cannot edit. Is it possible to redirect the user to any page after he has submitted the data to that site? I have checked a number of suggestions but not sucess at this point. thanks in advance
If you do not have to wait for the answer, you can use javascript (jquery if you want and can) for this:
$("#entrar2").click(function(){
$(location).href(link);
});
In your registar.php file, add header('Location: https://www.example.com/example.html');
This isn't necessarily JavaScript, but it's probably the most efficient method.
When you submit a form, there will be an automatic browser redirection to the URL you specified in the action attribute of your form. Here is a minimal example:
<form action="http://stackoverflow.com">
<input type="text">
<input type="submit" value="Submit">
</form>
Now, if you want to code a form properly, you should follow the Post/Redirect/Get pattern. Ajax is a viable solution for what you want to do:
(function () {
// Dummy submit handler
function handler() {
var xhr = new XMLHttpRequest(),
url = "action.php",
params = "foo=Foo&bar=Bar";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
location.href = "http://stackoverflow.com";
}
}
xhr.send(params);
}
})();
You have to send your data to other website using curl before form submitted.Where you can process your data or store it . And after successful response from other page you can redirect user to any page
Your submission will cancel the redirect.
<form name="form1" id="form1" method="post" onsubmit="return redirect()">
<input type="submit" class="button4" name="order" id="order" value="Place Order" >
</form>
<script>
function redirect() {
window.location.replace("login.php");
return false;
}
</script>
OR
document.getElementById("formId").onsubmit=function() {
window.location.replace("https://jsfiddle.net/");
return false;
}

Form validation with JavaScript using XHR

I'm fairly new to JavaScript, I've been using tutorials online but they seem to often validate with php and use JavaScript for warnings, the application I'm making users xhr to post the data to the server, but before this I want to have JavaScript complete some validations. Then I'll re validate with the PHP.
Here is the form code
<form id="booking" action="">
<span class="red">*</span>First Name:
<input type="text" name="firstName" id="firstName">
<br>
<span class="red">*</span>Last Name:
<input type="text" name="lastName" id="lastName">
<br>
<span class="red">*</span>Contact Number:
<input type="text" name="number" id="number">
<br>
Unit Number(optional):
<input type="text" name="unit" id="unit">
<br>
<span class="red">*</span>Street Number:
<input type="text" name="streetNumber" id="streetNumber">
<br>
<span class="red">*</span>Street Name:
<input type="text" name="streetName" id="streetName">
<br>
<span class="red">*</span>Suburb:
<input type="text" name="pickupSuburb" id="pickupSuburb">
<br>
Destination Suburb<span class="red">*</span>:
<input type="text" name="destinationSuburb" id="destinationSuburb">
<br>
Pick-Up Date and Time<span class="red">*</span>:
<input type="datetime-local" name="dateTime" id="dateTime">
<br>
<br>
<input type="button" value="Submit"
onclick="getData('bookingprocess.php','message', firstName.value, lastName.value, number.value, unit.value, streetNumber.value, streetName.value, pickupSuburb.value, destinationSuburb.value, dateTime.value)"/>
<input type="reset" value="Reset">
</form>
<div id="message">
</div>
I've created a div for the warning messages.
Here is the JavaScript
// file simpleajax.js
var xhr = createRequest();
function getData(dataSource, divID, firstName, lastName, number, unit, streetNumber, streetName, pickupSuburb, destinationSuburb, dateTime) {
if(xhr) {
var place = document.getElementById(divID);
var requestbody = "firstName="+encodeURIComponent(firstName)+"&lastName="+encodeURIComponent(lastName)+"&number="+encodeURIComponent(number)+"&unit="+encodeURIComponent(unit)+"&streetNumber="+encodeURIComponent(streetNumber)+"&streetName="+encodeURIComponent(streetName)+"&pickupSuburb="+encodeURIComponent(pickupSuburb)+"&destinationSuburb="+encodeURIComponent(destinationSuburb)+"&dateTime="+encodeURIComponent(dateTime);
xhr.open("POST", dataSource, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
place.innerHTML = xhr.responseText;
} // end if
} // end anonymous call-back function
xhr.send(requestbody);
} // end if
} // end function getData()
function checkForm(booking) {
var valid = true;
if(firstName.value.length <= 0) {
window.alert("Name is empty");
booking.firstName.focus();
return valid = false;
}
}
Note there will be more validations, my question is how can I call the validations from the form, or directly from the XHR, which is the best practice? I understand the call to the XHR from the form could be considered bad practice as well as I've hard coded all the values?
Getting this to work has been quite troublesome, so apologies if its a little Hodge podge.
Validating while the form is filled (when the cursor leaves a field) makes more sense since you can add some hints to user. Like, if a user enters an email, you check if it contains # and it doesn't, it's much more user-friendly to notify them that something's wrong with their email input (in contrast, they may send the form, you validate it then and tell them the form is not ok, but then they have to fill the form again, which is sort of frustrating).
Try
<input type="text" onblur="alert('out!');" />
This fires when the input loses focus. Now, you may wonder how to use functions defined elsewhere in such handling. That can be done, for instance, like this:
JS:
window.myHandler = function(input,event) { ... };
HTML:
<input type="text" onblur="window.myHandler(input,event);" />
Note that in HTML onblur attribute event is a "pre-defined" variable that contains the Event object "instance", but for elder versions of IE, you should use
window.myHandler = function(input,event) {
event = event || window.event; // elder IE store the Event object in window.event
// input is your DOM element. You can use input.value to get the value
// or this.classList to add some class which indicates (via CSS) that the input is wrong
...
};

Strange issue with Ajax file upload (jQuery, ASP.Net MVC)

On several pages of my web site (ASP.Net MVC, jQuery, KendoUI SPA), I have a modal window to upload a file.
addAttachment: function (e) {
$("form").on("submit", function (event) {
event.preventDefault();
});
e.preventDefault();
var formData = new FormData($("#formUpload")[0]);
var url = 'api/Attachments/UploadAttachment';
app.postFile(url, formData, function (statusCode) {
if (statusCode === 201) {
// File was created -- do stuff
}
});
},
<div id="addAttachmentWindow"
data-role="window"
data-height="300px"
data-width="600px"
data-modal="true"
data-title="Add Attachment"
data-visible="false">
<div class="row">
<form id="formUpload" class="form-horizontal">
<input type="hidden" id="hdnRecordId" name="recordId" data-bind="value: object.id" />
<div class="form-group">
<label class="col-sm-4 control-label" for="txtDocumentTitle">Title</label>
<div class="col-sm-6">
<input name="documentTitle" id="txtDocumentTitle" type="text" class="k-textbox" />
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="fuFileInput">Document</label>
<div class="col-sm-6">
<input id="fuFileInput" name="files" type="file" />
</div>
</div>
<div class="col-sm-6 col-sm-offset-6">
<button data-role="button" data-icon="plus" data-bind="click: addAttachment">Add Attachment</button>
</div>
</form>
</div>
</div>
With the code for postFile
var postFile = function(uri, formData, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
callback(xhr.status);
}
};
xhr.open('POST', uri);
xhr.setRequestHeader("RequestVerificationToken", antiForgeryToken);
xhr.send(formData);
};
Most of the pages, this works fine, But on a couple of pages, it will issue the POST, without the form fields and immediately issue a GET for
/?recordId=1&documentTitle=documentTitleInput&files=FileNameHere.pdf
which goes to the Home Controller's Index function. If I go to one of the pages with this issue, do a Shift-Reload, and try the upload it will work as expected, the form fields are intact, and the callback is called.
Issues
Why the GET is being issued with the form fields in the query string immediately following the initial POST (even before the POST returns a response)
Why the form fields are empty, unless I do a shift-reload on some of pages, whilethe same code works fine on other pages.
I've tried creating an empty FormData, and appending the values to it, and played everything I can find to stop the normal submit event from happening (e.preventDefault(), e.stopPropogation(), return false etc.);
ok so some reading on the subject and its because the prevent default only works on elements, not on a form submit event, which is what your using...
create two submit inputs... one a button, the other a hidden input.. like so ..
<button type="button" id="submit">Submit</button>
<input style="display: none;" type="submit" id="realsubmit">
then do your jquery like so ...
$("#submit").on('click', function() {
//do stuff
$("#realsubmit").trigger('click');
});

Categories

Resources