jQuery AJAX load() div table after loaded buttons are not working - javascript

currently having this problem, I have ajax request to send form datas and save it to database and after saving I then use load() function to refresh the list in table, but after being loaded the button inside the loaded div is not working which also uses js.
Ajax
var formData = new FormData(this);
$.ajax({
url: "/systemadmin/storemanagement/"+id,
method: "POST",
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log(data)
$("#storeDatatable").load(location.href + " #storeDatatable");
$(".message-error").remove();
$(".message-success").remove();
$('#store-update-header').append('<div class="message-success">Update succesfully</div>');
}, error:function (err) {
if (err.status == 422) {
console.log(err.responseJSON);
$(".message-error").remove();
$(".message-success").remove();
$.each(err.responseJSON.errors, function (i, error) {
$('#store-update-header').append('<div class="message-error">'+error[0]+'</div>');
});
}
}
});

solved by using
$(document).on('click','.toggleModal-updateStore', function(){ })
instead of
$('.toggleModal-updateStore.').on('click', function(){ })
for the buttons inside the row

Related

Issue with nested Ajax calls

I am having a series of nested Ajax calls to create and update data into the database as well as calling the updated list once data are successfully submitted.
This is how the code works:
(1) A list of transaction is shown when the page is rendered, each row can be edited by the user.
(2) When clicking a specific row, I run an Ajax call to retrive the form filled with the data to be updated
(3) The form is then submitted via Ajax as well.
(4) If successfully submitted it perform another Ajax call to get the table updated.
First problem: when the table is loaded via Ajax the "edit" button is not working anymore.
Second problem: The form displayed to update and to create is the same, except when updating the form is pre-filled. I would like to avoid duplicating the Ajax call but I had to do it otherwise I wasn't able to submit the form after it was loaded from the first Ajax call (pt 1). Is there a way to make a more clean code?
Here it is the javascript code, server side all works just fine:
$(".edit-transaction").click(function () {
// obtain the object id to load the correct form
const object_id = $(this).data('object-id');
// request the form via AJAX Get request
$.ajax({
type: 'GET',
url: "/transaction/",
data: {
'slug': object_id
},
success: function(response) {
// Get the form for the requested object
$("#display-form").html(response.html); // this code retrive the form
$("#transaction-form").submit(function (e) {
// preventing from page reload and default actions
e.preventDefault();
let serializedData = $(this).serialize();
// Update the form via AJAX
$.ajax({
type: 'POST',
url: "/transaction/",
data: serializedData,
success: function (response) {
console.log('updated successfully')
// load the table with the new content updated
$.ajax({
type: 'GET',
url: "/get-transactions-list/",
success: function (data) {
$("#display-transaction-list").html(data.html);
},
});
},
error: function (response) {
let error = response ["responseJSON"]["error"];
$.each(error, function (code, message) {
alert('message');
});
}
})
})
},
error: function (response) {
let error = response ["responseJSON"]["error"];
$.each(error, function (code, message) {
alert('message');
});
}
})
});
$("#transaction-form").submit(function (e) {
// preventing from page reload and default actions
e.preventDefault();
let serializedData = $(this).serialize();
// Create a new transaction via AJAX
$.ajax({
type: 'POST',
url: "/transaction/",
data: serializedData,
success: function (response) {
console.log('created successfully')
// load the table with the new content updated
$.ajax({
type: 'GET',
url: "/get-transactions-list/",
success: function (data) {
$("#display-transaction-list").html(data.html);
},
});
},
error: function (response) {
let error = response ["responseJSON"]["error"];
$.each(error, function (code, message) {
alert('message');
});
}
})
})
Thanks for any help
Since some of the elements are added asynchronously, this means that the event listeners which were added at runtime will not affect those elements. You should instead listen to events on them via "events delegation".
You can also create a custom event for loading the table content. So to update the table, you just .trigger() your custom event. This is useful when you want to implement other functionalities which will need a table update like, delete, etc.
// custom event for loading the table content
$(document).on('load.table', '#display-transaction-list', function () {
const $table = $(this);
$.ajax({
type: 'GET',
url: "/get-transactions-list/",
success: (data) => $table.html(data.html)
});
});
// edit transaction event
$(document).on('click', '.edit-transaction', function () {
// obtain the object id to load the correct form
const object_id = $(this).data('object-id');
// request the form via AJAX Get request
$.ajax({
type: 'GET',
url: "/transaction/",
data: {
'slug': object_id
},
success: function(response) {
// Get the form for the requested object
$("#display-form").html(response.html); // this code retrive the form
},
error: function (response) {
let error = response ["responseJSON"]["error"];
$.each(error, function (code, message) {
alert('message');
});
}
})
});
// save transaction event
$(document).on('submit', '#transaction-form', function (e) {
// preventing from page reload and default actions
e.preventDefault();
let serializedData = $(this).serialize();
// Update the form via AJAX
$.ajax({
type: 'POST',
url: "/transaction/",
data: serializedData,
success: function (response) {
// you can add some data to the response
// to differentiate between created and updated. Eg response.actionType
console.log('created or updated successfully')
// load the table with the new content updated
$("#display-transaction-list").trigger('load.table');
},
error: function (response) {
let error = response ["responseJSON"]["error"];
$.each(error, function (code, message) {
alert('message');
});
}
})
})

