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

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.

Related

How to get and send values from html <textarea> to a PHP page?

I created a form for image uploading. This form also includes a tag to add information about the image being uploaded. I need the text from the tag to be sent over to a page "savetofile.php" whenever 'Upload' button is clicked.
Currently the picture uploading works, the picture information is sent correctly, but I can't get the text from the tag on the "savetofile.php" page.
Form
<form action="savetofile.php" enctype="multipart/form-data" id="form1" method="post">
<div>
<label for="fileToUpload">Take or select photo(s)</label><br/>
<input accept="image/*" capture id="fileToUpload" name="fileToUpload" onchange="fileSelected();"
type="file"/>
</div>
<div>
<br><br>
<label for="notes">Notes:</label>
<textarea cols="50" id="notes" maxlength="2000" name="notes" placeholder="Please enter any additional information here"
rows="4" onchange="this.form.submit()"></textarea>
<br><br>
</div>
<div id="details"></div>
<div>
<input onclick="uploadFile()" type="button" value="Upload"/>
</div>
<div id="progress"></div>
</form>
savetofile.php
$text = $_POST['notes'];
_log('text: ' .$text);
uploadFile()
function uploadFile() {
var fd = new FormData();
var count = document.getElementById('fileToUpload').files.length;
for (var index = 0; index < count; index++) {
var file = document.getElementById('fileToUpload').files[index];
fd.append('myFile', file);
}
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", "savetofile.php");
xhr.send(fd);
}
Current output:
Undefined index: notes...
text:
Seems like you haven't append notes field value. Add this after for loop,
fd.append('notes', document.getElementById('notes').value);

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>

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

Required Field without Submit button after Ajax

I am trying to have my all my text/email input forms have a required attribute before you can "Submit" The email
But since I am using some Ajax to keep the page from refreshing after pressing the button the required attribute will not work.
This is why I am asking for an alternative for required with Javascript or jQuery (trying to prevent email form spam).
HTML (FORM)
<form id="contact">
<div class="form-group">
<label for="name">Voornaam*</label>
<input name="fn" type="text" class="form-control" id="fn" required>
</div>
<div class="form-group">
<label for="name">Achternaam*</label>
<input name="ln" type="text" class="form-control" id="ln" required>
</div>
<div class="form-group">
<label for="email">Email-address*</label>
<input name="email" type="email" class="form-control" id="email" required>
</div>
<div class="form-group">
<label for="message">Bericht*</label>
<textarea name="message" required class="form-control" id="message" rows="6"></textarea>
</div>
<button type="button" onClick="doIets(); this.form.reset();"
name="submit" id="submit" class="btn btn-primary">Verstuur <span id="result"></span></button>
<div id="result2"></div>
</form>
Ajax script
<script type="text/javascript">
function doIets()
{
console.log("doe iets");
var data = {
ck: (new Date()).getTime(),
fn: $("#fn").val(),
ln: $("#ln").val(),
email: $("#email").val(),
message: $("#message").val()
};
$.ajax({
type: "POST",
url: "sendmail.php",/*php file path*/
data: data,
beforeSend: function(){
$('#result').html('<img src="loader" style="height:10px;"/>')
},
success: function(data){
$('#result').hide();
$('#result2').html(data);
}
});
}
</script>
You will need to use e.preventDefault() when they click on the submit button and then validate the form and after that submit it using the ajax call you created above.
since you already read out the data, you can check whether your message is long enough for you via
data.message.length
if it is 0 (or lower than a threshold you defined), you can skip the ajax call and return some info to the user.
You might also want to trim the message first in order to be sure there aren't only whitespace in there.
Here is part from my code, where I bind the submit event to my form and check by looping if any required field is empty or if I want to do any such thing.
This way may help you--
$('.form .contact-form').submit(function(e) {
e.preventDefault();
$('.form .message').eq(0).html("<i>Sending... Please Wait...</i>");
var form = $(this);
var validated = true;
$('input[type="text"]',this).each(function(){
if($(this).val().length < 1){
$(this).addClass('error').focus();
validated = false;
return false;
}
});
if(validated === true){
$.post(__asyn.ajaxurl, $('.form form').eq(0).serialize(), function(data, textStatus, xhr) {
console.log(data);
});
}
});
Just pass the event object to your handler onClick="doIets(event);
and then add
function doIets(event) {
event.preventDefault();
...
}

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