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

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

Related

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.

Ajax jquery making web api call

I made an api in java , which allows the user to get data.
there is an call : ..../api/users where i give a list back of all users avalible.
Now i got a site with a search user button, wen you press that button i want to make a call to /api/users with the help of Ajax.
i got the part that you can click on the search button, but i don't understand how to make that call with ajax
This is my code:
$.ajax({
url: ”api / resource / users ",
dataType: "json”,
}
).fail(
funcNon(jqXHR, textStatus) {
alert("APIRequestfailed: " + textStatus);
}
).done(
funcNon(data) {
alert("succes!")
}
);
Is this the way of making a good call with ajax ?
or do i have to use :
http://localhost/projectUser/api/resource/users ?
Assuming you are using JQuery to make the Ajax call then this sample code should be helpful to you. What it does is;
On search button was clicked
Do AJAX call to fetch stuff from your Java REST API
When the expected JSON object was returned, parse it and do something
O
$(document).ready(function() {
$('#demoSearchBtn').click(function () {
// Search button was clicked!
$.ajax({
type: "GET",
url: "http://localhost/projectUser/api/resource/users", // edit this URL to point into the URL of your API
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (data) {
var jsonObj = $.parseJSON(data);
// Do something with your JSON return object
},
error: function (xhr) {
alert('oops something went wrong! Error:' + JSON.stringify(xhr));
}
});
});
}
if this http://localhost/projectUser/api/resource/users is the url, it's either
$.ajax({
url: ”api/resource/users", ...
or
$.ajax({
url: ”http://localhost/projectUser/api/resource/users", ...
depending on what the browsers current URL is (relative or absoute depends on context of the browser).
but it is never ever ”api / resource / users " with spaces between words and slashes.

Request data from server using AJAX and Jquery

I need to create a script that takes data from a form, send it to a server (there's some diabolical C# procedure on it, that's not my job...), the server resolves the string and reply me with 4 strings (yup, they are in spanish): 'pendiente', 'verificada', 'rechazada', and finally 'error'
Now, I have to get that response and properly show the correct message (hidden-inline html).
All this procedure shouldn't "refresh" the actual page, so I'm using AJAX for this.
Have in mind I'm a newbie :) I've learned Jquery just for this task,
and I have to say I'm quite happy with this.
The problem
I don't really know how to handle or "manipulate" that request using Jquery... I figured how to send the data to the server, but I think I'm handling incorrectly the response.
The code:
In this case I've adapted the script, every different response should get its own border color, I'm using conditionals (they are wrong for sure) to add CSS clases to an #ajax div.
So, it might have silly errors...
$(document).ready(function () {
$('#enviar').click(function (event) {
event.preventDefault(); //avoid page refresh
var consulta = $('#string').val();
$("#normal").text(consulta);
//Start AJAX!
$.ajax({
async: true,
cache: false,
type: 'post',
url: 'http://184.22.97.218:8081/chequeostatusdonation', //la del servr
data: {
html: consulta
},
dataType: 'html',
beforeSend: function () {
console.log('Sending...');
},
success: function (data) {
console.log('Just sent -'+data+'- with success dooh');
$('#ajax').html(data);
//start conditional
if (data == pendiente) {
$("#ajax").addClass(pendiente);
} else if (data == verificada) {
$("#ajax").addClass(verificada);
} else if (data == rechazada) {
$("#ajax").addClass(rechazada);
} else {
$("#ajax").html('<h1>error</h1>');
}
//end condicional
},
complete: function () {
console.log('Listo el pollo');
}
});
});
});
Here is the JSFiddle
Edit: Now, I just found these two links
learn.jquery.com/code-organization/concepts/
learn.jquery.com/code-organization/beware-anonymous-functions/
Screw my code! :D
Async is by default "true", so you don't need to mention that one in your code.
You included a link to the server (in the URL-field), but what is the file you are trying to open? You will need to include the path to where you will get the data from (file / script). To make Ajax work, you will need to respect the "same origin policy", so you can insert a relative path to the file / script.
Is the response of your call always a short string with one of those key words ('pendiente', 'verificada', 'rechazada' or 'error)? In that case I would recomment using "text" instead of "html" as dataType, as jQuery will try to parse it to a DOM-structure, which is not what you want here.
Your if-statements (and class-assignments as well) aren't working because you try to compare it to a non-excisting variable instead of the string with that value. You should use " or ' around your string to solve that.
This code should be working. If not, let me know. Include the error given in the console of the browser.
$(document).ready(function () {
$('#enviar').click(function (event) {
event.preventDefault(); //avoid page refresh
var consulta = $('#string').val();
$("#normal").text(consulta);
//Start AJAX!
$.ajax({
type: 'POST',
cache: false,
url: 'RELATIVE_PATH_HERE', //la del servr
data: {
html: consulta
},
dataType: 'text',
beforeSend: function () {
console.log('Sending...');
},
success: function (data) {
console.log('Just sent -'+data+'- with success dooh');
$('#ajax').html(data);
//start conditional
if (data === 'pendiente') {
$("#ajax").addClass('pendiente');
} else if (data === 'verificada') {
$("#ajax").addClass('verificada');
} else if (data === 'rechazada') {
$("#ajax").addClass('rechazada');
} else {
$("#ajax").html('<h1>error</h1>');
}
//end condicional
},
complete: function () {
console.log('Listo el pollo');
},
error: function() {
console.log('Problem with XHR-request');
});
});
});
Be careful with .addClass if you process multiple Ajax-calls as they will add on each other.

Page Loading Problems - AJAX Related?

I'm running a test website for a bit for me and my friends to play around with before I roll it into my actual site.
One of the things this test website does is have a "feed" where users can insert text/images and etc. through a form.
I use AJAX for inserting content into the "feed" and also use it to refresh the feed.
However after a user plays with it for a while and posts stuff, they eventually can't post or load the page.
I'm a beginner to AJAX or whatever, but what is the cause of this? Is it AJAX related since I'm sending requests often? (10,000 ms too much?)
function WallPost() {
REQUESTED_NAME = document.registerForm.NAME.value;
REQUESTED_BODY = document.registerForm.BODY.value;
if (!localStorage.name) {
localStorage.name = REQUESTED_NAME;
}
$.ajax({
type: "POST",
url: "/wall.php",
data: "NAME=" + REQUESTED_NAME + "&BODY=" + REQUESTED_BODY + "&FORM=1&IP=i",
success: function(msg) {
$("#registerMessage").append(msg);
}
});
document.registerForm.BODY.value = "";
RetrieveWall();
}
function RetrieveWall() {
$.ajax( {
url: "/getwall.php",
success: function(msg2) {
$("#wall").html(msg2);
}
});
window.setTimeout("RetrieveWall()", 10000);
}
$.ajax( {
url: "/getip.php",
success: function(i) {
IP = i;
}
});
10 seconds seems fine, so I doubt the problem is the frequency.
To determine the true problem we would need either javascript console output and/or server logs.

How do I reload the page after all ajax calls complete?

The first time a user is visiting my website, I am pulling a lot of information from various sources using a couple of ajax calls. How do I reload the page once the ajax calls are done?
if(userVisit != 1) {
// First time visitor
populateData();
}
function populateData() {
$.ajax({
url: "server.php",
data: "action=prepare&myid=" + id,
dataType: "json",
success: function(json) {
if(json.error) {
return;
}
_id = response[json].id;
getInformation(_id);
}
});
}
function getInformation(id) {
$.ajax({
url: "REMOTESERVICE",
data: "action=get&id=" + id,
dataType: "json",
success: function(json) {
if(json.error) {
return;
}
$.ajax({
url: "server.php",
data: "action=update&myid=" + id + '&data=' + json.data.toString(),
dataType: "json",
success: function(json) {
if(json.error) {
return;
}
}
});
}
});
}
So what the code does is, it gets a list of predefined identifiers for a new user (populateData function) and uses them to get more information from a thirdparty service (getInformation function). This getInformation function queries a third party server and once the server returns some data, it sends that data to my server through another ajax call. Now what I need is a way to figure out when all the ajax calls have been completed so that I can reload the page. Any suggestions?
In your getInformation() call you can call location.reload() in your success callback, like this:
success: function(json) {
if(!json.error) location.reload(true);
}
To wait until any further ajax calls complete, you can use the ajaxStop event, like this:
success: function(json) {
if(json.error) return;
//fire off other ajax calls
$(document).ajaxStop(function() { location.reload(true); });
}
.ajaxStop() works fine to me, page is reloaded after all ajax calls.
You can use as the following example :
$( document ).ajaxStop(function() {
window.location = window.location;
});
How it's works?
A: Whenever an Ajax request completes, jQuery checks whether there are any other outstanding Ajax requests. If none remain, jQuery triggers the ajaxStop event.
Hope help y'all, furthermore information, I'm sharing the link of the documentation following.
source: https://api.jquery.com/ajaxstop/
You could just redirect to the same page in the server.php file where the function is defined using a header('Location: html-page');
//document.location.reload(true);
window.location = window.location;
See more at: http://www.dotnetfunda.com/forums/show/17887/issue-in-ie-11-when-i-try-to-refresh-my-parent-page-from-the-popupwind#sthash.gZEB8QV0.dpuf

Categories

Resources