how to make page wait until delete complete, then refresh - javascript

I'm pretty new to using javascript, and ajax. So I have a button that's supposed to delete the item when clicked.
<button type="submit" class="delete-button" data-id="{{ d_id }}">Delete</button>
I used ajax to send the delete POST request. While this is happening (the item takes a while to delete) how can I go about having a loading circle in the HTML. I would like to show a processing bar or something similar while the request is processing and when it's done, refresh the to show the change. Currently after a successful delete, the user can't see the change until they manually refresh the page.
$(document).ready(function() {
$(".delete-button").click(function () {
var d_id = $(this).attr('d_id');
$.ajax({
type: "POST",
url: "/delete/" + d_id
}).done(function (data) {
if (data === 'Deleted') {
console.log("Deleted")
} else {
console.log("Failed")
}
})
});
});

Related

Not able to reload the div while using jQuery $.ajax()

I am trying to reload a div with id #todos after the data is saved in the database.
I tried using .load() in $.ajax()
$('.todo--checkbox').change(function () {
let value = $(this).data('value');
$.ajax({
url: `/todo/${value}`,
type: 'PUT',
data: { done: this.checked },
success: function (data) {
if (data.success) {
$('#todos').load(location.href + ' #todos');
}
},
});
});
The problem with this, that it is not reloading the page but it is updating the data in database correctly.
I also tried this
$('.todo--checkbox').change(function () {
let value = $(this).data('value');
$.ajax({
url: `/todo/${value}`,
type: 'PUT',
data: { done: this.checked },
success: $('#todos').load(location.href + ' #todos'),
});
});
In this, it is reloading the page as well as updating the data in the database but the problem is that it only reload and update the data at the first request, and after that I need to reload the whole page to update next data.
I tried to check if I am getting any data or not
$('.todo--checkbox').change(function () {
let value = $(this).data('value');
$.ajax({
url: `/todo/${value}`,
type: 'PUT',
data: { done: this.checked },
success: function (data) {
console.log(data);
},
});
});
It returned nothing, but my data in the mongoDB compass is changing.
I already read this articles so, please don't mark this question as duplicate.
Refresh/reload the content in Div using jquery/ajax
Refresh Part of Page (div)
refresh div with jquery
reload div after ajax request
I suggest you checking requests between your page and the server in the Network tab of browser's Development Console (F12).
Make sure you see PUT request going out to the server to update todo
Make sure that response you receive looks like { success: true } otherwise the following piece of code won't be triggered
if (data.success) {
$('#todos').load(location.href + ' #todos');
}
Make sure you see GET request going out to the server to pull '#todos' asynchronously.
If you don't see request #3 try the following:
replace location.href with window.location.href
try reloading it manually via console (for Chrome, F12 -> Console tab -> paste $('#todos').load(location.href + ' #todos') and hit Enter). That way you are going to skip first ajax request and just will check whether '#todo' section is loadable/reloadable.
I think it’s a cache problem. Try it like this
$('.todo--checkbox').change(function () {
let value = $(this).data('value');
$.ajax({
url: '/todo/${value}?t=202103010001',
type: 'PUT',
data: { done: this.checked },
success: $('#todos').load(location.href + ' #todos'),
});
});
t=202103010001 Set to a random number

CRUD - Add and Delete not working one after other if page is not refreshed

