Ajax call for second submit button of a form - javascript

I'm using spring boot and thymeleaf.
Managing to call a spring controller method on click of first submit button.
I'm trying for a Ajax call on hit of second submit button , how can I achieve it?
Ajax call for the second submit button
$(document).ready(function() {
$("#download").click(function() {
var checked = [];
$('.checkbox:checked').each(function() {
checked.push($(this).val());
});
console.log(checked);
$.ajax({
type: "POST",
url: "selectedsalesDownload",
data: {
name: checked
},
success: function(msg) {
console.log(mgs);
alert(msg);
}
});
});
});
<form name="salesList" th:action="#{/selectedsales}" th:object="${sales}" method="post">
<div class="container">
<hr>
<table class="table table-striped">
<thead class="thead-dark">
<tr>
<th>SELECT</th>
<th>Mandy Name</th>
<th>GSTIN</th>
</tr>
</thead>
<tbody>
<tr id="salesDataTable" th:each="tempSales:${sales}">
<td>
<input class="checkbox" type="checkbox" th:name="selected" th:value="${tempSales.ID}" />
</td>
<td th:text="${tempSales.mandyName}"></td>
<td th:text="${tempSales.gstin}"></td>
</tr>
</tbody>
</table>
<div>
<input type="submit" value="SELECT" name="submit" class="btn btn-primary btn-sm mb-3" />
<input id="download" type="submit" value="DOWNLOAD" name="download" class="btn btn-primary btn-sm mb-3" />
</div>
</div>
</form>
Controller Method for first submit button
#PostMapping("/selectedsales")
public String selectedSales(
#RequestParam(value = "selected", required = false) List<Integer> selectedList,
Model model
) {
//...
}
Controller Method for second submit button
#RequestMapping(value = "/selectedsalesDownload")
#ResponseBody
public String toDownload(#RequestParam("name") List<Integer> list) {
return "msg";
}
I'm not able to get into "toDownload" method in the controller on click of second submit button instead I'm getting into first submit button controller method "selectedSales".
And also I need to send the checked box value which is stored in the javascript array variable "checked" to spring controller method "toDownload".
Need Solution.

Two things here...
You aren't preventing the second submit button from submitting the form normally. Either use a button type...
<input id="download" type="button" ... />
or make sure you prevent the default event action
$("#download").on("click", function(e) {
e.preventDefault()
// and so on
})
#RequestParam list parameters should be sent with the following format for the greatest compatibility
name=1&name=2&name=3...
Unfortunately, the default for jQuery is
name[]=1&name[]=2&name[]=3...
probably for compatibility with PHP. You can change this though via the traditional option
$.ajax({
method: "POST",
url: "selectedsalesDownload",
data: {
name: checked
},
traditional: true, // 👈 note the value here
success: function(msg) {
console.log(mgs);
alert(msg);
}
});
See https://api.jquery.com/jquery.ajax/ and more specifically https://api.jquery.com/jQuery.param/

Why do you need two submit buttons? Which one actually completes the form?
Adding the following code to your JS would immediately solve the issue, but ultimately you really should change one of those submit inputs to type="button" as well. This will prevent the default functionality of the form element and you can then override it with your own code:
$("form").submit(function(){
event.preventDefault();
// Your other code to execute on form submission
});

Related

How can I pass input value in a complex Model from View to Controller?