Prevent Bootstrap Modal from showing using ajax error

I was wondering if there is a way to prevent the Modal from showing up when an ajax call returns an error. I've seen a few posts here already that use
e.stopPropagation();
but I couldn't manage to make that work. My ajax call looks as follow
$.ajax({
url: url,
data: data,
dataType: 'json',
cache: false,
type: "POST",
error: function (e) {
//show error message
$('#alertdone').removeClass('hidden');
},
//if ajax call is successful populate form fields and hide error message
success: function (data) {
//hides the error message
$('#alertdone').addClass('hidden');
}
});
Thanks
I am assuming that you need to hide (don't show) the modal if the AJAX calls fails (since there's a difference between ajax call failing and returning error from server side).
For that you need to remove your data-attribute from HTML and do something like this:
$.ajax({
url: url,
data: data,
dataType: 'json',
cache: false,
type: "POST",
error: function (e) {
$('#alertdone').removeClass('hidden');
$("modal_selector").modal('hide');
},
//if ajax call is successful populate form fields and hide error message
success: function (data) {
$('#alertdone').addClass('hidden');
$("modal_selector").modal('show');
}
});
If you want to hide/ show modal depending on condition use modal()
$.ajax({
url: url,
data: data,
dataType: 'json',
cache: false,
type: "POST",
error: function (e) {
//show error message
$('#alertdone').removeClass('hidden');
$("Your_modal_id").modal('hide');
},
//if ajax call is successful populate form fields and hide error message
success: function (data) {
//hides the error message
$('#alertdone').addClass('hidden');
$("Your_modal_id").modal('show');
}
});

Ajax: conflict in client between two functions

For a university homework, I have to create a little e-commerce website.
After the login, the user is redirected to the homepage. In this homepage, the client will recive a JSON object from the server (containing some product to be loaded) to generate the DOM of the homepage dynamically.
Note: I must use AJAX and JSON
I have this client.js file:
$(document).ready(function() {
// AJAX request on submit
$("#login_form").submit(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "submit.php",
data: {
Email: document.getElementById('login_email').value, // Email in the form
Password: document.getElementById('login_password').value // // Password in the form
},
cache: false,
success: function(){
window.location.href = "home.php"; // load the home.php page in the default folder
}
});
});
});
$(document).ready(function() {
// AJAX request to open a channel between php and client
function (e) {
e.preventDefault();
$.ajax({
type: "GET",
url: "queries.php",
dataType: "json",
success: function(data){
var data = JSON.parse(data);
alert(data); // debug
showProducts(data);
});
});
});
});
function showProducts(data){
alert(data);
// Insert object into the page DOM
}
I don't know why, but I can't access after the login if the second Ajax request (the AJAX request to open a channel between php and client) is not commented, and I don't know why, because the code seems right... Any suggestion?
after login action you need to set to cookie token in response
success: function(response){
console.log(response)
// then set to cookie response.token
window.location.href = "home.php";
}
after set token to cookie, you need to send this token to next ajax request url: "queries.php",
You need to wrap your anonymous function in parenthesis and add () at the end if you want to execute it:
(function (e) {
// I don't know why you need this:
e.preventDefault();
// etc.
})();
You should also check the contents of that function as you seem to have too many closing parentheses and you don't need to parse the returned value if you set the dataType to json.
In the end I think this is about all you need for that function:
(function () {
$.ajax({
type: "GET",
url: "queries.php",
dataType: "json",
success: function(data){
console.log(data); // debug
showProducts(data);
}
});
})();
or just:
$.ajax({
type: "GET",
url: "queries.php",
dataType: "json",
success: function(data){
console.log(data); // debug
showProducts(data);
}
});
To get it directly on page load.

