Ajax call multiple time onclick event on bootstrap modal - javascript

By clicking a button Its loaded a bootstrap modal. On the modal there have a form and on click save button I am trying to submit form by ajax call. At first time the ajax call trigger one time, but 2nd time the ajax url trigger two times. I see on firebug console section the post url is called multiple times.
Here Is my jquery code.
$(".show-modal").click(function() {
$('.upload-modal').modal();
$(".save-logo").click(function(e) {
e.preventDefault();
$.ajax({
type : "POST",
data : data,
contentType: false,
cache : false,
processData: false,
url : "../../io/upload/"
}).done(function(rawData) {
$('.modal-header .close').click();
})
});
})

The problem is that you have your .save-logo click handler inside the .show-modal click handler. So every time the modal is shown, you attach another click handler to the .save-logo element. The code below should fix that problem:
$(".show-modal").click(function () {
$('.upload-modal').modal();
});
$(".save-logo").click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
data: data,
contentType: false,
cache: false,
processData: false,
url: "../../io/upload/"
}).done(function (rawData) {
$('.modal-header .close').click();
})
});

$(function(){
var editUserId;
$('#edit-user-modal').on('show.bs.modal', function(e) {
editUserId = $(e.relatedTarget).data('userid');
});
$("#edit-user-form").submit(function(event) {
event.preventDefault();
var form = $(this);
var route = "/edit-user/" + editUserId;
if(validateEditUserForm()){
$.ajax({
type: "POST",
url: route,
data: form.serialize(),
success: function(Response)
{
if(Response){
console.log(Response.status);
console.log(Response.message);
if(Response.status == 'success'){
$('#adduser-alert-box').hide();
$("#add-user-form")[0].reset();
$('#adduser-success-box').show();
$('#adduser-success-box').html(Response.message);
}
else{
console.log('User could not be added');
$('#adduser-alert-box').show();
$('#adduser-alert-box').html(Response.message);
}
}
else{
console.log('No Response');
$('#adduser-alert-box').show();
$('#adduser-alert-box').html('No Response');
}
}
});
}
else{
console.log('Validation Error');
$('#adduser-alert-box').show();
$('#adduser-alert-box').html('Please Fill All the Fields Correctly');
}
});});
I faced the same issue and randomly i tried something .
so if you create a global variable to store the 'id' you pass from your button then store the id from the 'data' attribute of your button then it won't make multiple requests when clicked since you have declared the variable globally!
Hope it helps.

Related

Follow/unfollow to remember the click of the button. Not working after refresh

I want to make a follow/unfollow user on button click. However the current code only works until the page refreshes. If I refresh the page the follow text comes back. I want it to have unfollow when I refresh the page.
Do I need to have a Session for users in my PHP? Do I have to create a value for a button? Will it remember the click by multiple users?
<button class="user">Follow</button>
<p></p>
$(document).ready(function() {
$.ajax({
type: 'POST',
url: 'echocurrent.php',
success: function(data) {
$("p").text(data);
}
});
});
$('.user').click(function() {
var $this = $(this);
$this.toggleClass('user');
if ($this.hasClass('user')) {
//unfollows
$.ajax({
type: 'POST',
url: 'UnFollow.php',
success: function(data) {
$("p").text(data);
}
});
$this.text('Follow');
} else {
//follows
$.ajax({
type: 'POST',
url: 'follow.php',
success: function(data) {
$("p").text(data);
}
});
$this.text('UnFollow');
}
});
UPDATE :
I want to add this jquery to every user with a session in PHP.
How can I do that?
I'm assuming you're updating a value in "UnFollow.php" you should return this value in "echocurrent.php" and based on it show/hide the class "user"
Update:
add logic to in "echocurrent.php" to return both the number of followers and if the current user is following this user
$.ajax({
type: 'POST',
url: 'echocurrent.php',
success: function(data) {
$("p").text(data.followers);
if(data.isFollowing){
$this.toggleClass('user');
}
}
});

Display items from json file in an alert (sweetalert) jQuery

I am using sweetalert for alerts and want to display some data from an adjacent .json file in a sweetalert alert with jQuery. The json file has 5 items and in a seperate attempt using getJSON I managed to display the first 2 so I am trying the $ajax method to do more. The current code I have just goes right down to the "always" function and displays "complete" in the alert, it doesn't display the success method. So I would like to know how to alter the code to display the items in the alert.
The code is below.
jQuery(document).ready(function($) {
$(document).on('click', '#json', function(event) {
event.preventDefault();
$.ajax({
url: 'somedata.json',
type: 'GET',
dataType: 'json',
data: {param1: 'value1'}
})
.done(function() {
swal("success");
})
.fail(function() {
swal("error");
})
.always(function() {
swal("complete");
});
});
});
Try somthings like this
jQuery(document).ready(function($) {
$(document).on('click', '#json', function(event) {
event.preventDefault();
$.ajax({
url: 'somedata.json',
type: 'GET',
dataType: 'json',
data: {param1: 'value1'}
})
.done(function(data) {
data.each(el,function(){
setTimeout(function(){
swal(el);
},300);
});
});
});
});
EDIT
from this bug report you have to set time between instances Source

Button click event only works when page is reloaded or alert in function