My scenario here is that on my View, I have multiple field to input number and one field to auto generated result by a formula. I want to be able to pass those value back to my Controller, from there I will calculate and return the result back to View while the input value to calculate still remain. The reason why I don't perform this on my Javascript is because there are some condition that require me to interact with value from lots of others field in others data in database. I intend to do this by passing a whole set of Model from View to Controller, and I don't want to reload the page whenever an input field is input. So far, here's my two methods:
Using Javascript Ajax:
var modelObject = #Html.Raw(Json.Serialize(Model));
This allow me to store and passing Base Model at the beginning only. I can't pass new input value. Is there away for the input to automatically store their value in Model to be used in the code similar to the above?
Using Unobtrusive AJAX and Javascript to activate submit action:
function submit(){
$('#formSubmit').submit();
--OR--
$('#btnSubmit').click();
}
<form id="formSubmit" data-ajax="true" asp-action="Action" method="POST">
<input asp-for="Item.inputValue" onchange="submit()"/>
<button id="btnSubmit" type="submit"></button>
</form>
The button when click works fine with Unobtrusive AJAX. But the Javascript to activate the submit event can't. My page still reload.
What is the right way for me to go? And in which of them, how do I need to fix my code to make it run like I want?
Using Javascript Ajax:
var modelObject = #Html.Raw(Json.Serialize(Model));
This allow me to store and passing Base Model at the beginning only. I
can't pass new input value. Is there away for the input to
automatically store their value in Model to be used in the code
similar to the above?
When using JQuery Ajax to pass the data, you should use the serialize() method to serialize the form, then pass the form data to the controller action method. Code as below:
$("#btnAjax").click(function () {
// var data = $("#mainform").serialize(); //you could set a break point to check the value.
$.ajax({
url:"/Test/CreateProduct", // change the url to yours.
method: "Post",
data: $("#mainform").serialize(),
success: function (response) {
//after getting the response, update the content.
$("#div_partial").html("");
$("#div_partial").html(response); //
},
error: function (error) {
alert("error");
}
});
});
Using Unobtrusive AJAX and Javascript to activate submit action:
function submit(){
$('#formSubmit').submit();
--OR--
$('#btnSubmit').click();
}
<form id="formSubmit" data-ajax="true" asp-action="Action" method="POST">
<input asp-for="Item.inputValue" onchange="submit()"/>
<button id="btnSubmit" type="submit"></button>
</form>
The button when click works fine with Unobtrusive AJAX. But the
javascript to activate the submit event can't. My page still reload.
When using the jQuery Unobtrusive AJAX, first, please make sure you have added the jQuery Unobtrusive AJAX reference in current page, then, make sure you have activated unobtrusive Ajax on the target element.
For example, using the following code, after clicking the submit button, it will submit the mainform to the ProductIndex action method, then update the div_partial contents:
<form asp-action="ProductIndex" id="mainform"
data-ajax="true"
data-ajax-method="Post"
data-ajax-update="#div_partial">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div id="div_partial">
<partial name="_PVProduct.cshtml" data="#Model" />
</div>
<div class="form-group">
<input type="submit" value="Submit" class="btn btn-primary" />
</div>
</form>
More detail information about using jQuery Unobtrusive AJAX, refer this link.
The detail sample code as below:
Model:
public class Item
{
public int ItemId { get; set; }
public string ItemDescription { get; set; }
public decimal ItemUnitPrice { get; set; }
public decimal Quantity { get; set; }
}
public class ProductViewModel
{
public string UserName { get; set; }
public List<Item> Items { get; set; }
}
Controller:
public IActionResult ProductIndex()
{
ProductViewModel newitem = new ProductViewModel()
{
Items = _repository.GetItemViewModels().Select(c => new Item() { ItemId = c.ItemId, ItemDescription = c.ItemDescription, Quantity = c.Quantity, ItemUnitPrice = c.ItemUnitPrice }).ToList()
};
return View(newitem);
}
// Unobtrusive AJAX Post method
[HttpPost]
public IActionResult ProductIndex(ProductViewModel product)
{
return PartialView("_PVProduct", product);
}
//JQuery Ajax Post method.
[HttpPost]
public IActionResult CreateProduct(ProductViewModel product)
{
return PartialView("_PVProduct", product);
}
PartialView (_PVProduct.cshtml): Here I use a partial view to display the Model content, it is easier to update the content with Ajax.
#model WebApplication6.Models.ProductViewModel
<div class="form-group">
<label asp-for="UserName" class="control-label"></label>
<input asp-for="UserName" class="form-control" />
<span asp-validation-for="UserName" class="text-danger"></span>
</div>
<div class="form-group">
<table class="table">
<thead>
<tr>
<th>
ItemId
</th>
<th>
ItemDescription
</th>
<th>
ItemUnitPrice
</th>
<th>
Quantity
</th>
<th></th>
</tr>
</thead>
<tbody>
#for (var i = 0; i < Model.Items.Count(); i++)
{
<tr>
<td>
#Model.Items[i].ItemId
<input asp-for="Items[i].ItemId" type="hidden" />
</td>
<td>
#Model.Items[i].ItemDescription
<input asp-for="Items[i].ItemDescription" type="hidden" />
</td>
<td class="text-right">
<input asp-for="Items[i].ItemUnitPrice" type="text" />
</td>
<td class="text-right">
<input asp-for="Items[i].Quantity" type="text" />
</td>
<td class="text-right">
#(Model.Items[i].Quantity * Model.Items[i].ItemUnitPrice)
</td>
<td></td>
</tr>
}
</tbody>
</table>
</div>
View Page ():
#model WebApplication6.Models.ProductViewModel
<div class="row">
<div class="col-md-4">
<form asp-action="ProductIndex" id="mainform"
data-ajax="true"
data-ajax-method="Post"
data-ajax-update="#div_partial">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div id="div_partial">
<partial name="_PVProduct.cshtml" data="#Model" />
</div>
<div class="form-group">
<input type="submit" value="Submit" class="btn btn-primary" />
<input type="button" value="Ajax Submit" class="btn btn-primary" id="btnAjax" />
</div>
</form>
</div>
</div>
At the end the above view page, add the following scripts: Here I use the jQuery Unobtrusive AJAX CDN reference:
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-ajax-unobtrusive/3.2.6/jquery.unobtrusive-ajax.min.js"></script>
<script>
$(function () {
$("#btnAjax").click(function () {
//var data = $("#mainform").serialize();
$.ajax({
url:"/Test/CreateProduct", // change the url to yours.
method: "Post",
data: $("#mainform").serialize(),
success: function (response) {
//after getting the response, update the content.
$("#div_partial").html("");
$("#div_partial").html(response);
//attach change event and then trigger the submit form action..
$(".table> tbody >tr").each(function (index, tr) {
$(tr).find("input[name$='Quantity']").change(function () {
//console.log($(this).val());
$("#btnAjax").click();
});
});
},
error: function (error) {
alert("error");
}
});
});
//attach change event and then trigger the submit form action.
$(".table> tbody >tr").each(function (index, tr) {
$(tr).find("input[name$='Quantity']").change(function () {
//console.log($(this).val());
$("#btnAjax").click();
});
});
})
</script>
}
The output as below:
Submit button: using the Unobtrusive AJAX method submit the form.
Ajax Submit button: Using JQuery Ajax to submit the form.
Quantity Input change event: trigger the Ajax button and then submits the form.

