I did a script and he are submitting forms twice. Someone can help?
PS: I need that any element can send forms
$('*').bind('click', function(event) {
if ($(this).attr('href') && $(this).attr('href') != '#') {
.....
} else if ($(this).attr('form-name')) {
$(this).attr('disabled', true);
var FormId = '#' + $(this).attr('form-name');
var Target = $(this).attr('action-url');
$.ajax({
type: 'POST',
dataType: 'html',
url: Target,
data: $(FormId).serialize(),
success: function(response) {
eval(response);
}
}).always(function() {
$(this).attr('disabled', false);
});
}
}
You are submitting your form once via the $.ajax call, and once via the <button>'s default behaviour. Add:
event.preventDefault();
to the end of your click handler.
Also, if you want a click handler on every element on your page, I'd highly recommend looking into event delegation.
Related
Can anyone point out what I'm doing wrong here? I'm trying to interact with data (appended using ajax)
The alerts fire if the element is already in DOM, but not when It's appended.
Am I using the ".on" wrong?
$(function() {
$('.card').on('click','.add-exercise', function() {
alert('clicked');
});
// Detect 'enter' key up
$('#search').on('keyup', function(e){
if(e.keyCode == 13)
{
console.log('hit enter key');
$(this).trigger("enterKey");
}
});
$('#search').on("enterKey",function(e){
$.ajax({
url: '{{ url("exercises/load") }}',
method: "POST",
data: {
_token: "{{csrf_token()}}",
search: $('#search').val(),
},
dataType: "text",
success: function(data) {
console.log(data);
$('.exercise-result').remove();
$('.card-deck').append(data);
}
});
});
});
I guess you have other .card elements in data.
You have to assign the event click again for them. The event is currently only assigned to your first .card elements. This is why it doesn't fire on your new .card elements.
I believe you need to add the event again each time the append is done. Try this and let me know if it works:
function addEvent() {
$('.card').on('click','.add-exercise', function() {
alert('clicked');
});
}
$(function() {
addEvent();
// Detect 'enter' key up
$('#search').on('keyup', function(e){
if(e.keyCode == 13)
{
console.log('hit enter key');
$(this).trigger("enterKey");
}
});
$('#search').on("enterKey",function(e){
$.ajax({
url: '{{ url("exercises/load") }}',
method: "POST",
data: {
_token: "{{csrf_token()}}",
search: $('#search').val(),
},
dataType: "text",
success: function(data) {
console.log(data);
$('.exercise-result').remove();
$('.card-deck').append(data);
addEvent();
}
});
});
});
I think the .card element is also loading dynamically, in order to make event delegation works properly you need to bind it to an element which is present at the time of page load.
So either you can attach it to the document object.
$(document).on('click','.card .add-exercise', function(){
// rest of your code
});
or better approach would be, attach to an element which is present at the time of page load(I guess .card-deck is present at the time of page load since you are appending data to that or attach to body tag).
$('.card-deck').on('click','.card .add-exercise', function(){
// rest of your code
});
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).
I have this link:
$('.popup-window').click(function (e) {
e.preventDefault();
$.ajax({
...
})
});
which is a .NET LinkButton (a link that call a javascript, not a real href). I want to prevent Default if ajax return some (let say, false). Else, if true, continue with that link handler.
How can I do it?
P.S. I need that e.preventDefault(); at the beginning, else .NET handler will act immediatly.
You can use the __doPostBack() js function to trigger the postback in your AJAX callback.
The only thing is that you need to pass in the id of the control causing the postback, e.g.
__doPostBack('btnPopup', null);
you can see more on this function in this question: How to use __doPostBack()
I think I understand what you're looking for.
Here's my idea on it: use a data attribute on the DOM element to decide weither default event should be prevented or not. Initially, the event is prevented but the ajax has the power to "unlock?" it, then fire it again. It's a little bit of custom work but it may do the trick:
var $popupWindow=$('popup-window');
// initially "tell" the LinkButton to prevent default
$popupWindow.data('prevent-default', 1);
// the click event (initially prevents default)
$popupWindow.click(function(e){
var $this=$(this);
if ($this.data('prevent-default')==0) { // if "unlocked"
// "lock" it again (default isn't prevented)
$this.data('prevent-default', 1);
} else { // if "locked"
// default is prevented
e.preventDefault();
// test if it should be unlocked
$.ajax({
// ...
}).done(function(data){
if (data.length>0 && data.response==false) {
// set the attribute so it shouldn't prevent default
$this.data('prevent-default', 0);
// trigger this click (should let the event fire completely)
$this.trigger('click');
}
});
}
});
UPDATE:
An alternative could be to add a Page Method.
(See: Using jQuery to directly call ASP.NET AJAX page methods)
This would reduce the mechanics to somethink like this:
$('popup-window').click(function(e){
e.preventDefault();
$.ajax({
// ...
}).done(function(data){
if (data.length>0 && data.response==false) {
$.ajax({
type: "POST",
url: "YourPage.aspx/YourMethod",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Replace the div's content with the page method's return.
$("#Result").text(msg.d);
}
});
}
});
});
$('.popup-window').click(function (e) {
data = '?sample=1' //serialized data here
callback = function(json){
if(json.returnVar!=true){ //check if returnVar is not true
e.preventDefault(); //prevent redirect if not true
}
};
$.ajax({
type: 'POST',
url: "../ajaxcall.php", //the url to call for ajax here
data: data,
success: callback,
dataType: 'json'
});
});
Try this, let me know if you can't understand the code
Doing following in jQuery:
$('#signupbox1').on('click', '#signup1', function() {
var str = $('#signupform').serialize();
// make it look like a waiting button
$('#signup1').addClass("btn_wait");
var btn_val = $('#signup1').val();
$('#signup1').val('');
$.ajax({
type: "POST",
url: "signup_step1.php",
data: str,
success: function(msg) {
//doing stuff here
$('#signup1').removeClass("btn_wait");
$('#signup1').val(btn_val);
}
});
});
How could you disable the click event as well till you receive an answer from the ajax call? So, when you click on the button it not only "transforms" to a waiting button because of the added class, but also the click event will be "paused"... is this possible?
Thank you very much in advance!
$('#signupbox1').on('click', '#signup1', function() {
var str = $('#signupform').serialize();
// make it look like a waiting button
var btn_val = $('#signup1').val();
$('#signup1').addClass("btn_wait").val('').unbind('click');
$.ajax({
type: "POST",
url: "signup_step1.php",
data: str,
success: function(msg) {
$('#signup1').removeClass("btn_wait").val(btn_val);
},
complete: function() {
$('#signup1').bind('click'); // will fire either on success or error
}
});
});
You can add a flag to denote "currently loading". You can use anything like a variable, property or attribute. In this example, I use jQuery .data()
Also, it's advisable that you use submit event instead of adding a click handler to the submit button when you submit a form.
$('#signupform').on('submit', function() {
var form = $(this),
loading = form.data('loading'), //check loading status
str, button, val;
//if not loading
if(!loading){
//set loading to true
form.data('loading',true);
str = form.serialize();
button = $('#signup1', form);
val = button.val();
// make it look like a waiting button
button
.addClass("btn_wait");
.val('');
$.ajax({
type: "POST",
url: "signup_step1.php",
data: str,
success: function(msg) {
//remove loading state
form.data('loading',false);
//return button to normal
button
.removeClass("btn_wait");
.val(val);
}
});
}
});
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; });