Form wont submit with ajax, but will normally - javascript

Consider the following code:
$('.saveCheck').on('click',function()
{
var frm = $(this).parents('form');
frm.submit(function (ev)
{
$.ajax
({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data)
{alert("hooray!");}
});
ev.preventDefault();
});
});
This will not submit my form, however:
frm.submit();
On its own works fine, but wont have any of the AJAX goodness.
Is there any glaringly obvious reason for this?

You code is set up so that when saveCheck is clicked it will bind a submit handler so that when the form is later submitted, it will call the Ajax function.
It sounds like what you want to do is to just run the Ajax function when saveCheck is clicked. Get rid of your submit handler binding entirely.
$('.saveCheck').on('click', function(ev) {
var frm = $(this).parents('form');
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function(data) {
alert("hooray!");
}
});
ev.preventDefault();
});
That said, you should probably be using a submit handler on the form instead of a click handler on a button.

Related

How to put a loader in ajax requests?

One is a small code that allows me to view error messages when the form fields are empty or when everything is fine. What I would like to do is enter a loader or text to indicate that the submitted action is being processed. I really don't know where to start, can someone help me understand how to achieve this?
jQuery(document).ready(function($) {
$('.mts-edit-account').on('submit', function(e) {
e.preventDefault();
//Ajax Handling Error
var $form = $(this);
jQuery.post(
$form.attr('action'),
$form.serialize(),
function(data) {
jQuery('.newdiv').html(data);
}, 'json',
);
//Ajax function
jQuery.ajax({
type: "post",
data: jQuery(".mts-edit-account").serialize(),
});
});
});
Firstly put the loader in your HTML file where you want to display it. i.e: below the submit button
<img
src="https://thumbs.gfycat.com/PessimisticGlamorousDunnart-size_restricted.gif"
class="loader"
alt="Loader"
height=25
width=25
>
Then add CSS for this loader:
.loader{
display:none;
}
Then put the below code in jQuery:
jQuery(document).ready(function($) {
$('.mts-edit-account').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "your_url",
data: $(".mts-edit-account").serialize(),
beforeSend: function() {
$(".loader").show();
},
success: function(msg) {
$(".loader").hide();
}
});
});
});
AJAX requests using jQuery allows you to handle request completion, failure or success using the returned value from ajax() function. In your case you need to start by showing the loader before starting the request, then hide on completion. To do that, you can use always() function. That will make sure it's always called in case of success or failure.
// Show loader
jQuery.ajax({
// ..
}).always(() => {
// Hide loader
});

Submit button in a header fails to submit

