Submitting multiple html forms - javascript

I want to submit html forms present in an array. But the problem is only last form is actually posted to server. All other forms do not reach server. Any hint what I am doing wrong here?
if (numberOfRows > 0) {
for (var i = 0; i < numberOfRows; i++)
{
alert('submitting form ' + i);
submittedForms[i].submit();
}
}
}

Submitting a form with .submit() is similar to a user clicking a submit button which will result in a new page being loaded. So calling .submit() on multiple forms in the same page would equal a user clicking multiple submit buttons, what is the browser supposed to be doing then? I'm not sure if the specification documents a certain behavior, but I don't see how this could be handled generally. If all you want is that the form data reaches the server, use AJAX. For example like this when using jQuery: jQuery AJAX submit form

Thanks to #pschichtel.
I ended up using ajax to post multiple forms at once. Below is my final code:
var numberOfRows = submittedForms.length;
if (numberOfRows > 0) {
for (var i = 0; i < numberOfRows; i++) {
var formData = new FormData(submittedForms[i]); // yourForm: form selector
postFormAjax(formData);
}
deleteForms();
}
function postFormAjax(formData)
{
$.ajax({
type: "POST",
url: "https:url/servlet/servlet.WebToCase?encoding=UTF-8", // where you wanna post
data: formData,
processData: false,
contentType: false,
error: function (jqXHR, textStatus, errorMessage) {
alert(errorMessage); // Optional
},
success: function (data) {
alert(data)
}
});
}

Try this:
$('#form1').submit();
$('#form2').submit();

Related

NO refresh the page when success ajax

I have a ajax section to submit data in laravel. I want if I submit success then don't reload the page and submit the error then reload the page. In the code below, when the error reloads the page correctly, I am having a problem in the success case, the page must not be reloaded, but the result is reloaded. I have added the line e.preventDefault () then true in the success case but wrong in the error case
$(document).ready(function() {
$('form').submit(function(e){
//e.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url:'{{ route('contracts.store') }}',
method: "POST",
data: form_data,
dataType: "json",
success: function(data) {
$("#mgsContract").text("Add successfully");
$("#hideForm").css("visibility", "visible");
$("#hideForm").css("height", "auto");
$("#result-contract-id").val(data.contract_obj);
},
error: function(data) {
$("#mgsContract").text("Something wrong");
}
})
});
});
Add back that e.preventDefault() to prevent the form submission, and in the error case, call location.reload(). (Or if you want to submit the form conventionally in the error case, use e.target.submit(); instead. Since that's calling submit on the DOM element [not a jQuery wrapper], it won't call your submit handler again. [This is one of the differences between programmatically calling submit on a DOM element vs. calling it on a jQuery object.])
when you use ajax, laravel automatically responds in JSON for validation errors. therefore to access the validation errors you can use this.responseJSON.errors in error section of your ajax. there is no need to reload the page to access validation errors.
however in any case if you need to reload or go to specific location you can use window.location
window.location.href = "an address"; // going to specific location
window.location.reload(); //reloading the page
an ajax example is the following, in which a loop for showing all errors inside the form is specified.
$("#form_id").submit(function (e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
var url = form.attr('action');
$.ajax({
method: "POST",
url: url,
data: form.serialize(), // serializes the form's elements.
success: function (data) {
// code in the case of success
},
error: function (err) {
if (err.status == 422) { // when status code is 422, it's a validation issue
// code in the case of error
console.log(err.responseJSON);
// you can loop through the errors object and show it to the user
console.warn(err.responseJSON.errors);
// display errors on each form field
$.each(err.responseJSON.errors, function (i, error) {
var el = $(document).find('[name="' + i + '"]');
el.removeClass('is-valid');
el.addClass('is-invalid');
var parent = el.parents('.form-group');
parent.append("<small class='error-message text-right text-danger d-block pr-5 ' role='alert'>" + error + "</small >");
});
}
},
});
});

submit form with ajax validation jquery / standard javascript

