I have problem with buttons, I typed alert("") to be sure if it enters to function or not,I discovered that it enters into function after I click on button and the alert works fine but, anything else inside function does not work neither ajax nor any simple jquery code. I will add the code to be more clarified.
for example these buttons below
<button type="button" id="submitX" class="btn btn-primary">Submit</button>
<button type="submit" id="cancelX" class="btn btn-default">Cancel</button>
This javascript code
$(document).ready(function () {
$(document).on("click", "#cancelX", function (event) {
alert('cancel function');
window.location.href = "www.test.com";
});
$(document).on("click", "#submitX", function (event) {
alert('submit function');
var Details = $('#Detail').summernote('code');
var params = [];
params.push({ name: "CreatedBy", value: $('#Email').val() });
params.push({ name: "Detail", value: Details});
var apiURL = "<%= ResolveUrl("~/api/Submit/") %>";
$.ajax({
url: apiURL,
data: params,
type: "POST",
success: function (data, textStatus, jqXHR) {
window.location.href = "www.test.com";
},
error: function (err) {
swal({
text: "An error occured.",
icon: "error"
});
}
})
});
});
why are both buttons or functions not working properly ? did I do anything wrong here ?
Try to remove document.ready() function on click event of cancel and submit button.Use below syntax:
$("#id_name").click(function (event) {
..//Code
});
And also remove type submit on which is given in submit button.Just make it simple button.
try changing your 'button' tag to 'input' tag as you are using the type attribute.
Hope it works.
Related
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 3 years ago.
I can't figure out why the form redirects after being submitted. So, this is how my code works: When the mouse is entered (mouseenter) the button edit appears. When this button is clicked I send ajax request to the server, and I get as response a form with select options, so far so good. But, when I choose (select) something and hit update, the form redirects despite the fact that I wrote evt.preventDefault(), and subsequently ajax failed working. I got stuck and I can't figure out where the bug is. I appreciate any suggestions. Thanks in advance. Here is my code:
$('div.js-service-company').mouseenter(function(evt) {
const thisDiv = $(this);
const link = $(this).children().children('a');
const p = $(this).children();
let url = link.attr('href');
let currentTicketState = url.substring(url.lastIndexOf('=') + 1);
const ticketId = link.attr('data-id');
if (allowedTicketStates.includes(currentTicketState)) {
const btn = $('<button/>', {
type: 'submit',
name: 'serviceCompanyData',
class: 'btn btn-success btn-sm btn-edit-service-company',
text: 'Edit'
});
p.append(btn);
$('button.btn-edit-service-company').click(function(btn) {
btn.preventDefault();
const thisBtn = $(this);
$.ajax({
type: "GET",
url: '{{ path('
admin_cms3_core_ticket_getServiceCompany ') }}',
data: {
ticketId: ticketId,
},
success: response => {
link.parent('p').append(response);
link.hide();
thisBtn.hide();
$('div.js-service-company').off("mouseenter");
},
error: (jqXHR, textStatus) => {
console.log("Error occurred: " + textStatus)
}
});
});
// this is where the form submission occurres
$('form#service-company-form').submit(function(evt2) {
evt2.preventDefault();
const form = $(this);
const type = form.attr('method');
const thisUrl = form.attr('action');
$.ajax({
type,
url: thisUrl,
data: form.serialize(),
dataType: 'json',
async: false,
success: response => {
$('body div').removeClass("loader_wrap loader_background");
form.hide();
link.text(response.serviceCompany);
link.show();
},
error: err => {
console.log(err)
}
});
});
}
}).mouseleave(function() {
$('button.btn-edit-service-company').hide();
const objectId = $(this).attr('data-id');
$('.service_company-'.concat(`${objectId}`)).hide();
});
The html code:
<td class="sonata-ba-list-field sonata-ba-list-field-string" objectid="326966">
<div class="js-service-company">
<p>
<a data-id="326966" href="/app_dev.php/cms3/core/company/6/show?state=closed1">Text_01</a>
</p>
Company Name
</div>
</td>
The event you got is selecting an element which is not present in DOM. After your ajax call you inject new markup to the dom. To bind your events to these elements you can use the .on method:
$(document).on('submit', 'form#service-company-form', function (evt2) {
evt2.preventDefault();
// ...
});
As mplungjan suggested is this syntax better
$('#service-company-form').on('submit', function (evt2) {
evt2.preventDefault();
// ...
});
because jQuery will not listen on every submits in document and filter for the selector. This will only fire when #service-company-form is submitted.
I've small JS code which is not working as per my need.
Actually my backend PHP code contains so many functions which i want to process by pressing submit button and meantime i also want to show the status "Scanning" in place of submit button and when the data got fully processed, then i want to show "Completed" Status in place of submit button.
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'post.php',
data: $('form').serialize(),
success: function () {
$(#response).show();
$(#form).hide();
}
});
});
});
</script>
You can simply show whatever you want when user clicks the button. And when you get the response you can change to whatever you want. Something like.
This is just an example of mocking your ajax request.
var $button = $("#btn");
$button.click(function() {
$button.text("Scanning...");
var promise = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('foo');
}, 5000);
});
promise.then(function(){
$button.text("Done");
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn"> Submit </button>
You can use beforeSend...
beforeSend is a pre-request callback function that can be used to modify the jqXHR..
You can refer here for more detail.
And you can follow my code below for your ease.
..
Javascript:
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
let submitBtnEl = $(this).find('button[type="submit"]'); //submit button element
$.ajax({
type: 'post',
url: 'post.php',
data: $('form').serialize(),
beforeSend: function( xhr ) {
submitBtnEl.html('Scanning'); //the submit button text will change after click submit
},
success: function () {
$(#response).show();
$(#form).hide();
submitBtnEl.html('Completed'); //the submit button text will change after the form is completely submit
}
});
});
});
</script>
.
.
HTML:
<form>
<input type="text" name="input1" />
<button type="submit">Submit</button>
</form>
.
.
For your ease, you can try the code on this fiddle
Form validation works, but I can't get the Ajax call to fire correctly. The submitHandler is being reached, but the Ajax call isn't. I have included a Fiddle at the bottom, but obviously you can't fire ajax calls from there.
$(".player-code, .submit").hide();
//VALIDATION
$(function () {
$("#form").validate({
rules: {
playerClass: {
required: true
}
},
submitHandler: function () {
var accountNumber = $(".accountNumber").val();
var domain = $(".domain").val();
var playerClass = $(".playerClass").val();
var dataString = accountNumber + playerClass;
//Save Form Data........
$.ajax({
type: "POST",
dataType: "json",
url: "/",
contentType: "application/json",
data: dataString,
success: function () {
$(".player-code").show();
$('.render-info').html("<div class='alert alert-success'>You've successfully built your player code</div>");
},
failure: function () {
$('.render-info').html("<div class='alert alert-failure'>Submission Error</div>");
}
});
}
});
});
jQuery.validator.addMethod("domainChk", function (value, element, params) {
if (this.optional(element)) return true;
var regExp = new RegExp("^(?!www\\.|http:\/\/www\.)(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\\.)+([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$");
return regExp.test(value);
}, "Valid hostname required for player code");
jQuery.validator.addClassRules({
domainChk: {
domainChk: true
}
});
$('input[type="text"]').on('click keyup blur', function () {
if ($('#form').valid()) {
$(".submit").show();
} else {
$(".submit").hide();
}
});
//PREPOPULATE ACCOUNT FROM QUERY STRING
var url = window.location.href;
var regex = /=.*/; // match '=' and capture everything that follows
var accountId = url.match(regex);
$(".accountNumber").val(accountId).remove("=");
//
jsFiddle: Link
There is no failure: option for $.ajax(). If you want to see any errors that happen in the ajax call, then use error: to capture the error.
To make form submit you should use
<button class="btn btn-default submit" type="submit">Submit</button>
instead of <div class="btn btn-default submit">Submit</div>
submitHandler will be called only on native form submit.
Fiddle
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();
});;
}
});
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
}
}