i'm developing a jquery mobile app. In the app there is a form which the user has to submit and i've placed the submit button in the right side in the header. when the user is done with filling of the form and taps on the submit button with a class of "ui-btn-right", it fails to submit.
$(document).ready(function(){
$('.ui-btn-right').on('click', function(event) {
$("#form1").on('submit',function(event){
event.preventDefault();
data = $(this).serialize();
$.ajax({
type: "POST",
url: "register.php",
data: data
}).success(function() {
$("input[type=text]").val("");
});
});
});
});
HTML
<a href='#' class='ui-btn-right' id="button" >Register</a>
Just taking a guess here, as we can't see your markup. But it looks like you're not actually submitting the form when you click the button, you're just wiring up the submit event. Try this?
$(document).ready(function(){
$('.ui-btn-right').on('click', function(event) {
$('#form1').submit();
});
$("#form1").on('submit',function(event){
event.preventDefault();
data = $(this).serialize();
$.ajax({
type: "POST",
url: "register.php",
data: data
}).success(function() {
$("input[type=text]").val("");
});
});
});
Try this?
$(document).ready(function(){
$("#form1").on('submit',function(event){
event.preventDefault();
data = $(this).serialize();
$.ajax({
type: "POST",
url: "register.php",
data: data
}).success(function() {
$("input[type=text]").val("");
});
});
$('.ui-btn-right').on('click', function(event) {
$("#form1").submit(event);
});
});
If your button is not in the form and you want to fired the submit event you have to do something like:
$('.ui-btn-right').on('click', function(event) {
$("#form1").submit(function(event){
event.preventDefault();
stuff();
});
});
Probably I need more data to give answer,but we can go this way.
$('.ui-btn-right').on('click', function(event) {
check here any alert/console message is working
}
now you have create $("#form1").on('submit
but to submit it you need to do
$("#form1").submit();
manually as I assume this button is outside of your form.

Issue with onclick function

Hi I have written a GSP and Javascript code to perform on click remove file functionality.
JavaScript code
function remove(attachmentId) {
$(document).ready(function(){
$('.glyphicon-remove').click ( function(e){
e.preventDefault();
$(this).parent().parent().remove();
$.ajax({
url: "${g.createLink(controller: "landing", action: "deleteSelectedFile")}",
data: {
attachmentId: attachmentId
},
success: function(data){
alert("Success");
}
});
});
});
}
GSP Code
<g:each in="${fileList}" var="file">
<div>
<a href="#" onclick="remove('${file.attachmentId}')">
<span class="glyphicon glyphicon-remove"></span></a>
<a href="/forms/landing/attachment/${file.attachmentId}" >${file.name}</a>
</br>
</div>
</g:each>
Groovy Code
def deleteSelectedFile() {
String attachmentId= params.attachmentId
activitiService.deleteAttachemnt(attachmentId)
}
I am not getting why exactly it is taking double click for deleting the first record.
Please help me.
Note: Application is running in Internet Explorer.
The issue is you have bound a click event in a function. Because you have not called that function at page load, it is registering the click event on first click and on second click, it is getting executed.
To overcome this issue you have two ways either just use your inline handler and just call the ajax, don't try to bind any click in it:
function remove(attachmentId, elem) {
$(elem).parent().remove();
$.ajax({
url: "${g.createLink(controller: "landing", action: "deleteSelectedFile")}",
data: {attachmentId: attachmentId},
success: function(data){
alert("Success");
}
});
}
and in the view you have to pass this in the function:
<a href="#" onclick="remove('${file.attachmentId}', this)">
Second way is to use event delegation syntax:
$(static-parent).on(event, selector, callback);
so if you update your function as above and remove the inline event handler from the view and use data-* attribute. you can use it this way:
<a href="#" data-attachmentId='${file.attachmentId}'>
function remove() {
var attachmentId = $(this).parent().data('attachmentId');
$(this).closest('div').remove();
$.ajax({
url: "${g.createLink(controller: "landing", action: "deleteSelectedFile")}",
data: {attachmentId: attachmentId},
success: function(data){
alert("Success");
}
});
}
$(document).on('click', '.glyphicon-remove', remove);
I think removing the $(document).ready(function() {...}) part as well as $('.glypeicon-remove') part from the remove function but keeping the stuff happening inside of these untouched, should fix your problem.
So your code should look like:
JavaScript:
function remove(attachmentId) {
$(this).parent().parent().remove();
$.ajax({
url: '${g.createLink(controller: '
landing ', action: '
deleteSelectedFile ')}',
data: { attachmentId: attachmentId },
success: function (data) { alert('Success'); }
});
}
Hope this helps.
The problem is, in your case the jQuery event handler is registered only after the first click, so in the second click the event handler is getting triggered.
Looks like you are dealing dealing with dynamic elements. In that case instead of using inline event handlers use event delegation and remove the inline event handler
<a href="#" class="delete-attachment" data-attachment-id="${file.attachmentId}">
then
$(document).ready(function(){
$(document).on('click', '.delete-attachment', function(e){
e.preventDefault();
$(this).parent().parent().remove();
$.ajax({
url: "${g.createLink(controller: "landing", action: "deleteSelectedFile")}",
data: {
attachmentId: $(this).data('attachment-id')
},
success: function(data){
alert("Success");
}
});
});
I am not sure its working or not but as per jQuery rules try below code.
function remove(attachmentId) {
$(document).on('click','.glyphicon-remove', function(e){
e.preventDefault();
$(this).parent().parent().remove();
$.ajax({
url: "${g.createLink(controller: "landing", action: "deleteSelectedFile")}",
data: {
attachmentId: attachmentId
},
success: function(data){
alert("Success");
}
});
});
}

make sure ajax request doesn't get fired multiple time

I was working on a simple form page and I was wondering what happens if someone clicks the submit button many many times (incase my shared hosting somehow seems to be slow at that time).
Also, incase anyone wants to look at my code
$.ajax({
url: "submit.php",
type: 'POST',
data: form,
success: function (msg) {
$(".ressult").html("Thank You!");
},
error: function () {
$(".result").html("Error");
}
});
Is there a way to make it so after the user clicks it once, it won't run it again until the first click is done?
Thank you
You can use jQuery's .one() function:
(function handleSubmit() {
$('#submitBtn').one('click', function() {
var $result = $('.result');
$.ajax({
url: 'submit.php',
type: 'POST',
data: form,
success: function (msg) {
$result.html('Thank You!');
handleSubmit(); // re-bind once.
},
error: function () {
$result.html('Error');
}
}); // End ajax()
}); // End one(click)
}()); // End self-invoked handleSubmit()
*Edit: * Added recursion for multiple submissions.
Use a boolean flag
if (window.isRunning) return;
window.isRunning = true;
$.ajax({
url:"submit.php",
type: 'POST',
data: form,
success: function (msg){
$(".ressult").html("Thank You!");
},
error: function (){
$(".result").html("Error");
},
complete : function () {
window.isRunning = false;
}
});
var $button = $(this);
$button.prop('disabled', true); // disable the button
$.ajax({
url:"submit.php",
type: 'POST',
data: form,
success: function (msg){
$(".ressult").html("Thank You!");
},
error: function (){
$(".result").html("Error");
},
complete: function() {
$button.prop('disabled', false); // enable it again
}
});
Have you considered replacing your submit button with a loader image while the query executes, then re-adding it once the query is complete?
EDIT: Using the loader image is a sort of universal "I'm doing something" indicator, but disabling the button would work too!
You could disable the submit button, before the ajax call is made. And then, if required, enable it on success.

event.preventDefault not working

I have this simple code here, nothing too advanced.
$("input#send").submit(function(event){
event.preventDefault();
$.ajax({
type: 'POST',
url: add.php,
data: data,
success: success,
dataType: dataType
});
});
Whever I click on the "send" button, the event.preventDefault function doesn't work, and the page loads.
Any ideas why?
A form has the submit event, not a button. Plus, an ID should be unique so tag#id can just be #id.
$("#theform").submit(function(event) {
event.preventDefault();
// ...
});
You need to bind to the form's submit event or to the button's click event and call event.preventDefault() if you want to stop the form from submitting:
$('form').bind('submit', function (event) {
event.preventDefault();
});
$('form').find(':submit').bind('click', function (event) {
event.preventDefault();
});
I believe the submit event is for the form element. For an input[type='button'] you might want to use the click event.
Add quotes around 'add.php'
Change the selector in the first line to the id attribute of the form which contains input#send.
The advantage of handling the submit() handler on the form rather than the click handler on the input is that some forms can be submitted by pressing the enter key (when the user is focused on one of the form fields). If you don't have an id attribute, add one or use a different jQuery selector to target the form tag.
$("#myform").submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'add.php',
data: data,
success: success,
dataType: dataType
});
return false;
});
Try using return false instead
$("input#send").submit(function(event) {
$.ajax({
type: 'POST',
url: add.php,
data: data,
success: success,
dataType: dataType
});
return false;
});
If you're using preventDefault I assume that means you do NOT want the default submit action. I would just use a different event instead of using .submit. To me, it's not the submit action that you want to intercept, but rather the click that would normally cause the submit.
$('#inputSend').on('click', function(event) {
event.preventDefault();
//the rest
});
If both return false and event.stopPropagation() don't work, try the following method. Using .on() will make the submit function accessible. Once you change the .submit() to .on("submit"..), you can either use return false or e.stopPropagation().
$(document).on("submit", "input#send", function(event) {
event.stopPropagation();
$.ajax({
type: 'POST',
url: add.php,
data: data,
success: success,
dataType: dataType
});
return false; });

Categories

Resources