I'll start with an apology - I'm a .NET coder with little (no) front-end experience.
When the user clicks on Submit, the form needs to call a REST service, if the service returns true then the user is presented with a warning that a duplicate exists and are asked whether they want to continue. Appreciate any help.
I have the Submit button ONCLICK wired up to Approve()
When the checkForDuplicateInvoice() gets called, it passes the control back to the calling function right away before the ajax call has a chance to get the result. The effect is that the Validate() function finishes without taking into account whether or not a duplicate invoice exists.
I need help in modifying the form so that when the user clicks on the submit button, the form validates (including the ajax call to the db) before finally submitting.
I've modified the code based on Jasen's feedback.
I'm including https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js in my header.
The error I get now is "Object doesn't support property or method 'button'"
What I have now for my form submission/validation is:
$(document).ready(function () {
$("#process").button().click( function () {
if (ValidateFields()) { // internal validation
var companyCode = document.getElementById("_1_1_21_1").value;
var invoiceNo = document.getElementById("_1_1_25_1").value;
var vendorNo = document.getElementById("_1_1_24_1").value;
if (vendorNo == "undefined" || invoiceNo == "undefined" || companyCode == "undefined") {
return false;
}
$.ajax({ // external validation
type: "GET",
contentType: "application/json;charset=utf-8",
//context: $form,
async: false,
dataType: "jsonp",
crossDomain: true,
cache: true,
url: "http://cdmstage.domain.com/services/rest/restservice.svc/CheckDuplicateInvoice?InvoiceNumber=" + invoiceNo + "&VendorNumber=" + vendorNo + "&CompanyCode=" + companyCode,
success: function (data) {
var result = data;
var exists = result.CheckForInvoiceDuplicateResult.InvoiceExists;
var valid = false;
if (exists) {
if (confirm('Duplicate Invoice Found! Click OK to override or Cancel to return to the form.')) {
valid = true;
}
}
else {
valid = true; // no duplicate found - form is valid
}
if (valid) {
document.getElementById("_1_1_20_1").value = "Approve";
doFormSubmit(document.myForm);
}
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
});
});
First review How do I return the response from an asynchronous call? Understand why you can't return a value from the ajax callback functions.
Next, disassociate the submit button from the form to prevent it from performing default submission. Test it to see it does nothing.
<form>
...
<button type="button" id="process" />
</form>
Then wire it up to make your validation request
$("#process").on("click", function() {
if (valid()) {
$(this).prop("disabled", true); // disable the button to prevent extra user clicks
// make ajax server-side validation request
}
});
Then you can make your AJAX request truly asynchronous.
$.ajax({
async: true,
...,
success: function(result) {
if (exists) {
// return true; // returning a value is futile
// make ajax AddInvoice call
}
}
});
Pseudo-code for this process
if (client-side is valid) {
server-side validation: {
on response: if (server-side is valid) {
AddInvoice: {
on response: if (successful) {
form.submit()
}
}
}
}
}
In the callback for the server-side validation you make the AddInvoice request.
In the callback for AddInvoice you call your form.submit().
In this way you nest ajax calls and wait for each response. If any fail, make the appropriate UI prompt and re-enable the button. Otherwise, you don't automatically submit the form until both ajax calls succeed and you call submit() programmatically.

I need to get a variable between jQuery function and AJAX

I have two buttons on the form I'm getting, this first piece of coce allow me to know which was the button clicked by getting the id of it.
var button;
var form = $('.register_ajax');
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
});
and this other send the form data through AJAX using the info already obtained from the button using the script above.
form.bind('submit',function () {
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
cache: false,
dataType: 'json',
data: form.serialize() + '&' + encodeURI(button.attr('name')) + '=' + encodeURI(button.attr('value')) ,
beforeSend: function() {
//$("#validation-errors").hide().empty();
},
success: function(data) {
if(data.message == 0){
$("#fave").attr('src','interactions/favorite.png');
$("#favorite").attr('value',1);
console.log(data.errors);
}
if(data.message == 1)
{
$("#fave").attr('src','interactions/favorite_active.png');
$("#favorite").attr('value',0);
}
if(data.message == "plus")
{
$("#vote_up").attr('class','options options-hover');
$("#vote_down").attr('class','options');
console.log(data.message);
}
if(data.message == "sub")
{
$("#vote_down").attr('class','options options-hover');
$("#vote_up").attr('class','options');
console.log("sub");
}
},
error: function(xhr, textStatus, thrownError) {
console.log(data.message);
}
});
return false;
});
The problem is that the data is not being passed to the ajax function, the button info is being saved on the button var, but it's not being obtained at time on the ajax call to work with it (or at least that is what I think). I'd like to know what can I do to make this work, any help appreciated.
1st edit: If I get the button data directly like button = $('#vote_up'); it doesn't work either, it only works if I get the button directly like this but without using the function.
2nd edit: I found the solution, I posted below.
var button is in the scope of the .on('event', function(){})
You need to declare the variable in the shared scope, then you can modify the value inside the event callback, i.e.
var button,
form = $('.register_ajax');
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
});
You are being victim of a clousure. Just as adam_bear said you need to declare the variable outside of the function where you are setting it, but you are going to keep hitting these kind of walls constantly unless you dedicate some hours to learn the Good Parts :D, javascript is full of these type of things, here is a good book for you and you can also learn more from the author at http://www.crockford.com/.
I Found the solution, I just changed a little bit the click function like this:
var button;
var form = $('.register_ajax');
var data = form.serializeArray();
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
data.push({name: encodeURI($(this).attr('name')), value: encodeURI($(this).attr('value'))});
form.submit();
});
using e.preventDefault(); and form.submit(); to send the form. also I changed the data.serialize to serializeArray(); because it's more effective to push data into the serializeArray(). in the second script I just changed the data.serialize() and used the data variable that I already filled with the serializeArray() and the data.push():
form.bind('submit',function () {
alert(button);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
cache: false,
dataType: 'json',
data: data,
//here goes the rest of the code
//...
});
return false;
});
it worked for me, it solved the problem between the click and submit event that wasn't allowing me to send the function through ajax.

