Jquery form with file upload - onclick instead of dom ready - javascript

$("#form").submit(function() {
$(this).ajaxSubmit({
beforeSubmit: function(before) {
$('.result').html('loading');
},
success: function(d) {
//result process
}
});
return false;
});
When i click the submit button, This function works very good. But I would like to submit the form when a button is pressed. The above function is written in side
$(document).ready(function() {
But i want to write it inside a normal javascript function.
I am using the form plugin. form.min.js

Well, then subscribe to the click handler of your DOM element:
$(document).ready(function() {
$('#myButton').click(function() {
$("#form").ajaxSubmit(
beforeSubmit: function(before) {
$('.result').html('loading');
},
success: function(d) {
//result process
}
);
return false;
});
});

try this
<form action='' method='post' onsubmit='return uploadimg();'>
<script>
function uploadimg(){
$(this).ajaxSubmit({
beforeSubmit: function(before) {
$('.result').html('loading');
},
success: function(d) {
//result process
}
});
return false;
}
</script>

<button id="formSubmit">
binding the formsubmit to a buttons click event should work like this:
$('#formSubmit').on('click', function(){
$('#form').ajaxSubmit({
beforeSubmit: function(before) {
$('.result').html('loading');
},
success: function(d) {
//result process
}
});
return false;
});

you almost got it all, the point in binding inside document.ready is thats the point where the dom is ready to be read and we know its safe to setup event handlers to the dom elements, the normal pratice is that inside youre docuement.ready handler you assign bindings to youre elements, asuming you have a button whith the ID of "submitImageForm" the code be lokking somthing like this
$(function(){
$("#submitImageForm").click(function(e){ // tell the browser we wanner handle the onClick event of this element
e.preventDefault() // this is to tell the browser that we are going to handle things and it shod not do its default (e.g sending the form up to the server and reloading)
$("#form").submit(function() {
$(this).ajaxSubmit({
beforeSubmit: function(before) {
$('.result').html('loading');
},
success: function(d) {
//result process
}
})
})
})
})

Related

How to trigger another jquery event using the return data of previously executed jquery event

I have a button, for example
<a id="btn" class="button">Submit</a>
When this button is clicked, it triggers a jquery function
for example,
$("#btn").on("click", function() {
$.ajax({
url: 'index.php',
type: 'post',
data: {product_id: 1, qty: 2},
dataType: 'json',
success: function(json) {
if (json['success']) {
console.log('Product added to cart');
}
if (json['error']) {
console.log('Product not added to cart');
}
});
});
Now, I would like to know if it is possible to trigger another jquery event by some other jquery code, once the above function is executed, and I want to use the return values of the previous function without making any changes to the above-mentioned function.
For example, I would like to run the following function immediately after the above jquery event by writing another jquery code and not changing any part of the previous code.
function anotherAction(json_array) {
if (json_array['success']){
//calling another function
}
}
You mean
function anotherAction() {
if (submitBtn() == 'Submitted'){
console.log('Button is submitted');
}
}
But then you need to make str global in scope
Perhaps like this
let str;
$("#btn").on("click", function() {
str = 'Submitted';
});
$("#check").on("click", anotherAction);
function anotherAction() {
console.log('Button has '+(str === 'Submitted' ? "" : "not ")+'been clicked');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn" type="button">Click</button>
<button id="check" type="button">Check</button>
without making any changes to the above-mentioned function.
No. Its not possible. submitBtn function's return value is unused/no-reference/destroyed inside "#btn" click event. So you'll never know what was returned.

Unbind jquery in document ready conflict when used in two functions

I have two pages with posts and reviews. The functions for the reply buttons are similar and both using unbind function in document ready event. Somehow, just one function will work even if they are accessing different classes. They both work when one is commented out. I appreciate any help and ideas. Thank you!
//Replies Posts
$(document).ready(function () {
$(document).unbind().on("click", ".btnReplySubmit", function() {
if (!$.trim($(this).closest(".myRepliesForm").find(".textareaReply").val())) {
alert("Empty Content");
}
else {
$.ajax({
url: "/Replies/Create/",
type: "post",
cache: false,
data: $(this).closest(".myRepliesForm").serialize(),
success: function() {
$(".reloadComments").load(location.href + " .reloadComments");
$(".reloadComments").show("slow");
}
});
$(this).closest(".myRepliesForm").find(".textareaReply").val("");
}
return false;
});
});
//Reply Review
$(document).ready(function () {
$(document).unbind().on("click", ".btnReplySubmitReview", function () {
if (!$.trim($(this).closest(".myRepliesFormReview").find(".textareaReplyReview").val())) {
alert("Empty Content");
}
else {
$.ajax({
url: "/ReviewReplies/Create/",
type: "post",
cache: false,
data: $(this).closest(".myRepliesFormReview").serialize(),
success: function () {
$(".reloadCommentsReview").load(location.href + " .reloadCommentsReview");
$(".reloadCommentsReview").show("slow");
}
});
$(this).closest(".myRepliesFormReview").find(".textareaReplyReview").val("");
}
return false;
});
});
Well if you use unbind on both event handlers, one of the functions is going to be inevitably unbound. You also do not need two ready calls as one is enough and finally, you can chain your event handler binding as follows :
$(document).ready(function () {
$(document).unbind()
.on("click", ".btnReplySubmit", function() {
if (!$.trim($(this).closest(".myRepliesForm").find(".textareaReply").val())) {
// ...
}
else {
// ...
}
return false;
})
.on("click", ".btnReplySubmitReview", function () {
if (!$.trim($(this).closest(".myRepliesFormReview").find(".textareaReplyReview").val())) {
// ...
}
else {
// ...
}
return false;
});
});
Because unbind will clear all previous bindings.
But.. why complicating things with bind/unbind on document, you could just do a click listener on both buttons :
$(document).ready(function () {
$('.btnReplySubmit').click(function(){
// alert(1);
});
$('.btnReplySubmitReview').click(function(){
// alert(2);
})
});
the main issue I see here is that you are unbinding events attached to $(document). also, according to jquery's api, you shouldn't be using unbind anymore as it is already deprecated.
instead, you should structure your code like so
$(document).ready(function() {
$('. btnReplySubmit').click(function() {
// your code here
})
$('. btnReplySubmitReview').click(function() {
// your code here
})
})
this makes your event declarations much clearer and much easier to read
All the answers are correct. I may just add that the selector in .on(events [, selector] [,data], handler) method is the event trigger, but event is bound to document in your case.

avoid multiple clicks on a div

It's probably sthg simple, but I still didn't find a solution, I would like to avoid multiple clicks on a button, before finishing an ajax call.
Here is what I tried :
<button id="btn_pay"></button>
$("#btn_pay").click( function() {
$('#btn_pay').prop('disabled', true);
Stripe.card.createToken(form, stripeResponseHandler);
});
var stripeResponseHandler = function(status, response) {
$.ajax({
type: "POST",
success: function(data){
alert("success");
},complete:function(){
//we re-enable the button
$('#btn_pay').prop('disabled', false);
}
});
Problem :
If I click several times on the button, many alerts appear, it's like the button is still active, and many ajax call are done instead of jsut 1 at a time..
Any idea ?
You can control it with a simple variable:
<button id="btn_pay"></button>
var disabled = false; // global var to control button state
$("#btn_pay").click( function() {
if (disabled) {
return;
}
Stripe.card.createToken(form, stripeResponseHandler);
disabled = true; // button is now blocked
});
var stripeResponseHandler = function(status, response) {
$.ajax({
type: "POST",
success: function(data){
disabled = false; // release button lock
alert("success");
},complete:function(){
disabled = false; // release button lock
},fail: function(){
disabled = false; // when fail, you need to release the lock too
}
});
}
Other solutions with event handlers may work for you too, but this is a simpler way to implement this feature.
Try e.preventdefault();
The event.preventDefault() method stops the default action of an
element from happening. For example: Prevent a submit button from
submitting a form. Prevent a link from following the URL.
I have Also facine this type of problem , i have prevent it by using this .. May be it will help you
<button id="btn_pay"></button>
$("#btn_pay").click( function(e) {
e.preventdefault();
$('#btn_pay').prop('disabled', true);
Stripe.card.createToken(form, stripeResponseHandler);
});
var stripeResponseHandler = function(status, response) {
$.ajax({
type: "POST",
success: function(data){
alert("success");
},complete:function(){
//we re-enable the button
$('#btn_pay').prop('disabled', false);
}
});
Modify your code:
.unbind() Remove a previously-attached event handler from the elements.
.bind Attach a handler to an event for the elements.
<button id="btn_pay"></button>
<script>
$("#btn_pay").click( function(e) {
$("#btn_pay").unbind("click");
$('#btn_pay').prop('disabled', true);
Stripe.card.createToken(form, stripeResponseHandler);
});
var stripeResponseHandler = function(status, response) {
$.ajax({
type: "POST",
success: function(data){
alert("success");
},complete:function(){
//we re-enable the button
$("#btn_pay").bind("click");
}
});
</script>
Checkout the tutorials :
http://api.jquery.com/bind/
http://api.jquery.com/unbind/
You can also avoid multiple clicks on button by adding loading image untill your ajax call is completed in beforeSend: event.
for example:
$.ajax
({
url: 'your-url',
data: "",
type: 'post',
beforeSend: function() {
$("#loading-image").show();
},
success: function(result)
{
//alert(result);
$("#loading-image").hide();
}
});
You have to keep image in div id 'loading-image' and by default display:none(CSS Setup).
<div id="loader_div_all" style="position: absolute ! important;opacity: 0.60;display: none;">
<img src="ajaxSpinner.gif" style="width: 200px; height: 200px; margin-left: 500px; margin-top: 1060px;'">
$("#buttonid").click(function(){
$.ajax({
url: 'PATH_TO_AJAX_REQUEST_URL',
type: 'POST',
data: {/*Data set here*/},
beforeSend: function () {
$("#loader_div_all").css('display','block');
},
success: function(resp) {
$("#loader_div_all").css('display','none');
/*Perform Ajax Success Action Here*/
}
});
});
Link the disabled state of the button to the response function firing. This way the visual cue and the button behaviour should match.
$("#btn_pay").click( function(event) {
event.preventDefault();
if ($(this).prop('disabled')) {
return;
}
$(this).prop('disabled', true);
Stripe.card.createToken(form, stripeResponseHandler);
});
(It would be better to pass a callback re-enabling the button to stripeResponseHandler, so that that function is not tied to a specific button calling it).

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");
}
});
});
}

Form request is made three times: Status 200 OK

I created a form on /contact-us and having action="/contact-us". Now, when I added Ajax to it, it is sending the request three times, i cannot find the reason.
Ajax:
define(['jquery', 'foundation.alert'], function($) {
return {
init: function() {
$("#success-alert").hide();
$("#error-alert").hide();
$('button').click(function(e){
$('input').map(function() {
if(!$(this).val()) {
$("#error-alert").show();
$("#success-alert").hide();
return false;
} else {
$('document').ready(function() {
var form = $('#contact_us'); // contact form
var submit = $('button'); // submit button
var status = $('#form-status'); // alert div for show alert message
// form submit event
form.on('submit', function(e) {
e.preventDefault(); // prevent default form submit
$.ajax({
url: '/contact-us', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
submit.html('Sending....'); // change submit button text
},
success: function(data) {
form.trigger('reset'); // reset form
$("#success-alert").show();
$("#error-alert").hide();
submit.html('Send'); // reset submit button text
},
error: function(e) {
console.log(e);
}
});
});
});
}
});
});
}
}
});
You are looping through all the inputs and applying on submit for every input in your form. So if it is submitting 3 times, you must have three inputs. Each time you click the button, you will be adding even more submit handlers! The whole design of this is wrong.
You should not be attaching the submit handler inside of the click event, it should be outside and have it done one time. Do your validation inside of the submit handler to make sure that it is valid before making the Ajax call.
try this solution.
var wait = false;
wait variable for global scope
if (!wait) {
wait = true;
$.ajax({
url: '/contact-us', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function () {
submit.html('Sending....'); // change submit button text
},
success: function (data) {
wait = false;
form.trigger('reset'); // reset form
$("#success-alert").show();
$("#error-alert").hide();
submit.html('Send'); // reset submit button text
},
error: function (e) {
console.log(e)
}
});
}
After going through my code i realized what mistakes i have been doing and also realized that reading code is more important than writing it.
This is how i rewrite the code and its working fine but i am still not sure if it is the best approach.
define(['jquery', 'foundation.alert'], function($) {
return {
init: function() {
$("#success-alert").hide();
$("#error-alert").hide();
$(function () {
$('#contact_us').on('submit', function (e) {
$.ajax({
type: 'post',
url: '/contact-us',
data: $('#contact_us').serialize(),
success: function () {
$("#success-alert").show();
$("#error-alert").hide();
}
});
e.preventDefault();
});
});
$('button').click(function(e){
$('input').map(function() {
if(!$(this).val()) {
$("#error-alert").show();
$("#success-alert").hide();
return false;
}
});
});
}
}
});
Note: Never take writing code as a burden.

Categories

Resources