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');
});
Related
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.
I'm using a super basic google form on my website. I'm using this website to extract the HTML to display it on my website - http://stefano.brilli.me/google-forms-html-exporter/
Once I hit submit, nothing happens. The page is just locked. I'm trying to resubmit it to another page. Here is my code
<div class="row">
<form action="https://docs.google.com/forms/d/e/1FAIpQLSfJQ9EkDN8aggSL9AEB2PK4BGiZgBzLDbS1IPppfSkU1zy-oA/formResponse"target="_self" id="bootstrapForm" method="POST">
<div class="col-sm-6 col-md-3">
<input id="679075295" type="text" name="entry.679075295" class="form-control" >
</div>
<div class="col-sm-6 col-md-3">
<input id="897968244" type="text" name="entry.897968244" class="form-control" >
</div>
<div class="col-sm-6 col-md-3">
<input id="685661947" type="text" name="entry.685661947" class="form-control" >
</div>
<input id="503500083" type="hidden" name="entry.503500083" value="<%= #investment.id %>" >
<div class="col-sm-6 col-md-3">
<button type="submit" value"submit" class="btn btn--primary type--uppercase" >Get Started</button>
</div>
</form>
Here is the ajax script
<script>
$('#bootstrapForm').submit(function (event) {
event.preventDefault()
var extraData = {}
$('#bootstrapForm').ajaxSubmit({
data: extraData,
dataType: 'jsonp', // This won't really work. It's just to use a GET instead of a POST to allow cookies from different domain.
error: function () {
// Submit of form should be successful but JSONP callback will fail because Google Forms
// does not support it, so this is handled as a failure.
alert('Form Submitted. Thanks.')
// You can also redirect the user to a custom thank-you page:
window.location = 'http://reif.com.au/thankyou'
}
})
})
</script>
</div>
Feeling a little silly on this one. Essentially i didn't copy over all of the scripts. I was rushing through.. ALWAYS number 1 error!
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.2.2/jquery.form.min.js" integrity="sha256-2Pjr1OlpZMY6qesJM68t2v39t+lMLvxwpa8QlRjJroA=" crossorigin="anonymous"></script>
This is what i needed to add, it now successfully submits and redirects!
I've looked at several existing questions on here already. They're all for submitting post requests, but the mechanics should be the same for get requests, so I modified my code to work for get requests. But it's not working correctly.
What's wrong: I submit a form, but the page continues to reload (right now it's redirecting to a new page with the json data.
What I want to do: Submit a form, prevent it from reloading, and display the json data on the same html page
<div class="row">
<div class="col-md-3">
<form method="GET" action="/search">
<div class="form-group">
<input type="text" class="form-control" id="term" name="term" placeholder="Find">
<br>
<input type="text" class="form-control" id="location" name="location" placeholder="Near">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</div>
<script>
$(function() {
$('form').submit(function(event) {
event.preventDefault();
var $this = $(this);
$.get($this.attr('action'), function(data) {
$('pre').text(data);
});
});
});
</script>
And in my express code, I have this:
app.get('/search', function(req, res) {
var apiUrl = getApiUrl(req.query);
var apiData = getApiData(apiUrl, function(statusCode, data) {
// console.log(data);
// res.render('api-guide', data);
res.send(data);
});
});
I should note, I'm using handlebars for templating. So the form is in its own template, while the jquery script is in the main template. Would this be why it's not working as expected?
Can someone please help me?
You are setting an action parameter in your form that is conflicting with your AJAX request. If you remove
action="/search"
and set the path directly in your AJAX request
$.get('/search', function(data) {
$('pre').text(data);
});
from your form declaration, it should work as you expect.
I have a lot of buttons, each opens its form . How do I get the input value of form opened at the moment, and post it on my server, like post("/addOrders", valueOfinputs)?
https://jsfiddle.net/ave6uvez/21/
<div class="rows">
<div class="row">
<button class="open">Buy</button>
<form id="myform" action="/index" method="post">
<div class="form-group">
<label for="exampleInputEmail1">Name</label>
<input type="namee" name ="name" >
</div>
<div class="form-group">
<label for="exampleInputPassword1">Phone</label>
<input type="phone" name = "phone" >
</div>
<button class="ave" >Close</button>
<INPUT type="submit" id = "submit" class = "close" value="Submit">
<!---- <button id="submit" class="close"></button>-->
</form>
</div>
</div>
try this,
$("#submit").click(function(e){
$.post("/addOrders",$("#myForm").serialize());
return null;
})
.serialize() will put all form elements data into the request
Also you need to give different id for different Forms submit button and you have to do the above code for each submit button
Hope this works for you.
This is a simple reference:
// this is the id of the forms, set the form ids accordingly.
$("#idForm").submit(function(e) {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
I am very new to jQuery and I'm looking for an explanation as to why this code does not seem to work. I think it is something with the "action" not sure. Can someone help me understand my mistake here. thanks
<script src="/jquery.validationEngine.js"></script>
<script>
$("#contact_body").submit(function(e) {
e.preventDefault(); // Prevents the page from refreshing
var $this = $(this); // `this` refers to the current form element
if ($("#contact_body").validationEngine('validate')) {
//Post Data to Node Server
$.post(
$this.attr("action"), // Gets the URL to sent the post to
$this.serialize(), // Serializes form data in standard format
function(data) { /** code to handle response **/ },
"json" // The format the response should be in
);
//Notify User That the Email Was Sent to the Server & Thanks!
//$('#contactThanksModal').modal('show');
$('#contactModal').modal('hide');
alert("success");
}
else {
//handle Invalid Email Format Error
alert("error");
}
});
</script>
<!--pop up contact form -->
<div id="contact" class="modal hide fade in" style="display: none;">
<div class="modal-header">
<a class="close" data-dismiss="modal">x</a>
<h3>Send us a message</h3>
</div>
<div class="modal-body">
<form id="contact_body"class="contact_body" name="contact_body" action="/contact">
<label class="label" for="form_name">Your Name</label><br>
<input type="text" name="form_name" id="form_name" class="input-xlarge"><br>
<label class="label" for="form_email">Your E-mail</label><br>
<input type="form_email" name="form_email" class="input-xlarge"><br>
<label class="label" for="form_msg">Enter a Message</label><br>
<textarea name="form_msg" class="input-xlarge"></textarea>
</form>
</div>
<div class="modal-footer">
<input class="btn btn-success" type="submit" value="Send!" id="submit">
Nah.
</div>
<!-- <div id="thanks"><p><a data-toggle="modal" href="#contact" class="btn btn-primary btn-large">Modal powers, activate!</a></p></div> -->
You need to wrap your JQuery scripts in a
$(document).ready(function() {
...your_code_here...
});
This will then wait for the whole document to load before trying to attach events to objects.
Without this you may be trying to bind events to objects that have yet to be "created".
You need to put your code in a document ready handler:
<script src="/jquery.validationEngine.js"></script>
<script>
$(function() {
$("#contact_body").submit(function(e) {
// your code...
});
});
</script>
Your code is currently trying to add the submit() handler before the element exists in the DOM.