JavaScript Multiple Forms [duplicate] - javascript

If I have a form like this,
<form action="/Car/Edit/17" id="myForm" method="post" name="myForm"> ... </form>
how can I submit it without redirecting to another view by JavaScript/jQuery?
I read plenty of answers from Stack Overflow, but all of them redirect me to the view returned by the POST function.

You can achieve that by redirecting the form's action to an invisible <iframe>. It doesn't require any JavaScript or any other type of scripts.
<iframe name="dummyframe" id="dummyframe" style="display: none;"></iframe>
<form action="submitscript.php" target="dummyframe">
<!-- Form body here -->
</form>

In order to achieve what you want, you need to use jQuery Ajax as below:
$('#myForm').submit(function(e){
e.preventDefault();
$.ajax({
url: '/Car/Edit/17/',
type: 'post',
data:$('#myForm').serialize(),
success:function(){
// Whatever you want to do after the form is successfully submitted
}
});
});
Also try this one:
function SubForm(e){
e.preventDefault();
var url = $(this).closest('form').attr('action'),
data = $(this).closest('form').serialize();
$.ajax({
url: url,
type: 'post',
data: data,
success: function(){
// Whatever you want to do after the form is successfully submitted
}
});
}
Final solution
This worked flawlessly. I call this function from Html.ActionLink(...)
function SubForm (){
$.ajax({
url: '/Person/Edit/#Model.Id/',
type: 'post',
data: $('#myForm').serialize(),
success: function(){
alert("worked");
}
});
}

Since all current answers use jQuery or tricks with iframe, figured there is no harm to add method with just plain JavaScript:
function formSubmit(event) {
var url = "/post/url/here";
var request = new XMLHttpRequest();
request.open('POST', url, true);
request.onload = function() { // request successful
// we can use server response to our request now
console.log(request.responseText);
};
request.onerror = function() {
// request failed
};
request.send(new FormData(event.target)); // create FormData from form that triggered event
event.preventDefault();
}
// and you can attach form submit event like this for example
function attachFormSubmitEvent(formId){
document.getElementById(formId).addEventListener("submit", formSubmit);
}

Place a hidden iFrame at the bottom of your page and target it in your form:
<iframe name="hiddenFrame" width="0" height="0" border="0" style="display: none;"></iframe>
<form action="/Car/Edit/17" id="myForm" method="post" name="myForm" target="hiddenFrame"> ... </form>
Quick and easy. Keep in mind that while the target attribute is still widely supported (and supported in HTML5), it was deprecated in HTML 4.01.
So you really should be using Ajax to future-proof.

Okay, I'm not going to tell you a magical way of doing it because there isn't.
If you have an action attribute set for a form element, it will redirect.
If you don't want it to redirect simply don't set any action and set onsubmit="someFunction();"
In your someFunction() you do whatever you want, (with AJAX or not) and in the ending, you add return false; to tell the browser not to submit the form...

One-liner solution as of 2020, if your data is not meant to be sent as multipart/form-data or application/x-www-form-urlencoded:
<form onsubmit='return false'>
<!-- ... -->
</form>

