Ajax Call before submitting the form - javascript

I need to check whether the data is already exists in the database before submitting the form using ajax. The most common scenario is the checking the availability of the username and email.
It's not working but I tested the ajax function without using the from control and it works fine. The project is created in MVC 3 VB.
Javascript:
$('#addSalesPeople').click(function () {
$.post("ajax_functions/checkDuplicate.cshtml",
{
extension: document.getElementById('Extension').value,
initials: document.getElementById('Initials').value
},
function (data, status) {
alert("Data: " + data + "\nStatus: " + status);
});
});
HTML:
#Using Html.BeginForm("Create", "SalesPeople", FormMethod.Post)
#Html.ValidationSummary(True)
#<fieldset>
............................
..............................
#Html.TextBoxFor(Function(model) model.Extension, New With {.onkeyup = "javascript: charCounter(this,4);", .onblur = "javascript: zeroPad(this, 4)"})
#Html.TextBoxFor(Function(model) model.Initials)
<input id="addSalesPeople" class="btn span2" type="submit" value="Add" />
</fieldset>
-Thanks

You need to observe the submit event of the form.
Instead of
$('#addSalesPeople').click(function () {
use
$('#theFormId').submit(function () {
see: http://api.jquery.com/submit/
You can also disable the form submit and send it later manually:
$( '#theFormId' ).submit( function ( event ) {
event.preventDefault();
/* your AJAX code */
$( '#theFormId' ).submit();
} );

I am posting a real tested code.
HTML: Simple form post button in #using
(Html.BeginForm())
{
//use your text box or other control here
<input type="submit" id="Create" value="Create" class="btn btn-primary" />
}
JavaScript:
<script>
$(document).ready(function () {
$("form").submit(function (e) {
e.preventDefault(); //prevent default form submit
if ($(this).valid()) {
var UserId= $('#UserId').val();
$.ajax({
url: '/Home/CheckUserExist/', //ControllerName/ActionName/
data: {
UserId: UserId
},
success: function (data) {
showMsg(data);
},
cache: false
});
}
});
});
function showMsg(hasCurrentJob) {
if (hasCurrentJob != "OK") {
alert(hasCurrentJob);
return false;
} else {
//if check is ok than from post to controller
$("form").unbind('submit').submit();
}
}
</script>
MVC Controller:
public async Task<JsonResult> CheckUserExist(int UserId)
{
//condition for user check
if (UserExist==true)
{
return Json("User Exist Please choose another user name or etc", JsonRequestBehavior.AllowGet);
}
return Json("OK", JsonRequestBehavior.AllowGet);
}
if you have any query mail me vishalroxx7#gmail.com.

Related

send model to MVC C# controllerĀ“s action via button click event jQuery

I,ve been working on a MVC C# project and I need to send the info (model) from my View to the due controller action but after managing some validations via jQuery and the click event of the submit button, here is the javascript code on click of submit button and its validation (works fine)
$("#sentInfo").click(function (e) {
e.preventDefault();
$("#idProveedor").val(proveedor);
$("#idacme").val('ingresar');
var table = $('#myTable');
table.find('tbody tr').each(function (index, tr) {
if ($(tr).find("td:eq(2)").html() === $("#idDUI").val()) {
alert('ya existe el DUI');
exit;
}
else if ($(tr).find("td:eq(3)").html() === $("#idISSS").val()) {
alert('ya existe el ISSS');
exit;
}
else {
$("form").submit();
}
});
});
the code above sets the values to the #idProveedor and #idacme inputs and also validate if the DUI or ISSS already exists but if the values already exist it always send the model to the action and what I want that if ISSS or DUI values exists then the model shouldn't be send to the action method.
Can anyone help me?
this is my form code
#using (Html.BeginForm("EnviarEALG", "Home", FormMethod.Post, new { #class = "form-horizontal", role = "form", id = "FormEmp" }))
{
...
some code goes here
...
<input type="submit" value="Ingresar Empleado" class="btn btn-info" id="sentInfo" />
}
this is the code with modifications:
$("#sentInfo").click(function (e) {
e.preventDefault();
$("#idProveedor").val(proveedor);
$("#idacme").val('ingresar');
var table = $('#myTable');
table.find('tbody tr').each(function (index, tr) {
if ($(tr).find("td:eq(2)").html() === $("#idDUI").val()) {
alert('ya existe el DUI');
exit;
}
else if ($(tr).find("td:eq(3)").html() === $("#idISSS").val()) {
alert('ya existe el ISSS');
exit;
}
else {
$("FormEmp").submit();
}
});
});
and the button
<input type="button" value="Ingresar Empleado" class="btn btn-info" id="sentInfo" />
One solution is to use ajax to send your data from your view to your controller. I use this often and might be a good solution for you since you are using a jQuery click event. Below is an untested example but it will give you an idea of how to do it.
function Save(model){
var data = {
'modelNameToPass': model
}
$.ajax({
url: "/Home/EnviarEALG", // "/ControllerName/Method"
data: data,
type: "POST",
success: function(response){
//code to do something on success
},
error: function(response){
//do error stuff here
}
});
}
Then your controller should already be set up like this..
[HttpPost]
public ActionResult EnviarEALG(DataModel modelNameToPass)
{
}
Hopefully this helps!

two submit buttons within the same form

I have a form with two submit buttons, one for create, one for edit
<div class="modal-footer">
<button name="add" class="companyCreateSubmitBtn ladda-button btn btn-primary" data-style="zoom-in" data-spinner-size="25" onclick="CompanyCreate()">Add</button>
<button name="edit" class="companyEditSubmitBtn ladda-button btn btn-primary" data-style="zoom-in" data-spinner-size="25" onclick="CompanyEdit()">Save</button>
</div>
Here are my onclick functions:
function CompanyCreate() {
//work experience create
$("#companyForm").submit(function (event) {
//validate form
if (!$(this).valid()) {
return;
}
//serialize the form
serializedForm = $(this).serializeArray();
cvId = $("#CVId").val();
serializedForm.push({ name: "cvId", value: cvId });
//ajax post
$.ajax({
url: "#Url.Action("CompanyCreate", "CV")",
type: "POST",
data: serializedForm,
beforeSend: function () {
l.ladda("start");
},
success: function (result) {
if (result.success) {
//add row to table
cTable.fnAddData([
result.id,
result.name,
result.title,
result.city,
result.country,
$.datepicker.formatDate("dd/mm/yy", new Date(parseInt(result.startdate.substr(6)))),
$.datepicker.formatDate("dd/mm/yy", new Date(parseInt(result.enddate.substr(6)))),
result.description,
"<button class='companyEditBtn btn'' title='Edit Work Experience'><i class='icon-pencil'></i></button>" + " " + "<button class='companyDeleteBtn btn'><i class='icon-trash'></i></button>"
]);
//success
toastrSuccess(result.message);
} else {
//fail
toastrError(result.message);
}
},
error: function (jqXHR, textStatus, errorThrown) {
//fail
toastrError(textStatus);
},
complete: function () {
//stop ladda button loading
l.ladda("stop");
//hide modal
$(".modal").modal("hide");
}
});
//prevent default submit behaviour
event.preventDefault();
event.stopImmediatePropagation();
});
}
function CompanyEdit() {
//work experience edit
$("#companyForm").submit(function (event) {
//validate form
if (!$(this).valid()) {
return;
}
//serialize the form
serializedForm = $(this).serialize();
//ajax post
$.ajax({
url: "#Url.Action("CompanyEdit", "CV")",
type: "POST",
data: serializedForm,
beforeSend: function () {
l.ladda("start");
},
success: function (result) {
if (result.success) {
//update row of table
cTable.fnUpdate([
result.id,
result.name,
result.title,
result.city,
result.country,
$.datepicker.formatDate("dd/mm/yy", new Date(parseInt(result.startdate.substr(6)))),
$.datepicker.formatDate("dd/mm/yy", new Date(parseInt(result.enddate.substr(6)))),
result.description,
"<button class='companyEditBtn btn'' title='Edit Work Experience'><i class='icon-pencil'></i></button>" + " " + "<button class='companyDeleteBtn btn' title='Delete Work Experience'><i class='icon-trash'></i></button>"
], position);
toastrSuccess(result.message);
} else {
toastrError(result.message);
}
},
error: function (jqXHR, textStatus, errorThrown) {
toastrError(textStatus);
},
complete: function () {
//stop ladda button loading
l.ladda("stop");
//hide modal
$(".modal").modal("hide");
}
});
//prevent default submit behaviour
event.preventDefault();
event.stopImmediatePropagation();
});
}
Every time i click the Save button, it goes to the CompanyCreate() function instead of the CompanyEdit() function, what am i doing wrong?
You can do something as follows:
$('#companyForm').on('submit', function(e) {
e.preventDefault(); // stops form from being submitted
// get the clicked button name
var clickedButton = $(document.activeElement).attr('name');
if (clickedButton === 'edit') {
companyEdit();
}
if (clickedButton === 'add') {
companyAdd();
}
});
function companyEdit() {
// your code to edit company
alert('editing company');
}
function companyAdd() {
// your code to add company
alert('adding company');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modal-footer">
<form id="companyForm">
<button name="add" class="companyCreateSubmitBtn ladda-button btn btn-primary" data-style="zoom-in" data-spinner-size="25">Add</button>
<button name="edit" class="companyEditSubmitBtn ladda-button btn btn-primary" data-style="zoom-in" data-spinner-size="25">Save</button>
</form>
</div>
UPDATE
If you do not wish to use the former example, you can simply do the following. Not that using events like onclick in the dom is considered as bad practice and should be done in javascript.
$('.companyEditSubmitBtn').on('click', function(e) {
e.preventDefault(); // stops form from being submitted
alert('editing company');
});
$('.companyCreateSubmitBtn').on('click', function(e) {
e.preventDefault(); // stops form from being submitted
alert('creating company');
});
Here is working js-fiddle
<div class="modal-footer">
<button type="button" id="CompanyCreate" name="add" class="companyCreateSubmitBtn ladda-button btn btn-primary" data-style="zoom-in" data-spinner-size="25">Add</button>
<button type="button" id="CompanyEdit" name="edit" class="companyEditSubmitBtn ladda-button btn btn-primary" data-style="zoom-in" data-spinner-size="25">Save</button>
</div>
Jquery code is
$(document).ready(function () {
$("#CompanyCreate").click(function () {
//your code here
});
$("#CompanyEdit").click(function () {
//your code here
});
});
Simple pattern I use (MVC based):
1. Create custom attribute
[AttributeUsage(AttributeTargets.Method)]
public class MultipleButtonAttribute : ActionNameSelectorAttribute
{
public string Name { get; set; }
public string Argument { get; set; }
public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
{
var isValidName = false;
var keyValue = string.Format("{0}:{1}", Name, Argument);
var value = controllerContext.Controller.ValueProvider.GetValue(keyValue);
if (value != null)
{
controllerContext.Controller.ControllerContext.RouteData.Values[Name] = Argument;
isValidName = true;
}
return isValidName;
}
}
2. Controller
MultipleButton(Name = "action", Argument = "Action1")
public ActionResult Action1(MyModel model)
{...}
[MultipleButton(Name = "action", Argument = "Action2")
public ActionResult Action2(MyModel model)")]
{...}
3. View
#using (Ajax.BeginForm("Action1", "Search", new AjaxOptions { }))
{
<button type="submit" name="action:Action1" >Action1</button>
<button type="submit" name="action:Action2" >Action2</button>
}
Prevent using .submit function inside .click, it will not work, instead you have to grab the form and post it.
NO
$("#companyCreateSubmitBtn").click(function () {
$("#companyForm").submit(function (event) {
//validate form
if (!$(this).valid()) {
return;
}
//prevent default submit
event.preventDefault();
//ajax post etc...
YES
$("#companyCreateSubmitBtn").click(function () {
//get the form
var form = $("#companyForm");
//validate form
if (!form.valid()) {
return;
}
//ajax post etc..
Remember your button type has to be type="button" instead of the default type="submit"
<button id="companyCreateSubmitBtn" name="add" class="ladda-button btn btn-primary" data-style="zoom-in" data-spinner-size="25" type="button">Add</button>

how to get ajax response to trigger click

I have two forms for buy now and for pincode when I click buynow button sending request through ajax and same thing is done for pincode form also.
HTML
<form method="POST" action="/cart/add" id="myForm">
.....
....
<input type="button" class="buyNowBtn" id="btnBuyNow"/>
</form>
<form action="#">
<input type="text" id="pinCheck" class="pinCheck" placeholder="enter pin code" />
<button class="btn btn-info" id="pinCheckTest"> Check</button>
</form>
In the same buynow click event I need to trigger a pincode submit button, so I did this
(document).on('click', '#btnBuyNow', function (e) {
....
....
$("#pinCheckTest").trigger('click');
....
});
the above trigger event is successfully calling pincode click event
$('#pinCheckTest').click(function () {
$.ajax({
type: 'GET',
url: url,
success: function (output) {
if (output == 'true') {
}
else{
}
}
});
but I need to get ajax response back to trigger event so that I can do some operation is it possible?
something like
(document).on('click', '#btnBuyNow', function (e) {
....
....
$var output=$("#pinCheckTest").trigger('click');//I need to get ajax response back to this click
if(output=='true'){
......
}else{
.....
}
....
});
You can define a variable outside of both click handlers, when .trigger() is called, assign $.ajax() to variable, use .then() within first click handler to process results of $.ajax() call.
Note, included event.preventDefault() to prevent submission of <form>, as pointed out by #IsmailRBOUH
var dfd;
$(document).on('click', '#btnBuyNow', function (e) {
e.preventDefault();
....
....
$("#pinCheckTest").trigger('click');
if (dfd) {
dfd.then(function(output) {
// do stuff with output
console.log(output)
})
}
....
});
$('#pinCheckTest').click(function (e) {
e.preventDefault();
dfd = $.ajax({
type: 'GET',
url: url,
success: function (output) {
if (output == 'true') {}
else{};
}
})
});
var dfd;
$("#first").click(function() {
$("#second").trigger("click");
if (dfd) {
dfd.then(function(data) {
alert(data)
})
}
})
$("#second").click(function() {
// do ajax stuff
dfd = $.when("second clicked")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="first">first button</button>
<button id="second">second button</button>
Since you are binding the click event to a button inside form you have the prevent the default behaviour which is 'submit the form'. Change you code to :
$('#pinCheckTest').click(function (e) {
e.preventDefault();
//Your ajax call
});
Here is a demo to clarify the difference https://jsfiddle.net/qvjjo3jk/.
Update1:
Add an id to your form:
<form action="#" id="pinCheckForm">
<input type="text" id="pinCheck" class="pinCheck" placeholder="enter pin code" />
<button class="btn btn-info" id="pinCheckTest"> Check</button>
</form>
Then:
$('#pinCheckForm').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: url,
data: $(this).serialize(), //Sends all form data
success: function(output) {
if (output == 'true') {} else {}
}
});
});

Ajax call just before form submitting does not work

I've got a Spring MVC - JSP web application. Before submitting a specific form I need to fill a text value input with JS/jQuery so the form POSTed contains that info. This text value is the result of an ajax call that should be done when the submit button is clicked but before the form data is send to the controller.
The relevant pieces of code in my JSP are the following:
<script>
//Gets from model a new valid file code number
function getFileCodeNumber(res){
$.ajax({
type: "post",
url: "getFileCodeNumber",
cache: false,
data: { department: $("#department").val(), docType: $("#docType").val() },
success: res,
error: function(){ alert('Error while request..');}
});
}
</script>
<script>
$(function() {
//Other JS code
$("#submitForm").click((function(event) {
if($("#chkLanguage").prop('checked')){
//some stuff
}else{
getFileCodeNumber(function(data){
//do some stuff with 'data'
});
}
}));
});
</script>
<form:form id="form" class="form-horizontal" method="post" action="AddDoc" commandName="document" enctype="multipart/form-data">
<div class="row" style="text-align:center;">
<input id="submitForm" type="submit" class="btn btn-primary btn-lg" name="commit" value="Finish">
</div>
</br>
</form:form>
Just to let you know, the ajax call works perfectly when called from another trigger action in the same JSP, but when called from the "click" function it retrieves an alert error but is shown on screen for less than 1 second and therefore I cannot tell you what does it say. By the way, Firebug throws "NS_ERROR_NOT_AVAILABLE: prompt aborted by user".
Note that I tried to replace "click" trigger for "submit" that happens exactly the same. My guess would be that the form is being submitted before the ajax call is completely done, but I expected "submit" and "click" functions to do the its job before POSTing the data.
Does anybody have a clue?
EDIT : I found out that the alert that I wasn't able to see is printing the error code of the ajax call. However, I've checked the controller's function that gives response to this call and I've seen it gets completed succesfully and retrieves the expected value. What's more, when I call this function from another trigger in the same JSP it works perfectly. Just to let you see the simple code in the controller:
#RequestMapping(value = "getFileCodeNumber", method = RequestMethod.POST, headers = "Accept=*/*")
public #ResponseBody
String getFileCodeNumber(#RequestParam(value = "department", required = true) String department,
#RequestParam(value = "docType", required = true) String docType) {
int n = cdocs.getNewCode(department, docType);
if (n == 0) {
return "EEEE";
} else {
char[] zeros = new char[4];
Arrays.fill(zeros, '0');
DecimalFormat df = new DecimalFormat(String.valueOf(zeros));
System.out.println(df.format(n));
return df.format(n);
}//END_IF
}//END_METHOD
Any ideas?
Try that:
function getFileCodeNumber(res) {
return $.ajax({
type: "post",
url: "getFileCodeNumber",
cache: false,
data: {
department: $("#department").val(),
docType: $("#docType").val()
},
success: res,
error: function () {
alert('Error while request..');
}
});
}
$("#submitForm").click(function (event) {
event.preventDefault();
if ($("#chkLanguage").prop('checked')) {
//some stuff
} else {
getFileCodeNumber(function (data) {
//do some stuff with 'data'
}).done(function () {
$('#form').get(0).submit();
});
}
});
Instead of executing your javascript when the submitbutton is pressed, use a normal button and execute the submit function from the script.
You could do something like this:
function getFileCodeNumber(res){
$.ajax({
type: "post",
url: "getFileCodeNumber",
cache: false,
data: { department: $("#department").val(), docType: $("#docType").val() },
success: res,
error: function(){ alert('Error while request..');}
})
}
$(function() {
if($("#chkLanguage").prop('checked')){
//some stuff
$("#form").submit();
}else{
getFileCodeNumber(function(data){
//do some stuff with 'data'
}).done(function(){
$("#form").submit();
});;
}
});

Two submit buttons in Ajax.BeginForm. Need to call different js functions in OnSuccess

I have an Ajax form on my MVC page, with two separate submit buttons...
#using (Ajax.BeginForm("Save", "Company", new AjaxOptions() {
HttpMethod="Post", OnSuccess="closeForm"
}, new {#id = "companyEditForm"})) {
....some edit fields......
<input type="submit" value="Save & Next"/>
<input type="submit" value="Save" />
}
I would like to call a different js function after the form is submitted with the "Save & Next" button. So if the user clicks the "Save" button, it should submit the form then call the "closeForm" javascript function. If the user clicks the "Save & Next" button, it should submit the form, then call the "nextForm" javascript function. Is there a simple way of achieving this?
Is there a simple way of achieving this?
No, but you could have the controller action pass the button that was clicked in the result. This could be done either as a Json property (if you are returning JSON) or it could also be a custom response HTTP header.
And then inside your success callback (which can only be one) you could retrieve this value in order to know which button was clicked and act accordingly.
So, start by giving a name to your submit button so that you know which one was clicked:
#using (Ajax.BeginForm("Save", "Company", new AjaxOptions() {
HttpMethod="Post", OnSuccess="onSuccess"
}, new { id = "companyEditForm" })) {
....some edit fields......
<button type="submit" name="btn" value="save_next">Save & Next</button>
<button type="submit" name="btn" value="save">Save</button>
}
And then inside your controller action
[HttpPost]
public ActionResult Save(MyViewModel model)
{
Response.AppendHeader("X-Button", Request["btn"]);
... your usual processing
}
and finally inside your onSucecss callback:
function onSuccess(data, status, xhr) {
function onSuccess(data, status, xhr) {
var btn = xhr.getResponseHeader('X-Button');
if (btn == 'save_next') {
// The "Save & Next" button was clicked
} else if (btn == 'save') {
// The "Save" button was clicked
} else {
// The user didn't submit the form by using the mouse and
// clicking on a button, he simply pressed Enter while
// inside some text field or you have some other portion of
// javascript which triggered the form submission without pressing
// on any submit button
}
}
}
You could switch from Ajax.BeginForm() to Html.BeginForm() and then use JQuery to submit your form.
<script type="text/javascript">
$('#save').on('click', function () {
var form = $('form');
$.ajax({
url: form.attr('action'),
type: 'post',
data: form.serialize(),
success: function (result) {
// call another function
}
});
return false;
});
$('#saveAndEdit').on('click', function() {
$.ajax({
url: form.attr('action'),
type: 'post',
data: form.serialize(),
success: function (result) {
// call another function
}
});
return false;
});
</script>
You can also write something like this:
#using (Ajax.BeginForm("Save", "Company", new AjaxOptions() {
HttpMethod="Post", OnSuccess="closeForm"
}, new { id = "companyEditForm" })) {
<input type="submit" onclick="showNextForm = true;">Save & Next</button>
<input type="submit" onclick="showNextForm = false;">Save</button>
}
...
var showNextForm = false;
function closeForm(data) {
if(showNextForm) {
nextForm();
}
else {
// do your stuff
}
}

Categories