Use jQuery to submit 1 Ajax form on page with several unique forms

I have a Bootstrap page that is dynamically created using PHP, and on the page there are 25+ forms that are used to edit records.
The form submits to the server using jQuery Ajax script which works as expected on the first form, but when the second form is edited and submitted it submits form 1 and 2, and when I go to form 3 it will submit forms 1, 2, and 3
Here is the HTML:
<tr id="375987">
<td width="20%">audio controls to play wav file</td>
<td width="80%">
<div class="form-group">
<form id="375987">
<textarea class="form-control" id="rec_txt" name="rec_txt" rows="4">There is text from the Database</textarea>
<input type="text" id="event_num" name="event_num" value="" />
<button type="submit" id="correct_stt" class="btn btn-outline-success my-2 my-sm-0" OnClick="update_stt()">Edit</button>
<input type="hidden" id="rec_id" name="rec_id" value="375987" />
<input type="hidden" name="act" value="correct_stt" />
</form>
</div>
</td>
<td>
<a href="#" class="btn btn-primary a-btn-slide-text" onClick="hiderow('375987')">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
<span><strong>Hide</strong></span>
</a>
</td>
</tr>
<!-- 25+ forms ..... -->
And here is the Java:
function update_stt() {
var url = "function_ajax.php"; // the script where you handle the form input.
$('form[id]').on('submit', function(e) {
$.ajax({
type: 'POST',
url: url,
data: $(this).serialize(),
success: function(data) {
console.log('Submission was successful.');
console.log(data);
$(e.target).closest('tr').children('td,th').css('background-color', '#000');
},
error: function(data) {
console.log('An error occurred.');
console.log(data);
},
});
e.preventDefault();
});
}
How can I identify only the id of the form that I want submitted, or submit only the form on that row?
You use a submit button which will automatically submit the form, but you also add a click event to it using the onclick attribute, so it will execute the associated function and submit the form. All that is unnecessarily complicated.
Remove the onclick attribute on your button:
<button type="submit" id="correct_stt" class="btn btn-outline-success my-2 my-sm-0">Edit</button>
And change your code to:
$('#375987').on('submit', function(e) {
var url = "function_ajax.php"; // the script where you handle the form input.
$.ajax({
type: 'POST',
url: url,
data: $(this).serialize(),
success: function(data) {
console.log('Submission was successful.');
console.log(data);
$(e.target).closest('tr').children('td,th').css('background-color', '#000');
},
error: function(data) {
console.log('An error occurred.');
console.log(data);
},
});
e.preventDefault();
});
If you want all your forms to use the same function, then simply replace the selector $('#375987') with $('form'):
$('form').on('submit', function(e) { ... }
If you only want to select some forms, not all, then you can give them the same class and then select them by that class, like <form class="ajaxed">:
$('form.ajaxed').on('submit', function(e) { ... }
You can give id to forms and use
$('#formid').submit();
in your case
$('#375987').submit();
But that id is used by your tr div too. You should consider using id for form only
It's because each time you click the button and call update_stt() you are attaching again the .on() listener.
This is why you end up with more and more submit requests.
$('form[id]').on('submit', function (e) {
This line of code should only be called once not on every click.
ALSO: you said you build these on the backend so you could pass the ID straight to the function:
update_stt(375987)
Then you can use this:
function update_stt(passedNumber) { ...
Then you can use the id number in the call
Your mixing jQuery and vanilla JS a lot here, might make sense to try a larger refactor.

How do you execute a new AJAX everytime a submit button is clicked?

I have a form that is executed every time a submit button is clicked. When the submit button is clicked, a modal is shown and the modal is populated with JSON data. The application /addresschecker checks against the addresses posted and sends me an error message if I get a code return number of 2003. If not I select the return data via JSON using jQuery's $.each
The application works but when I close the modal, refill out the form and click submit, the form does not make a new call to /addresschecker I looked in my network tab of chrome and it seems to be using the old data. I am thinking that I need to force a new Ajax call everytime a user clicks on the submit button or clear the cache somehow. Not sure why I'm seeing old data
<form id="Validate">
<input class="form-control" id="adr1" name="address1" type="text" placeholder="Address 1" />
<input class="form-control" id="adr2" name="address1" type="text" placeholder="Address 1" />
<button type="submit" >Submit</button>
</form>
<div class="modal hide">
<!-- JSON Data returned -->
<div id="Message_1"></div>
<div id="Message_2"></div>
<div id="error_message"></div>
</div>
// My main form code
submitHandler: function(form) {
$.ajax({
url: '/addresschecker',
type: 'post',
cache: false,
dataType: 'json',
data: $('form#Validate').serialize(),
success: handleData
});
function handleData(data) {
var mesgcheck = data.message;
if (data.code == '2003') {
$("#error_messag").html(mesgcheck);
} else {
// Display Modal
$(".modal").removeClass("hide");
$.each(data, function(i, suggest) {
$(".adr1").val(suggest.address1);
$(".adr2").val(suggest.address2);
});
}
}
}
Let ajax handle your request.
Use this:
<input type="button" value="submit">
Instead of type submit.

Submitting AJAX form when a field is changed

I have a GET form that when submitted uses an AJAX request to update a php page.
I want this form to automatically submit any time a field is changed, the form contains mostly text inputs and a few dropdowns.
What I have tried:
onchange="this.form.submit()" - This works, but instead of AJAXing the data to the php page, it actually redirects me to the page, which is a no go.
<input type="submit"> - I would like this to be a last resort, because I want the form to send automatically, but it does work otherwise.
I know that sending a form every input change isn't usually a good idea, so ideally I would like it to send the form 1-2 seconds after inactivity (After inputting something obviously) - if that isn't possible, then every time a field is changed would be acceptable as its a low traffic server.
So my question is, what is the proper way to send a form via ajax automatically?
My current :
<form method="GET" id="submitRequest" action="showTable.php">
<th><input type="text" id="SSeries" name="SSeries" class="form-control"></th>
<th><input type="text" id="SModel" name="SModel" class="form-control"></th>
<th><input type="text" id="SSerial" name="SSerial" class="form-control"></th>
<th><input type="text" id="SColor" name="SColor" class="form-control"></th>
<th><input type="text" id="SStorage" name="SStorage" class="form-control"></th>
<th><input type="text" id="SCarrier" name="SCarrier" class="form-control"></th>
<th><input type="text" id="SType" name="SType" class="form-control"></th>
<th><input type="text" id="SUPC" name="SUPC" class="form-control"></th>
<th><input type="text" id="SStatus" name="SStatus" class="form-control"></th>
<input type="submit" class="btn btn-success">
</form>
My current AJAX:
$(document).ready(function() {
$('#submitRequest').submit( function( event ) {
$.ajax({ // create an AJAX call...
data: $('#submitRequest').serialize(), // serialize the form
type: $('#submitRequest').attr('method'), // GET or POST from the form
url: $('#submitRequest').attr('action'), // the file to call from the form
success: function(response) { // on success..
showTable();
}
});
event.preventDefault();
});
});
try this:
When input value change then form will submit,
jQuery("#submitRequest input").change(function(){
$('#submitRequest').submit();
});
I was able to fix my problem by simply changing my jquery selection and function.
I changed it from
$('#submitRequest').submit( function( event ) {
To
$('.submitForm').on('keyup', function(){
and I added submitForm to each inputs class.
You can make a post in ajax after change, and get a response from server
$("#submitRequest input").change(function(){
var data = {
SSeries : $("#SSeries").val(),
...
}
$.ajax({
url: 'your_url_method',
type: 'POST',
data: data,
success : function(res){
showTable();
console.log("Success, you submit your form" + res);
},
error : function(error){
console.log(error, "Error in submit")
}
});
});

Make a Post request with request body from HTML form

I am working on a html page which is supposed to submit a post request with request body to my server like below
<html>
<head>Customer app</head>
<body>
<div>
<table>
<tr>
<td>Customer Id :</td>
<td>
<form name="submitform" method="post">
<input type="text" id="customerId" name="customerId"/>
<input type="submit" value="Submit">
</form>
</td>
</tr>
</table>
</div>
</body>
<script>
$(document).ready(function(){
$("#submitform").click(function(e)
{
var MyForm = JSON.stringify($("#customerId").serializeJSON());
console.log(MyForm);
$.ajax({
url : "http://localhost:7777/ola-drive/customer/ride",
type: "POST",
data : MyForm,
});
e.preventDefault(); //STOP default action
});
});
</script>
</html>
It does not work as expected throwing 404 Not Found getting redirected to http://localhost:7777/customerapp.html. But form data corresponding to the request submission seems to be correct.
Can someone help me fix the issue with my html code submit POST request redirection ?
Your issue is in this line:
$("#submitform").click(function(e)
Your form does not have an id but a name, so you can write:
$('[name="submitform"]').click(function(e)
That is the reason because your form is giving you a redirection error.
$('[name="submitform"]').click(function (e) {
e.preventDefault();
$.ajax({
url: "http://localhost:7777/ola-drive/customer/ride",
type: "POST",
data: {"customerId": $("#customerId").val()},
success: function (result) {
//do somthing here
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<table>
<tr>
<td>Customer Id :</td>
<td>
<form name="submitform" method="post">
<input type="text" id="customerId" name="customerId"/>
<input type="submit" value="Submit">
</form>
</td></tr>
</table>
</div>
You are already created form using html, you can add action attrbiute with value for post url like
<form name="submitform" method="post" action="/ola-drive/customer/ride">
Unless you want to use ajax, you create your data form manually
you have this:
$("#submitform").click(function(e){...}
The first problem is you are selecting an input tag, instead the Form. The second is rather the action desired, in this case should be "submit". And if you already are using JQuery you might be interested in save some space using the method 'serialize()'. Try:
$('form').on('sumbit', function(e){
e.preventDefault();
$.ajax({
url: // your path
type: 'post',
data: $(this).seialize(),
...})
})
And use an id for Form, it's easier to select it.

Categories

Resources