It seems that a couple of buttons I have on my HTML page only work when there is an alert in the function of the event, or when I navigate to another page and then back to the home page. From other similar problems I've read about, it seems as though the home page is attempting to finish some task and that the alert is buying it more time. However, I am not sure that is true in my case.
I have a Javascript file actions.js that is loaded by the HTML page in the header as a source. The file is as follows (only showing relevant code) :
$(document).ready(function() {
//This function only works with an alert before the Ajax call or when page is reloaded
$("button[name='delete_deck']").click(function() {
var id = this.id;
$.ajax({
url: "delete_decks.php",
type: "GET",
data: {selection:JSON.stringify(id)},
async: false,
success: function(data) {
location.reload();
}
});
});
//This function is for a button on the same page, but works fine without the alert or reloading the page
$("#study").click(function() {
var selection = getDeckSelections();
if(selection.length > 0) {
//Get the selected side of the card
var selected_side = $('input[name=side_selection]:checked', '#side_selection_form').val();
//Store the selected side in session storage
sessionStorage.setItem("selected_side", selected_side);
//Ajax call to get cards from database
$.ajax({
url: "get_cards.php",
type: "GET",
data: {selection:JSON.stringify(selection)},
cache: false,
async: false,
success: function(data) {
json = JSON.parse(data);
//Store the cards in session storage
sessionStorage.setItem("cards", JSON.stringify(json));
}
});
}
});
}
$(document).on('click',"button[name='delete_deck']",function() {
var id = this.id;
$.ajax({
url: "delete_decks.php",
type: "GET",
data: {selection:JSON.stringify(id)},
async: false,
success: function(data) {
location.reload();
}
});
});

JQuery form submit not calling success

After click on submit beforeSend: works but it does not call success: also there is no console error . The data also submit to database correctly ! Then why it not call the success: . Please Help
$(function() {
//hang on event of form with id=ticketForm
$("#ticketForm").submit(function(e) {
//prevent Default functionality
e.preventDefault();
//get the action-url of the form
var actionurl = e.currentTarget.action;
var form = $('#ticketForm');
var submit = $('#submite');
$.ajax({
url: actionurl,
type: "POST",
data: $("#ticketForm").serialize(),
dataType: "json",
contentType: 'application/json; charset=utf-8',
cache: false,
beforeSend: function(e) {
submit.html("Booking....");
},
success: function(e) {
submit.html("Booking Completed !");
//get the message from booking.php and show it.
$(".alert").removeClass("hide");
var msg = $.ajax({
type: "GET",
url: actionurl,
async: false
}).responseText;
document.getElementById("success-message").innerHTML = msg;
setTimeout(function() { // wait for 3 secs(2)
location.reload(); // then reload the page.(3)
}, 3000);
},
error: function(e) {
console.log(e)
}
});
});
});
Console Message
Object {readyState: 4, responseText: "<strong>Seat Booked Successfully</strong>", status: 200, statusText: "OK"}
In a Ajax call 'dataType' attributes means what data format can be expect from client(browser). As per error message server is returning 'string' instead 'json'.
But on the other hand, given ajax call is expecting json data to be returned by backend server. Either provide a
valid JSON in response or change datatype to html.
In your AJAX call settings you set dataType to json, but in return you provide a string.
dataType (default: Intelligent Guess (xml, json, script, or html)) The
type of data that you're expecting back from the server. If none is
specified, jQuery will try to infer it based on the MIME type of the
response
So, you have two solutions:
Provide a valid JSON in response
Do not ask for JSON by changing your dataType value (to html), or by removing it.
I had similar problem. As you are redirecting page in success you need to use
e.preventDefault(); // to prevent page refresh
after the ajax call or
return false; // to prevent page refresh
Something like this :
$(function() {
//hang on event of form with id=ticketForm
$("#ticketForm").submit(function(e) {
//prevent Default functionality
e.preventDefault();
//get the action-url of the form
var actionurl = e.currentTarget.action;
var form = $('#ticketForm');
var submit = $('#submite');
$.ajax({
url: actionurl,
type: "POST",
data: $("#ticketForm").serialize(),
dataType: "json",
contentType: 'application/json; charset=utf-8',
cache: false,
beforeSend: function(e) {
submit.html("Booking....");
},
success: function(e) {
submit.html("Booking Completed !");
//get the message from booking.php and show it.
$( ".alert" ).removeClass( "hide" );
var msg = $.ajax({type: "GET", url: actionurl, async: false}).responseText;
document.getElementById("success-message").innerHTML = msg;
setTimeout(function(){// wait for 3 secs(2)
location.reload(); // then reload the page.(3)
}, 3000);
},
error: function(e) {
console.log(e)
}
});
return false; e.preventDefault(); //any one of this options to prevent page refresh after ajax call
});
});

Bootstrap modal popup and fadeout after few seconds according to ajax success

I am trying to display a bootstrap modal with success of a ajax request. Its working for me. But my problem is when I try to hide it after few seconds as soon as it triggered.
This is how I tried it.
$.ajax({
type: "POST",
url: "includes/process.php",
data: $(".banner-form").serialize(), // serializes the form's elements.
success: function(data)
{
$("#myModal").fadeTo(2000, 500).slideUp(500, function(){
$("#myModal").modal('close');
});
}
});
But this is not working properly when I submitting the form first time. After that when I submitting the form this modal is not popup. Can anybody tell me what is the reason for this?
Thank you.
Here it is,
$.ajax({
url: 'link/',
dataType: 'json',
success: function (s) {
$('#MyModal').modal({
show: false
});
},
error: function (e) {
}
});
This should work
$.ajax({
url: "test.html",
context: document.body
// wait until ajax request is done
}).done(function() {
// close the modal
$('#myModal').modal('hide')
// try this if above does not work!
// $('#modal').modal('toggle');
});

Categories

Resources