Save 2 Forms At the Same Time MVC 3

Im planning to save 2 forms but the 1st form is where i get the Foreign key for the Second form
This is my Attempt to save this Using Javascript
$("#btnSave").click(function (e) {
e.preventDefault();
$('#workForm').submit();
$('#conttForm').submit();
});
But it errors on Contact Form Submit because the ID of Worker Form is still null while saving the contact form that is its Foreign Key
i also Tried this method
$("#btnSave").click(function (e) {
e.preventDefault();
if (Id != 0) {
$('#workForm').submit();
$('#contForm').submit();
} else {
$('#workForm').submit(); }
});
But it only go at Else because the ID is 0
I hope someone can help me here
Thanks :D
jQuery's submit function actually causes the browser to send a request, i.e. you're submitting the form. To accomplish this you'll need to uses ajax. Something like this should do the trick:
$.ajax({
method: 'POST',
url: $('#workForm').attr('action'),
data: $('#workForm').serialize(),
success: function(data) {
//grab whatever id you need here
var id_thing = $(data).find('#id_here').val();
//do something with id
$('#conttForm input[name="your-hidden-id-field"]').val(id_thing);
$('#conttForm').submit();
}
})

get form data with javascript and then submit it to a php file using ajax

I am having some trouble working out how to get data from a form to post via ajax. I have the following code but it doesn't seem to be sending though the data from elements like checkboxes and radio buttons. Instead it is sending though all the fields. ie if there is a set of radiobuttons it is sending through all the possibilities not just the checked ones. The form can be made up of any type of element and have an undermined amount of elements in it, so I need to iterate through in the way I am. That part seems to be working, but I can't seem to get the javascript to grab the selected data. Do I need to manually check each element's type and then check to see if it checked etc?
myString = "";
my_form_id = "1";
my_url = "phpscript.php";
elem = document.getElementById("form_" + my_form_id).elements;
for(var i = 0; i < elem.length; i++)
{
if (i>0) { myString += "&"; }
myString += elem[i].name + "=" + elem[i].value;
}
$.ajax({
type: "POST",
url: my_url,
data: myString,
success: function(data) {
// process the post data
}
});
`
Since you're using jQuery, you can drastically simplify it all:
var my_form_id = "1";
var my_url = "phpscript.php";
var form = $("#form_" + my_form_id);
$.ajax({
type: "POST",
url: my_url,
data: form.serialize(),
success: function(data) {
// process the post data
}
});
jQuery's serialize method does all the work for you. But if you wanted to do it by hand, then yes, you would have to check each field.

Categories

Resources