You need Ajax to make it happen. Something like this:
$(document).ready(function(){
$("#myform").on('submit', function(){
var name = $("#name").val();
var email = $("#email").val();
var password = $("#password").val();
var contact = $("#contact").val();
var dataString = 'name1=' + name + '&email1=' + email + '&password1=' + password + '&contact1=' + contact;
if(name=='' || email=='' || password=='' || contact=='')
{
alert("Please fill in all fields");
}
else
{
// Ajax code to submit form.
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});

See jQuery's post function.
I would create a button, and set an onClickListener ($('#button').on('click', function(){});), and send the data in the function.
Also, see the preventDefault function, of jQuery!

The desired effect can also be achieved by moving the submit button outside of the form as described here:
Prevent page reload and redirect on form submit ajax/jquery
Like this:
<form id="getPatientsForm">
Enter URL for patient server
<br/><br/>
<input name="forwardToUrl" type="hidden" value="/WEB-INF/jsp/patient/patientList.jsp" />
<input name="patientRootUrl" size="100"></input>
<br/><br/>
</form>
<button onclick="javascript:postGetPatientsForm();">Connect to Server</button>

Using this snippet, you can submit the form and avoid redirection. Instead you can pass the success function as argument and do whatever you want.
function submitForm(form, successFn){
if (form.getAttribute("id") != '' || form.getAttribute("id") != null){
var id = form.getAttribute("id");
} else {
console.log("Form id attribute was not set; the form cannot be serialized");
}
$.ajax({
type: form.method,
url: form.action,
data: $(id).serializeArray(),
dataType: "json",
success: successFn,
//error: errorFn(data)
});
}
And then just do:
var formElement = document.getElementById("yourForm");
submitForm(formElement, function() {
console.log("Form submitted");
});

Fire and forget vanilla js + svelte
function handleSubmit(e) {
const request = new Request(`/products/${item.ItemCode}?_method=PUT`, {
method: 'POST',
body: new FormData(e.target),
});
fetch(request)
}
Used in Svelte:
<form method="post" on:submit|preventDefault={handleSubmit}>

If you control the back end, then use something like response.redirect instead of response.send.
You can create custom HTML pages for this or just redirect to something you already have.
In Express.js:
const handler = (req, res) => {
const { body } = req
handleResponse(body)
.then(data => {
console.log(data)
res.redirect('https://yoursite.com/ok.html')
})
.catch(err => {
console.log(err)
res.redirect('https://yoursite.com/err.html')
})
}
...
app.post('/endpoint', handler)

Related

How to disable redirection to the url specified in the form action attribute on form submitting

I have a form with the action attribute set to "/tasks/". All I want is that on submitting the form, the data go to "/tasks/", but the user is not redirected to "/tasks/", they just stay on "/" instead. Is it possible to achieve?
I tried to add "return false" and "preventDefault" to the "onclick" handler, but that's not what I need as they cancel the form submission.
<form id="add-task-form" method="POST" name="add-task-form" action="/tasks/" enctype="multipart/form-data">
<label for="name" class="field-description">*Name</label>
<input id="name" type="text"required name="name" autofocus="true"><br>
<label for="description-text" class="field-description">*Description</label>
<textarea id="description-text" name="description"></textarea><br>
<button type="submit" id="save-button" class="saveButton"><span>Add task</span></button>
</form>
$('#save-button').on( 'click', function(){
if($('input').data().length() != 0){
var data = $('#add-task-form form').serialize();
$.ajax({
method: "POST",
url: '/tasks/',
data: data,
success: function(response){
$('#add-task-form').css('display', 'none');
var task = {};
task.id = response;
var dataArray = $('#add-task-form form').serializeArray();
for(i in dataArray) {
task[dataArray[i]['name']] = dataArray[i]['value'];
}
appendTask(task);
getTasksCount();
}
});
return false;
$('#home-page').show();
$('#add-task-page').remove();
};
})
I'm new to js and jQuery and they are definitely not my strongest points, so please, advice.
It's shall work like this :
$('#save-button').click(function(event) {
event.preventDefault();
...
});
to know more about it : https://api.jquery.com/event.preventdefault/
You can do something like this.
$(document).ready(function(){
var $form = $('form');
$form.submit(function(){
$.post($(this).attr('action','/tasks/'), $(this).serialize(), function(response){
// Do something
},'json');
return false;
});
});
quotation
if you want to prevent it all, you can use event.preventDefault(). But since you are using ajax and you don't want to reload the page, you can try to apply this code:
$("#save-button").click(function(){
$.post('{post_url}',
$("#add-task-form form").serializeArray(),
function(data){
if (data.success){
redirect = '{last}';
} else {
reload(true);
}
},"json"
);
});

Submit form array fields using Ajax [duplicate]

I have a form with name orderproductForm and an undefined number of inputs.
I want to do some kind of jQuery.get or ajax or anything like that that would call a page through Ajax, and send along all the inputs of the form orderproductForm.
I suppose one way would be to do something like
jQuery.get("myurl",
{action : document.orderproductForm.action.value,
cartproductid : document.orderproductForm.cartproductid.value,
productid : document.orderproductForm.productid.value,
...
However I do not know exactly all the form inputs. Is there a feature, function or something that would just send ALL the form inputs?
This is a simple reference:
// this is the id of the form
$("#idForm").submit(function(e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
var actionUrl = form.attr('action');
$.ajax({
type: "POST",
url: actionUrl,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
});
You can use the ajaxForm/ajaxSubmit functions from Ajax Form Plugin or the jQuery serialize function.
AjaxForm:
$("#theForm").ajaxForm({url: 'server.php', type: 'post'})
or
$("#theForm").ajaxSubmit({url: 'server.php', type: 'post'})
ajaxForm will send when the submit button is pressed. ajaxSubmit sends immediately.
Serialize:
$.get('server.php?' + $('#theForm').serialize())
$.post('server.php', $('#theForm').serialize())
AJAX serialization documentation is here.
Another similar solution using attributes defined on the form element:
<form id="contactForm1" action="/your_url" method="post">
<!-- Form input fields here (do not forget your name attributes). -->
</form>
<script type="text/javascript">
var frm = $('#contactForm1');
frm.submit(function (e) {
e.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
console.log('Submission was successful.');
console.log(data);
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
});
});
</script>
There are a few things you need to bear in mind.
1. There are several ways to submit a form
using the submit button
by pressing enter
by triggering a submit event in JavaScript
possibly more depending on the device or future device.
We should therefore bind to the form submit event, not the button click event. This will ensure our code works on all devices and assistive technologies now and in the future.
2. Hijax
The user may not have JavaScript enabled. A hijax pattern is good here, where we gently take control of the form using JavaScript, but leave it submittable if JavaScript fails.
We should pull the URL and method from the form, so if the HTML changes, we don't need to update the JavaScript.
3. Unobtrusive JavaScript
Using event.preventDefault() instead of return false is good practice as it allows the event to bubble up. This lets other scripts tie into the event, for example analytics scripts which may be monitoring user interactions.
Speed
We should ideally use an external script, rather than inserting our script inline. We can link to this in the head section of the page using a script tag, or link to it at the bottom of the page for speed. The script should quietly enhance the user experience, not get in the way.
Code
Assuming you agree with all the above, and you want to catch the submit event, and handle it via AJAX (a hijax pattern), you could do something like this:
$(function() {
$('form.my_form').submit(function(event) {
event.preventDefault(); // Prevent the form from submitting via the browser
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()
}).done(function(data) {
// Optionally alert the user of success here...
}).fail(function(data) {
// Optionally alert the user of an error here...
});
});
});
You can manually trigger a form submission whenever you like via JavaScript using something like:
$(function() {
$('form.my_form').trigger('submit');
});
Edit:
I recently had to do this and ended up writing a plugin.
(function($) {
$.fn.autosubmit = function() {
this.submit(function(event) {
event.preventDefault();
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()
}).done(function(data) {
// Optionally alert the user of success here...
}).fail(function(data) {
// Optionally alert the user of an error here...
});
});
return this;
}
})(jQuery)
Add a data-autosubmit attribute to your form tag and you can then do this:
HTML
<form action="/blah" method="post" data-autosubmit>
<!-- Form goes here -->
</form>
JS
$(function() {
$('form[data-autosubmit]').autosubmit();
});
You can also use FormData (But not available in IE):
var formData = new FormData(document.getElementsByName('yourForm')[0]);// yourForm: form selector
$.ajax({
type: "POST",
url: "yourURL",// where you wanna post
data: formData,
processData: false,
contentType: false,
error: function(jqXHR, textStatus, errorMessage) {
console.log(errorMessage); // Optional
},
success: function(data) {console.log(data)}
});
This is how you use FormData.
Simple version (does not send images)
<form action="/my/ajax/url" class="my-form">
...
</form>
<script>
(function($){
$("body").on("submit", ".my-form", function(e){
e.preventDefault();
var form = $(e.target);
$.post( form.attr("action"), form.serialize(), function(res){
console.log(res);
});
});
)(jQuery);
</script>
Copy and paste ajaxification of a form or all forms on a page
It is a modified version of Alfrekjv's answer
It will work with jQuery >= 1.3.2
You can run this before the document is ready
You can remove and re-add the form and it will still work
It will post to the same location as the normal form, specified in
the form's "action" attribute
JavaScript
jQuery(document).submit(function(e){
var form = jQuery(e.target);
if(form.is("#form-id")){ // check if this is the form that you want (delete this check to apply this to all forms)
e.preventDefault();
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: form.serialize(), // serializes the form's elements.
success: function(data) {
console.log(data); // show response from the php script. (use the developer toolbar console, firefox firebug or chrome inspector console)
}
});
}
});
I wanted to edit Alfrekjv's answer but deviated too much from it so decided to post this as a separate answer.
Does not send files, does not support buttons, for example clicking a button (including a submit button) sends its value as form data, but because this is an ajax request the button click will not be sent.
To support buttons you can capture the actual button click instead of the submit.
jQuery(document).click(function(e){
var self = jQuery(e.target);
if(self.is("#form-id input[type=submit], #form-id input[type=button], #form-id button")){
e.preventDefault();
var form = self.closest('form'), formdata = form.serialize();
//add the clicked button to the form data
if(self.attr('name')){
formdata += (formdata!=='')? '&':'';
formdata += self.attr('name') + '=' + ((self.is('button'))? self.html(): self.val());
}
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: formdata,
success: function(data) {
console.log(data);
}
});
}
});
On the server side you can detect an ajax request with this header that jquery sets HTTP_X_REQUESTED_WITH
for php
PHP
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
//is ajax
}
This code works even with file input
$(document).on("submit", "form", function(event)
{
event.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: $(this).attr("method"),
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
},
error: function (xhr, desc, err)
{
}
});
});
I really liked this answer by superluminary and especially the way he wrapped is solution in a jQuery plugin. So thanks to superluminary for a very useful answer. In my case, though, I wanted a plugin that would allow me to define the success and error event handlers by means of options when the plugin is initialized.
So here is what I came up with:
;(function(defaults, $, undefined) {
var getSubmitHandler = function(onsubmit, success, error) {
return function(event) {
if (typeof onsubmit === 'function') {
onsubmit.call(this, event);
}
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()
}).done(function() {
if (typeof success === 'function') {
success.apply(this, arguments);
}
}).fail(function() {
if (typeof error === 'function') {
error.apply(this, arguments);
}
});
event.preventDefault();
};
};
$.fn.extend({
// Usage:
// jQuery(selector).ajaxForm({
// onsubmit:function() {},
// success:function() {},
// error: function() {}
// });
ajaxForm : function(options) {
options = $.extend({}, defaults, options);
return $(this).each(function() {
$(this).submit(getSubmitHandler(options['onsubmit'], options['success'], options['error']));
});
}
});
})({}, jQuery);
This plugin allows me to very easily "ajaxify" html forms on the page and provide onsubmit, success and error event handlers for implementing feedback to the user of the status of the form submit. This allowed the plugin to be used as follows:
$('form').ajaxForm({
onsubmit: function(event) {
// User submitted the form
},
success: function(data, textStatus, jqXHR) {
// The form was successfully submitted
},
error: function(jqXHR, textStatus, errorThrown) {
// The submit action failed
}
});
Note that the success and error event handlers receive the same arguments that you would receive from the corresponding events of the jQuery ajax method.
I got the following for me:
formSubmit('#login-form', '/api/user/login', '/members/');
where
function formSubmit(form, url, target) {
$(form).submit(function(event) {
$.post(url, $(form).serialize())
.done(function(res) {
if (res.success) {
window.location = target;
}
else {
alert(res.error);
}
})
.fail(function(res) {
alert("Server Error: " + res.status + " " + res.statusText);
})
event.preventDefault();
});
}
This assumes the post to 'url' returns an ajax in the form of {success: false, error:'my Error to display'}
You can vary this as you like. Feel free to use that snippet.
jQuery AJAX submit form, is nothing but submit a form using form ID when you click on a button
Please follow steps
Step 1 - Form tag must have an ID field
<form method="post" class="form-horizontal" action="test/user/add" id="submitForm">
.....
</form>
Button which you are going to click
<button>Save</button>
Step 2 - submit event is in jQuery which helps to submit a form. in below code we are preparing JSON request from HTML element name.
$("#submitForm").submit(function(e) {
e.preventDefault();
var frm = $("#submitForm");
var data = {};
$.each(this, function(i, v){
var input = $(v);
data[input.attr("name")] = input.val();
delete data["undefined"];
});
$.ajax({
contentType:"application/json; charset=utf-8",
type:frm.attr("method"),
url:frm.attr("action"),
dataType:'json',
data:JSON.stringify(data),
success:function(data) {
alert(data.message);
}
});
});
for live demo click on below link
How to submit a Form using jQuery AJAX?
I know this is a jQuery related question, but now days with JS ES6 things are much easier. Since there is no pure javascript answer, I thought I could add a simple pure javascript solution to this, which in my opinion is much cleaner, by using the fetch() API. This a modern way to implements network requests. In your case, since you already have a form element we can simply use it to build our request.
const form = document.forms["orderproductForm"];
const formInputs = form.getElementsByTagName("input");
let formData = new FormData();
for (let input of formInputs) {
formData.append(input.name, input.value);
}
fetch(form.action,
{
method: form.method,
body: formData
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error.message))
.finally(() => console.log("Done"));
Try
fetch(form.action,{method:'post', body: new FormData(form)});
function send(e,form) {
fetch(form.action,{method:'post', body: new FormData(form)});
console.log('We submit form asynchronously (AJAX)');
e.preventDefault();
}
<form method="POST" action="myapi/send" onsubmit="send(event,this)" name="orderproductForm">
<input hidden name="csrfToken" value="$0meh#$h">
<input name="email" value="aa#bb.com">
<input name="phone" value="123-456-666">
<input type="submit">
</form>
Look on Chrome Console > Network after/before 'submit'
consider using closest
$('table+table form').closest('tr').filter(':not(:last-child)').submit(function (ev, frm) {
frm = $(ev.target).closest('form');
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert(data);
}
})
ev.preventDefault();
});
You may use this on submit function like below.
HTML Form
<form class="form" action="" method="post">
<input type="text" name="name" id="name" >
<textarea name="text" id="message" placeholder="Write something to us"> </textarea>
<input type="button" onclick="return formSubmit();" value="Send">
</form>
jQuery function:
<script>
function formSubmit(){
var name = document.getElementById("name").value;
var message = document.getElementById("message").value;
var dataString = 'name='+ name + '&message=' + message;
jQuery.ajax({
url: "submit.php",
data: dataString,
type: "POST",
success: function(data){
$("#myForm").html(data);
},
error: function (){}
});
return true;
}
</script>
For more details and sample Visit:
http://www.spiderscode.com/simple-ajax-contact-form/
To avoid multiple formdata sends:
Don't forget to unbind submit event, before the form submited again,
User can call sumbit function more than one time, maybe he forgot something, or was a validation error.
$("#idForm").unbind().submit( function(e) {
....
If you're using form.serialize() - you need to give each form element a name like this:
<input id="firstName" name="firstName" ...
And the form gets serialized like this:
firstName=Chris&lastName=Halcrow ...
I find it surprising that no one mentions data as an object. For me it's the cleanest and easiest way to pass data:
$('form#foo').submit(function () {
$.ajax({
url: 'http://foo.bar/some-ajax-script',
type: 'POST',
dataType: 'json',
data: {
'foo': 'some-foo-value',
'bar': $('#bar').val()
}
}).always(function (response) {
console.log(response);
});
return false;
});
Then, in the backend:
// Example in PHP
$_POST['foo'] // some-foo-value
$_POST['bar'] // value in #bar
This is not the answer to OP's question,
but in case if you can't use static form DOM, you can also try like this.
var $form = $('<form/>').append(
$('<input/>', {name: 'username'}).val('John Doe'),
$('<input/>', {name: 'user_id'}).val('john.1234')
);
$.ajax({
url: 'api/user/search',
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
data: $form.serialize(),
success: function(data, textStatus, jqXHR) {
console.info(data);
},
error: function(jqXHR, textStatus, errorThrown) {
var errorMessage = jqXHR.responseText;
if (errorMessage.length > 0) {
alert(errorMessage);
}
}
});
JavaScript
(function ($) {
var form= $('#add-form'),
input = $('#exampleFormControlTextarea1');
form.submit(function(event) {
event.preventDefault();
var req = $.ajax({
url: form.attr('action'),
type: 'POST',
data: form.serialize()
});
req.done(function(data) {
if (data === 'success') {
var li = $('<li class="list-group-item">'+ input.val() +'</li>');
li.hide()
.appendTo('.list-group')
.fadeIn();
$('input[type="text"],textarea').val('');
}
});
});
}(jQuery));
HTML
<ul class="list-group col-sm-6 float-left">
<?php
foreach ($data as $item) {
echo '<li class="list-group-item">'.$item.'</li>';
}
?>
</ul>
<form id="add-form" class="col-sm-6 float-right" action="_inc/add-new.php" method="post">
<p class="form-group">
<textarea class="form-control" name="message" id="exampleFormControlTextarea1" rows="3" placeholder="Is there something new?"></textarea>
</p>
<button type="submit" class="btn btn-danger">Add new item</button>
</form>
There's also the submit event, which can be triggered like this $("#form_id").submit(). You'd use this method if the form is well represented in HTML already. You'd just read in the page, populate the form inputs with stuff, then call .submit(). It'll use the method and action defined in the form's declaration, so you don't need to copy it into your javascript.
examples

How to post form to two different pages with a single button click?

I have a form with a single button like below:
<form name="sampleForm" id="sampleForm" method="post" action="" enctype="multipart/form-data">
<input type="text" id="biosample" name="biosample" class="sample"/>
<input type="text" id="library" name="library" class="sample"/>
<input type="submit" name="btnAdd" id="btnAdd" class="buttonsub" value="NEXT>>">
</form>
Ajax code is:
<script>
$(document).ready(function(){
var encoded_project_id = $('#encoded_project_id').val();
$('#sampleForm').on('submit', function(){
var target = 'windowFormTarget';
window.open('', target, 'width=500,height=300');
this.setAttribute('target', target);
$.post('postdata.php', $(this).serialize(), function(){
window.location.href = 'phases.php?edit='+encoded_project_id;
}).fail(function(){
window.location.href = 'sample.php?edit='+encoded_project_id;
});
});
});
</script>
Now when button is clicked, I want to post the data from the above form in 2 pages - handler.php and postdata.php
Handler.php should open in a new javascript window and postdata.php should open in same tab and same window.
How it can be achieved?
EDIT: It would seem you are using jQuery, so change this:
$(document).ready(function () {
document.getElementById('sampleForm').onsubmit = function (e) {
var req = new XMLHttpRequest();
req.open('POST', 'test.php', true);
req.send();
}
});
to this:
$(document).ready(function(){
$('#sampleForm').on('submit', function(){
$.post('postdata.php', $(this).serialize(), function(){
console.log('success');
}).fail(function(){
console.log('error');
});
});
});
You should do two things. First add
<form target="_blank" action="handler.php"></form>
This will ensure when the submit button is clicked that the form will open a new window.
Then you need to intercept the submit like so:
document.getElementById('sampleForm').onsubmit = function(e){
//xmlHTTPRequest function
//This is where you send your form to postdata.php
}
The code above will be called first and you can send your form with the asynchronous XMLHTTPRequest object to postdata.php . After that function ends, the default behavior of the form will start and your handler.php will receive the form.
you just to need two ajax call . Do something like this
$(document).ready(function(){
// if want to stop default submission
$("#sampleForm").submit(function(e){
e.preventDefault();
});
$(document).on('click','#btnAdd',function(){
send('page1.php',{'data1':'value'});
send('page2.php',{'data1':'value'});
});
});
function send(url,data)
{
$.ajax({
url: url,
type: 'POST',
datatype: 'json',
data: data,
success: function(data) {
// success
},
error: function(data) {
alert("There may an error on uploading. Try again later");
},
});
}

Have to click submit twice for AJAX request to fire on form submission

My Form HTML looks like this.
<form novalidate action="register.php" method="post" >
<label for="username">Username</label>
<input type="text" name="username" required placeholder="Your username" autofocus/>
<input type="submit" name="register" value="Register" cid="submit" />
</form>
And My jQuery looks like this
$("form").submit(function(e) {
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
url: "check.php",
type: "post",
data: { formData: serializedData },
datetype: "JSON"
});
request.done(function(response, textStatus, jqXHR) {
console.log("HELLO");
$('form').unbind();
$('form').submit();
});
e.preventDefault();
});
The sad thing is that it logs hello to the console but it never submits the form with one click on the submit button. I need to press two times to submit button.
Can anyone tell me the problem and how can I fix it so that 1 click is sufficient for form submission.
NOTE: The data of form is send for validation not actually for submission . If data like email , username etc are valid i want the form to be submitted with one click.
Try separating the validation from the form submit.
Simply changing this line:
$("form").submit(function(e) {
to
$("input[name='register']").click(function(e) {
First of all I think it would be cleaner to use a success function instead of a .done() function. For example:
$("form").submit(function(e) {
e.preventDefault();
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
// Merge the check.php and register.php into one file so you don't have to 'send' the data twice.
url: "register.php",
type: "post",
data: { formData: serializedData },
datetype: "JSON",
success: function() {
console.log("This form has been submitted via AJAX");
}
});
});
Notice that I removed the .unbind() function, as I suspect it might be the reason your code is acting up. It removes the event handlers from the form, regardless of their type (see: http://api.jquery.com/unbind/). Also, I put the e.preventDefault() at the start. I suggest you try this edited piece of code, and let us know if it does or does not work.
EDIT: Oh, and yeah, you don't need to submit it when you're sending the data via AJAX.
Try this one.
$("form").submit(function(e) {
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
url: "check.php",
type: "post",
data: { formData: serializedData },
datetype: "JSON"
});
request.done(function(response, textStatus, jqXHR) {
console.log("HELLO");
$('form').unbind();
$('form').submit();
});
});
$("form").submit(function(e) {
e.preventDefault();
var $form = $(this);
var serializedData = $form.serialize();
$.ajax({
url: "check.php",
type: "post",
data: { formData: serializedData },
datatype: "JSON",
success: function(data) {
return data;
}
});
});
So, to break it down.
Stop the form submission with the preventDefault().
Get the form data and submit it to your validator script.
The return value, I assume, is a boolean value. If it validated, it'll be true, or false.
Return the value which will continue the form submission or end it.
NB.: This is a horrible way to validate your forms. I'd be validating my forms on the server with the form submission, because javascript can be terribly easily monkeyed with. Everything from forcing a true response from the server to turning the submission event listener off.
Once I have the same issue
What I found is I have some bug in my url xxx.php
it may return error message like "Notice: Undefined variable: j in xxx.php on line ....."
It may let ajax run unexpected way.
Just for your info.
Instead of doing prevent default when clicking a submit button, you can create a normal button and fire a function when you click it, at the end of that function, submit the form using $('#form').submit();. No more confusing prevent default anymore.
You don't need to call submit() since you are posting your data via ajax.
EDIT You may need to adjust the contentType and/or other ajax params based on your needs. PHP example is very basic. Your form is most likely much more complex. Also, you will want to sanitize any php data - don't rely on just the $_POST
jQuery:
$("form").submit(function(e) {
$.ajax({
'type': 'post',
'contentType': 'application/json',
'url': 'post.php',
'dataType': 'json',
'data': { formData: $(this).serialize},
'timeout': 50000
).done(function(data) {
// Response from your validation script
if (data === true)
{
// SUCCESS!
}
else
{
// Something happened.
}
).fail(function(error) {
console.log(error);
});
e.preventDefault();
});
PHP
$is_valid = FALSE;
$name = $_POST['name'];
if ($name !== '')
{
$is_valid = TRUE;
}
else
{
return FALSE;
}
if ($is_valid)
{
// insert into db or email or whatver
return TRUE;
}

jQuery AJAX submit form

I have a form with name orderproductForm and an undefined number of inputs.
I want to do some kind of jQuery.get or ajax or anything like that that would call a page through Ajax, and send along all the inputs of the form orderproductForm.
I suppose one way would be to do something like
jQuery.get("myurl",
{action : document.orderproductForm.action.value,
cartproductid : document.orderproductForm.cartproductid.value,
productid : document.orderproductForm.productid.value,
...
However I do not know exactly all the form inputs. Is there a feature, function or something that would just send ALL the form inputs?
This is a simple reference:
// this is the id of the form
$("#idForm").submit(function(e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
var actionUrl = form.attr('action');
$.ajax({
type: "POST",
url: actionUrl,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
});
You can use the ajaxForm/ajaxSubmit functions from Ajax Form Plugin or the jQuery serialize function.
AjaxForm:
$("#theForm").ajaxForm({url: 'server.php', type: 'post'})
or
$("#theForm").ajaxSubmit({url: 'server.php', type: 'post'})
ajaxForm will send when the submit button is pressed. ajaxSubmit sends immediately.
Serialize:
$.get('server.php?' + $('#theForm').serialize())
$.post('server.php', $('#theForm').serialize())
AJAX serialization documentation is here.
Another similar solution using attributes defined on the form element:
<form id="contactForm1" action="/your_url" method="post">
<!-- Form input fields here (do not forget your name attributes). -->
</form>
<script type="text/javascript">
var frm = $('#contactForm1');
frm.submit(function (e) {
e.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
console.log('Submission was successful.');
console.log(data);
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
});
});
</script>
There are a few things you need to bear in mind.
1. There are several ways to submit a form
using the submit button
by pressing enter
by triggering a submit event in JavaScript
possibly more depending on the device or future device.
We should therefore bind to the form submit event, not the button click event. This will ensure our code works on all devices and assistive technologies now and in the future.
2. Hijax
The user may not have JavaScript enabled. A hijax pattern is good here, where we gently take control of the form using JavaScript, but leave it submittable if JavaScript fails.
We should pull the URL and method from the form, so if the HTML changes, we don't need to update the JavaScript.
3. Unobtrusive JavaScript
Using event.preventDefault() instead of return false is good practice as it allows the event to bubble up. This lets other scripts tie into the event, for example analytics scripts which may be monitoring user interactions.
Speed
We should ideally use an external script, rather than inserting our script inline. We can link to this in the head section of the page using a script tag, or link to it at the bottom of the page for speed. The script should quietly enhance the user experience, not get in the way.
Code
Assuming you agree with all the above, and you want to catch the submit event, and handle it via AJAX (a hijax pattern), you could do something like this:
$(function() {
$('form.my_form').submit(function(event) {
event.preventDefault(); // Prevent the form from submitting via the browser
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()
}).done(function(data) {
// Optionally alert the user of success here...
}).fail(function(data) {
// Optionally alert the user of an error here...
});
});
});
You can manually trigger a form submission whenever you like via JavaScript using something like:
$(function() {
$('form.my_form').trigger('submit');
});
Edit:
I recently had to do this and ended up writing a plugin.
(function($) {
$.fn.autosubmit = function() {
this.submit(function(event) {
event.preventDefault();
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()
}).done(function(data) {
// Optionally alert the user of success here...
}).fail(function(data) {
// Optionally alert the user of an error here...
});
});
return this;
}
})(jQuery)
Add a data-autosubmit attribute to your form tag and you can then do this:
HTML
<form action="/blah" method="post" data-autosubmit>
<!-- Form goes here -->
</form>
JS
$(function() {
$('form[data-autosubmit]').autosubmit();
});
You can also use FormData (But not available in IE):
var formData = new FormData(document.getElementsByName('yourForm')[0]);// yourForm: form selector
$.ajax({
type: "POST",
url: "yourURL",// where you wanna post
data: formData,
processData: false,
contentType: false,
error: function(jqXHR, textStatus, errorMessage) {
console.log(errorMessage); // Optional
},
success: function(data) {console.log(data)}
});
This is how you use FormData.
Simple version (does not send images)
<form action="/my/ajax/url" class="my-form">
...
</form>
<script>
(function($){
$("body").on("submit", ".my-form", function(e){
e.preventDefault();
var form = $(e.target);
$.post( form.attr("action"), form.serialize(), function(res){
console.log(res);
});
});
)(jQuery);
</script>
Copy and paste ajaxification of a form or all forms on a page
It is a modified version of Alfrekjv's answer
It will work with jQuery >= 1.3.2
You can run this before the document is ready
You can remove and re-add the form and it will still work
It will post to the same location as the normal form, specified in
the form's "action" attribute
JavaScript
jQuery(document).submit(function(e){
var form = jQuery(e.target);
if(form.is("#form-id")){ // check if this is the form that you want (delete this check to apply this to all forms)
e.preventDefault();
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: form.serialize(), // serializes the form's elements.
success: function(data) {
console.log(data); // show response from the php script. (use the developer toolbar console, firefox firebug or chrome inspector console)
}
});
}
});
I wanted to edit Alfrekjv's answer but deviated too much from it so decided to post this as a separate answer.
Does not send files, does not support buttons, for example clicking a button (including a submit button) sends its value as form data, but because this is an ajax request the button click will not be sent.
To support buttons you can capture the actual button click instead of the submit.
jQuery(document).click(function(e){
var self = jQuery(e.target);
if(self.is("#form-id input[type=submit], #form-id input[type=button], #form-id button")){
e.preventDefault();
var form = self.closest('form'), formdata = form.serialize();
//add the clicked button to the form data
if(self.attr('name')){
formdata += (formdata!=='')? '&':'';
formdata += self.attr('name') + '=' + ((self.is('button'))? self.html(): self.val());
}
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: formdata,
success: function(data) {
console.log(data);
}
});
}
});
On the server side you can detect an ajax request with this header that jquery sets HTTP_X_REQUESTED_WITH
for php
PHP
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
//is ajax
}
This code works even with file input
$(document).on("submit", "form", function(event)
{
event.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: $(this).attr("method"),
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
},
error: function (xhr, desc, err)
{
}
});
});
I really liked this answer by superluminary and especially the way he wrapped is solution in a jQuery plugin. So thanks to superluminary for a very useful answer. In my case, though, I wanted a plugin that would allow me to define the success and error event handlers by means of options when the plugin is initialized.
So here is what I came up with:
;(function(defaults, $, undefined) {
var getSubmitHandler = function(onsubmit, success, error) {
return function(event) {
if (typeof onsubmit === 'function') {
onsubmit.call(this, event);
}
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()
}).done(function() {
if (typeof success === 'function') {
success.apply(this, arguments);
}
}).fail(function() {
if (typeof error === 'function') {
error.apply(this, arguments);
}
});
event.preventDefault();
};
};
$.fn.extend({
// Usage:
// jQuery(selector).ajaxForm({
// onsubmit:function() {},
// success:function() {},
// error: function() {}
// });
ajaxForm : function(options) {
options = $.extend({}, defaults, options);
return $(this).each(function() {
$(this).submit(getSubmitHandler(options['onsubmit'], options['success'], options['error']));
});
}
});
})({}, jQuery);
This plugin allows me to very easily "ajaxify" html forms on the page and provide onsubmit, success and error event handlers for implementing feedback to the user of the status of the form submit. This allowed the plugin to be used as follows:
$('form').ajaxForm({
onsubmit: function(event) {
// User submitted the form
},
success: function(data, textStatus, jqXHR) {
// The form was successfully submitted
},
error: function(jqXHR, textStatus, errorThrown) {
// The submit action failed
}
});
Note that the success and error event handlers receive the same arguments that you would receive from the corresponding events of the jQuery ajax method.
I got the following for me:
formSubmit('#login-form', '/api/user/login', '/members/');
where
function formSubmit(form, url, target) {
$(form).submit(function(event) {
$.post(url, $(form).serialize())
.done(function(res) {
if (res.success) {
window.location = target;
}
else {
alert(res.error);
}
})
.fail(function(res) {
alert("Server Error: " + res.status + " " + res.statusText);
})
event.preventDefault();
});
}
This assumes the post to 'url' returns an ajax in the form of {success: false, error:'my Error to display'}
You can vary this as you like. Feel free to use that snippet.
jQuery AJAX submit form, is nothing but submit a form using form ID when you click on a button
Please follow steps
Step 1 - Form tag must have an ID field
<form method="post" class="form-horizontal" action="test/user/add" id="submitForm">
.....
</form>
Button which you are going to click
<button>Save</button>
Step 2 - submit event is in jQuery which helps to submit a form. in below code we are preparing JSON request from HTML element name.
$("#submitForm").submit(function(e) {
e.preventDefault();
var frm = $("#submitForm");
var data = {};
$.each(this, function(i, v){
var input = $(v);
data[input.attr("name")] = input.val();
delete data["undefined"];
});
$.ajax({
contentType:"application/json; charset=utf-8",
type:frm.attr("method"),
url:frm.attr("action"),
dataType:'json',
data:JSON.stringify(data),
success:function(data) {
alert(data.message);
}
});
});
for live demo click on below link
How to submit a Form using jQuery AJAX?
Try
fetch(form.action,{method:'post', body: new FormData(form)});
function send(e,form) {
fetch(form.action,{method:'post', body: new FormData(form)});
console.log('We submit form asynchronously (AJAX)');
e.preventDefault();
}
<form method="POST" action="myapi/send" onsubmit="send(event,this)" name="orderproductForm">
<input hidden name="csrfToken" value="$0meh#$h">
<input name="email" value="aa#bb.com">
<input name="phone" value="123-456-666">
<input type="submit">
</form>
Look on Chrome Console > Network after/before 'submit'
I know this is a jQuery related question, but now days with JS ES6 things are much easier. Since there is no pure javascript answer, I thought I could add a simple pure javascript solution to this, which in my opinion is much cleaner, by using the fetch() API. This a modern way to implements network requests. In your case, since you already have a form element we can simply use it to build our request.
const form = document.forms["orderproductForm"];
const formInputs = form.getElementsByTagName("input");
let formData = new FormData();
for (let input of formInputs) {
formData.append(input.name, input.value);
}
fetch(form.action,
{
method: form.method,
body: formData
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error.message))
.finally(() => console.log("Done"));
consider using closest
$('table+table form').closest('tr').filter(':not(:last-child)').submit(function (ev, frm) {
frm = $(ev.target).closest('form');
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert(data);
}
})
ev.preventDefault();
});
You may use this on submit function like below.
HTML Form
<form class="form" action="" method="post">
<input type="text" name="name" id="name" >
<textarea name="text" id="message" placeholder="Write something to us"> </textarea>
<input type="button" onclick="return formSubmit();" value="Send">
</form>
jQuery function:
<script>
function formSubmit(){
var name = document.getElementById("name").value;
var message = document.getElementById("message").value;
var dataString = 'name='+ name + '&message=' + message;
jQuery.ajax({
url: "submit.php",
data: dataString,
type: "POST",
success: function(data){
$("#myForm").html(data);
},
error: function (){}
});
return true;
}
</script>
For more details and sample Visit:
http://www.spiderscode.com/simple-ajax-contact-form/
To avoid multiple formdata sends:
Don't forget to unbind submit event, before the form submited again,
User can call sumbit function more than one time, maybe he forgot something, or was a validation error.
$("#idForm").unbind().submit( function(e) {
....
If you're using form.serialize() - you need to give each form element a name like this:
<input id="firstName" name="firstName" ...
And the form gets serialized like this:
firstName=Chris&lastName=Halcrow ...
I find it surprising that no one mentions data as an object. For me it's the cleanest and easiest way to pass data:
$('form#foo').submit(function () {
$.ajax({
url: 'http://foo.bar/some-ajax-script',
type: 'POST',
dataType: 'json',
data: {
'foo': 'some-foo-value',
'bar': $('#bar').val()
}
}).always(function (response) {
console.log(response);
});
return false;
});
Then, in the backend:
// Example in PHP
$_POST['foo'] // some-foo-value
$_POST['bar'] // value in #bar
This is not the answer to OP's question,
but in case if you can't use static form DOM, you can also try like this.
var $form = $('<form/>').append(
$('<input/>', {name: 'username'}).val('John Doe'),
$('<input/>', {name: 'user_id'}).val('john.1234')
);
$.ajax({
url: 'api/user/search',
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
data: $form.serialize(),
success: function(data, textStatus, jqXHR) {
console.info(data);
},
error: function(jqXHR, textStatus, errorThrown) {
var errorMessage = jqXHR.responseText;
if (errorMessage.length > 0) {
alert(errorMessage);
}
}
});
JavaScript
(function ($) {
var form= $('#add-form'),
input = $('#exampleFormControlTextarea1');
form.submit(function(event) {
event.preventDefault();
var req = $.ajax({
url: form.attr('action'),
type: 'POST',
data: form.serialize()
});
req.done(function(data) {
if (data === 'success') {
var li = $('<li class="list-group-item">'+ input.val() +'</li>');
li.hide()
.appendTo('.list-group')
.fadeIn();
$('input[type="text"],textarea').val('');
}
});
});
}(jQuery));
HTML
<ul class="list-group col-sm-6 float-left">
<?php
foreach ($data as $item) {
echo '<li class="list-group-item">'.$item.'</li>';
}
?>
</ul>
<form id="add-form" class="col-sm-6 float-right" action="_inc/add-new.php" method="post">
<p class="form-group">
<textarea class="form-control" name="message" id="exampleFormControlTextarea1" rows="3" placeholder="Is there something new?"></textarea>
</p>
<button type="submit" class="btn btn-danger">Add new item</button>
</form>
There's also the submit event, which can be triggered like this $("#form_id").submit(). You'd use this method if the form is well represented in HTML already. You'd just read in the page, populate the form inputs with stuff, then call .submit(). It'll use the method and action defined in the form's declaration, so you don't need to copy it into your javascript.
examples

Categories

Resources