I have one annoying problem that I am not able to solve.
I am generating CRUD operations in my Symfony project. I made an AJAX request for Add method which works as it should.
After that I have created AJAX request for Delete method.
When I add my new entity object the table is reloaded without page refresh.
Problem is that if I click delete after it's added it throws an error that ID is not found.
/**
* #Route("/user/{id}", name="user_delete", options={"expose"=true})
*/
public function delete($id)
{
$em = $this->getDoctrine()->getManager();
$$user = $em->getRepository(User::class)
->findOneby(['id' => $id]);
if (!$user) {
throw $this->createNotFoundException('No User found for id '.$id);
}
$em->remove($user);
$em->flush();
return $this->json(["message" => "SUCCESS"]);
}
So, for example I have added entity with ID = 2 . DIV is reloaded. Now I click in delete of 2 and it's says:
No user found for id 1
Problem is it always fatches the last ID I deleted after page refresh.
Now, if I refresh the page and then try delete it will catch ID = 2 and delete it. Now, I add ID = 3 without refreshing the page and it will throw:
No user found for id 2
I think maybe it has to do with my add form:
Add form:
$('#form-submit').on('click', function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: '/subscription/add',
data: $('form#subscription-form').serialize(),
processData: false,
success: function () {
$("#user-table").load(location.href + " #user-table");
$('#addUser').modal('hide');
displayNotif('success', 'check', 'User created successfully');
},
error: function (xhr, status, error) {
var ErrorMessage = JSON.parse(xhr.responseText);
$('#general-error').html(ErrorMessage.message);
}
});
});
Can someone please help?
$(document).ready(function () {
$('.user_delete').on('click', function () {
let removeUrl = $(this).attr('data-remove-url');
$('.remove-user').attr('data-remove-url', removeUrl);
});
$(".remove-user").click(function (e) {
let removeUrl = $(this).attr('data-remove-url');
e.preventDefault();
$.ajax({
url: removeUrl,
type: 'DELETE',
success: function()
{
$("#user-table").load(location.href + " #user-table");
$('#confirmDelete').modal('hide');
displayNotif("danger", "warning", "User deleted successfully");
}
});
});
});
I am adding everything so you can get an idea of what I am doing:
<a href data-toggle="modal" data-target="#confirmDelete" data-remove-url="{{ path('user_delete', {'id':user.id}) }}" class="btn user_delete">x</a>
Option 1:
The click event is not working properly for the delete button.
Try to replace
$(".remove-user").click
With
$(".remove-user").on(“click”
Option 2:
data-remove-url
this attribute is not updated accordingly. Check your DOM to verify

AJAX query not always updating information consistently

I am experiecing some issues with AJAX updating the page. The actual data in the database is updated but this is not always reflecting in real time on the web page.
For example, I have the following event:
$("#add_note").click(function(e) {
//e.preventDefault();
$("#add_note_form").validate({
rules: {
contact_note: {
required: true
}
},
submitHandler: function(form) {
contact.modal_update({
'obj' : $('#add_note_form'),
'uri' : '/contact/add_note/'
});
}
});
});
This function when a new note is created calls a callback to validate the form fields first and then if successful calls a callback inside a seperate class to conduct the update. See the modal_update class below:
// Update modal
this.modal_update = function(data)
{//
// Declare a few variables for the data object we've received
obj = data.obj // The form element to serialize
uri = data.uri;
// Get the form ID from the data-target attribute
id = obj.attr('data-target');
// URL to send to
url = this.site_url + uri + id;
// The form object
this.post_data(obj.serialize(),url);
// Hide Modal
obj.closest('.modal').modal('hide');
// Refresh
this.refresh();
}
This then figures out the correct route to ajax and calls a ajax call back inside the same class:
// AJAX post
this.post_data = function(obj,uri)
{
$.ajax({
data: obj,
dataType: 'json',
type: 'post',
url: uri,
headers: { "cache-control": "no-cache" },
cache: false,
success: function (response) {
if (response.success == true)
{
$("#alert_success .msg").html(response.message);
$("#alert_success").fadeIn(200).delay(2000).fadeOut(200);
}
else
{
$("#alert_error .msg").html(response.error);
$("#alert_error").fadeIn(200).delay(2000).fadeOut(200);
console.log(response.error);
}
}
});
}
I am then running another class callback to "refresh" the data in all the elements on the page:
this.refresh = function()
{
// Refresh the ajax requests
this.get_contact_data();
this.get_notes();
this.get_contact_log();
this.get_contact_tasks();
}
This class re loads the functions which run on page load to get the inial data into the tables/fields on the page. See "get_notes" below:
// Get notes
this.get_notes = function()
{
// Get all notes and populate table
var log_uri = this.site_url + "/contact/get_notes/" + this.contact_id;
this.get_data(log_uri,function(data) {
notes = $("#contact_notes ul");
notes.empty("");
// Populate the contact fields, assuming there is a result to play with
if (data != false) {
//alert(JSON.stringify(data));
$("#notes-tab .count").html("(" + data.length + ")");
$.each( data, function( key, value ) {
notes.append("<li class='list-group-item' modal-id='editNoteModal' data-target='" + value.ID + "'><div class='row'><div class='col-lg-3'><i class='fa fa-sticky-note mr-3'></i>" + value.timestamp + "</div><div class='col-lg-7'>" + value.note + "</div><div class='col-lg-2'><a href='#' class='edit mr-3'><i class='fa fa-edit mr-1'></i>Edit</a><a href='#' class='delete'><i class='fa fa-times mr-1'></i>Remove</a></div></div></li>");
});
console.log('Notes loaded');
} else {
notes.append("<li>There are currently no notes for this contact</li>");
}
});
}
Now the problem:
For some reason this does not update consistently in real time. The data is updated fine on the server side but on the client side the update/refresh does not always update. I might add a note and get a correct update response but the refresh method seems to be receiving the old data and always be one note behind. So the next time I add a note, the one I added before then appears and so forth.
Another problem I am experiencing is the methods seem to stack on each event so if I add one note (or one of the other methods) I will see the console say "notes loaded" but on the second note it says "notes loaded" twice, then on the 3rd note added 3 times and so forth.
I am sure there must be something fatal flaw in the design of my code here but I am not experienced enough with javascript/jquery to notice what direction I am going wrong so I can fix it.
I thought that this was an issue with ajax caching and not refreshing the result so I have adjusted the ajax request as cache none and also to send no cache headers. I am running in wamp.
In your case, your refresh code will always run before your data got updated. Because ajax is asynchronous so the code behind and below ajax will always execute nearly the time your ajax running.
At the time you run your post_data function to call the API, the refresh function got run too. So it's done before your data got updated.
You should run refresh function inside ajax callback. For example:
this.post_data = function(obj,uri, callback)
{
$.ajax({
data: obj,
dataType: 'json',
type: 'post',
url: uri,
headers: { "cache-control": "no-cache" },
cache: false,
success: function (response) {
if (response.success == true)
{
$("#alert_success .msg").html(response.message);
$("#alert_success").fadeIn(200).delay(2000).fadeOut(200);
}
else
{
$("#alert_error .msg").html(response.error);
$("#alert_error").fadeIn(200).delay(2000).fadeOut(200);
console.log(response.error);
}
callback();
}
});
}
And in modal_update, you pass refresh function to post_data as a callback:
this.modal_update = function(data)
{//
// Declare a few variables for the data object we've received
obj = data.obj // The form element to serialize
uri = data.uri;
// Get the form ID from the data-target attribute
id = obj.attr('data-target');
// URL to send to
url = this.site_url + uri + id;
// The form object
this.post_data(obj.serialize(),url, this.refresh);
// Hide Modal
obj.closest('.modal').modal('hide');
}
You should read more about asynchronous ajax. You can use other tricky solution is setTimeout to run this.refresh but I do not recommend that because you not sure when the update is done.

don't perform database query request during ajax call if request was already done and data is available

I have a button in my view that when clicked triggers an ajax request for data on the database. Then I show the data in my page. I want to be able to hide the data if the button is clicked again and show it if it's clicked a second time and so on. I don't want to perform a new DB query everytime I click it.
so for example my request is like this:
$.ajax({
url: '../route/button,
type: 'get',
data: {_method: 'get', _token: token},
success: function (data) {
// bla bla get data from DB and insert in div
});
so once I clicked I have the data, then I click the button again and I want to toggle(); the div and data disappears from page but then if I click again I want to just toggle the div again and show the data that's already there without performing the DB query again.
Any clue?
You'll have to save the data from the ajax request. Then each time the button is clicked check to see if you have data saved. See this fiddle for an example.
;(function() {
var data = null,
$output = $('#output');
$output.hide();
$('#button').on('click', function() {
if (data === null) {
// ajax request
data = {
foo: 'bar'
};
console.log('fetching data');
// populate table with data
}
$output.toggle();
});
})();

Javascript/Jquery: setTimeout function not running AJAX query via anonymous function

I am working on a login page with some pretty animations. I would like to be able to pause the script while I run a custom animation after the user submits the login post. To simplify:
Behavior: user submits login --> load custom animation --> wait 5 seconds --> execute AJAX post --> present error or navigate to home
Here is my code in its most working form
function ValidateUser() {
var userid = $("#Username").attr('value');
var pass = $("#Password").attr('value');
var url = "/Account/ValidateUser";
var $this = $('.login'),
$state = $this.find('button > .state');
$this.addClass('loading');
$state.html('Authenticating');
setTimeout(function () {
$.ajax({
url: url,
data: { username: userid, password: pass },
cache: false,
type: "POST",
success: function (data) {
if (data == "1") {
$this.addClass('ok');
$state.html('Welcome back!');
window.location.href = "Home/Index";
} else {
$state.html('Incorrect username or password!');
$this.addClass('loginError');
$this.removeClass('ok loading');
}
$("#txtuserid").attr({ 'value': '' });
$("#txtpassword").attr({ 'value': '' });
},
error: function (reponse) {
alert(response);
$state.html('An unknown error has occurred!');
$this.addClass('loginError');
$this.removeClass('ok loading');
}
});
}, 5000);
}
After running it through firefox's javascript debugger I noticed that the ajax post is never actually run. I am developing in visual studio using C# and I place a breakpoint on the validate user method but it never hits the breakpoint.
Any help would be appreciated.
EDIT:
Here is the HTML I use to call the ValidateUser method.
<button onclick="ValidateUser()">
<i class="spinner"></i>
<span id="submit" class="state">Submit</span>
</button>
If the button is submitting the form you will have a problem.
A button without type="button" will submit - in some browsers actually submit to the page URL if no form
You likely want
$("#formID").on("submit",function (e) {
e.preventDefault();
var userid = $("#Username").attr('value');....

Categories

Resources