Suppressing SUCCESS alert boxes?

I have three functions that called as shown below (Functions not included):
Code:
$("#btnSubmit").click(function() {
var data = JSON.stringify(getAllSourcepData());
console.log(data);
$.ajax({
url: 'closures.aspx/SaveSourceData',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
'empdata': data
}),
success: function() {
alert("Data Added Successfully");
},
error: function() {
alert("Error while inserting data");
}
});
});
$("#btnSubmit").click(function() {
var data = JSON.stringify(getAllSpouseData());
console.log(data);
$.ajax({
url: 'closures.aspx/SaveSpousData',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
'empdata': data
}),
success: function() {
alert("Data Added Successfully");
},
error: function() {
alert("Error while inserting data");
}
});
});
$("#btnSubmit").click(function() {
var data = JSON.stringify(getAllDividentData());
console.log(data);
$.ajax({
url: 'closures.aspx/SaveDividentData',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
'empdata': data
}),
success: function() {
alert("Data Added Successfully");
},
error: function() {
alert("Error while inserting data");
}
});
});
When data is submitted successfully, three alert boxes popup, each with same message: "Data Added Successfully".
This forces user to have to close three popup boxes.
Is there a way to disable the success alert boxes leaving just one? Or even all three be disabled allowing me to come up with a custom Success message?
You could also simplified your code by using Promise.all:
$("#btnSubmit").click(function() {
var allSourcepData = JSON.stringify(getAllSourcepData());
var allSpouseData = JSON.stringify(getAllSpouseData());
var allDividentData = JSON.stringify(getAllDividentData());
Promise.all([
getData('closures.aspx/SaveSourceData', allSourcepData),
getData('closures.aspx/SaveSpousData', allSpouseData),
getData('closures.aspx/SaveDividentData', allDividentData)
])
.then( alert )
.catch( alert )
});
function getData(url, data)
{
return new Promise((resolve, reject){
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
'empdata': data
}),
success: () => { resolve("Data Added Successfully") },
error: () => { reject("Error while inserting data"); }
});
})
}
You need to wait until all ajax requests are complete, like in this answer
So in your case you need to create functions for all $.ajax calls like this:
function ajax1() {
var data = JSON.stringify(getAllSourcepData());
$.ajax({
url: 'closures.aspx/SaveSourceData',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
'empdata': data
}),
success: function() {
alert("Data Added Successfully");
},
error: function() {
alert("Error while inserting data");
}
});
}
// add ajax2() and ajax3() ...
And then use only one click handler like this:
$("#btnSubmit").click(function() {
$.when(ajax1(), ajax2(), ajax3()).then(function(a1, a2, a3){
// success, display message
}, function(){
// exception
});
});
You can reorder a little your code to use the deferred method to jQuery 1.5+ otherwise you can implement as this answer:
jQuery callback for multiple ajax calls
Why you want to call 3 times for button click?
Why not put them all together?
Any how you can use variable as isAlertToBeShown= false and after pushing data make it has true. finally check the variable is true or false.

Display loading while retrieving data using Ajax method

I am using ajax, sometimes it takes time to load all the data from my database therefore I need to find a way to display (Loading...) While the data is not yet complete. Below is my sample code, and I am looking for some event while the data is still in process.
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(data){
$('#para').html(data);
}
});
It is very simple..
before you call the ajax start your loading image..& after the success hide the image
for eg :
$.fancybox.showLoading();
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(data){
$.fancybox.hideLoading();
$('#para').html(data);
}
});
here
$.fancybox.showLoading()
is my function in which I have the property of displaying the loader,
This will be internally called whenever an ajax call is made.
$.ajaxStart(function() {
$("img#loading").show();
});
$.ajaxComplete(function() {
$("img#loading").hide();
});
HTML
<img src="../images/loading.gif" alt="wait" id="loading"/>
<div id="loading">LOADING...</div>
var loading = $("#loading");
loading.hide();
function doAjax() {
loading.show();
$.ajax({
url: "/js/beautifier.js",
success: function (data) {
loading.hide();
}
});
}
doAjax();
on jsfiddle

Categories