AJAX, PHP, MySQL. (refreshing tables without blink) - javascript

I can't find a solution for this and I can't believe I can't find just one example!
Ok, I have a kind of monitory (PHP / MySQL), refreshed by Javascript. The thing is, that my script reload an entire php page, where I have the MySQL Querys. So, every reload I see a little blink, which is nothing else that the page loading.
This is what I have:
(function($) {
$(document).ready(function() {
$.ajaxSetup( {
cache: false,
beforeSend: function() {
$('#colas').hide();
$('#loading').show();
},
complete: function() {
$('#loading').hide();
$('#colas').show();
},
success: function() {
$('#loading').hide();
$('#colas').show();
}
});
var $colas = $("#colas");
$colas.load("panelColasRealtime.php");
var refreshId = setInterval(function() {
$colas.load('panelColasRealtime.php');
}, 8000);
});
})(jQuery);
I load "panelColasRealtime.php" right here:
<div id="colas"></div>
This is working, but I don't want this solution, I don't like that blink. I want to refresh the monitory without reload the php page, just the data.
I think that AJAX is my best choice, but I can't find any example.
Summarizing:
I would like a realtime monitory (every X secods) of my BD and show it .
If anyone has an example script I would really appreciated it.

if you just want to refresh the data here is a simple example which refreshes every 5 seconds
$(document).ready(function() {
loadData();
});
var loadData = function() {
$.ajax({
type: "GET",
url: "data_source_page.php",
dataType: "html",
success: function(response) {
$(".refresh").html(response);
setTimeout(loadData, 5000);
}
});
};
html
<div class="refresh"></div>

Related

Problem using multiple jquery ajax request in a single page

Hello i am working on a PHP Project where i need to load some request using ajax request. Below are my request function.
Function One: When showNotify event is click i call the ajax request to get content and use ajaxStart to show spinner untill the content is fully ready!
//* First click load nofication
$(document).on('click', '#showNotify', function() {
let check = $(this).data('check');
if(check === 0) {
//* Process notification
$(this).attr('data-check', 1);
//* Load ajax request
$(document).ajaxStart(function() {
$('#notify-wait').show();
});
$(document).ajaxComplete(function() {
$('#notify-wait').hide();
$('#list-noti').show();
});
$.ajax({
url: '/list-dd-notifications',
method: 'GET',
success: function() {
$('#notif-unread').hide();
}
});
}
});
Function Two: i need to check from the server side to see if user has a new unready notify and show up the new notification sign.
function checkNewFotify() {
$.ajax({
url: '/check-notifications',
method: 'GET',
success: function(data) {
if(data) {
if($('#notif-unread').is(":hidden"))
{
$('#notif-unread').show();
}
}
else
{
if($('#notif-unread').is(":visible"))
{
$('#notif-unread').hide();
}
}
}
});
}
//* check for new notification
setInterval(() => {
checkNewFotify();
}, 5000);
Problem: Any time the showNotify is dropdown at first it show the spinner the loader until the request is fully loaded also if the function checkNewFotify is doing is job by refreshing every 5 secs to check the server for new notification the ajaxStart in showNotify will be affected by showing the spinner loader every time the checkNewFotify is refreshing in background.
Please how can i stop it from showing the spinner loader whil it refreshing every 5 seconds.
Set the global option to false on the ajax on checkNewFotify() this will prevent handlers like ajaxStart from firing.
$.ajax({
url: '/check-notifications',
method: 'GET',
global: false,
});

Using beforeSend and complete in every instance of ajaxForm globally

I am trying to use the beforeSend and complete functions on all ajaxForms in a project. I would like to do this without adding the exact bit a code all throughout the project.
I've been able to accomplish this with the below code on a per form basis.
beforeSend: function() {
$('.lightbox').append('<div id="page-loader" style="display:block"><div class="page-loader-overlay"></div><div class="page-loader-content-container"><div class="top-corners"><div></div></div><div class="middle"><div class="page-loader-content">Loading...</div></div><div class="bottom-corners"><div></div></div></div></div>');
},
complete: function(xhr) {
$('.lightbox#page-loader').remove()
},
I'd like to be able to put that code into one place that executes every time an ajaxForm is submitted. Is this possible?
$(function(){
$.ajaxSetup({
beforeSend: function() {
$('.lightbox').append('<div id="page-loader" style="display:block"><div class="page-loader-overlay"></div><div class="page-loader-content-container"><div class="top-corners"><div></div></div><div class="middle"><div class="page-loader-content">Loading...</div></div><div class="bottom-corners"><div></div></div></div></div>');
},
complete: function(xhr) {
$('.lightbox#page-loader').remove()
},
});
});
Please use the function ajaxsetup. When you do it this way it will be valid in all ajax functions.
Referrer : https://api.jquery.com/jQuery.ajaxSetup/
If anyone runs across a similar dilemma, this is what I came up with and it seems to do the trick. I haven't found any problems with this thus far.
// add loading masks on form submits
$( document ).ajaxSend(function() {
$('.lightbox').append('<div id="page-loader" style="display:block; z-index: 999"><div class="page-loader-overlay"></div><div class="page-loader-content-container"><div class="top-corners"><div></div></div><div class="middle"><div class="page-loader-content">Loading...</div></div><div class="bottom-corners"><div></div></div></div></div>');
});
$(document).ajaxSuccess(function() {
$('#page-loader').remove()
});

jQuery Load And Ajax Forms Not Working Together

I've created a news system, where i should be able to edit articles dynamically without redirect, from a modal. Also, i should be able to delete and create articles.
When something is changed, jQuery Load is called, but the problem is when i have to edit the loaded content.
$("#toolbox-items").load('inc-toolbox');
The above code loads the articles (the file is called inc-toolbox on purpose and works fine).
$(function () {
$('form').on('submit', function(e) {
e.preventDefault();
var clicked = document.activeElement.getAttribute('name');
$.ajax({
type: 'post',
url: 'process-toolbox',
data: $(this).serialize() + "&" + clicked + "=success",
success: function (response) {
$("#toolbox-items").load('inc-toolbox');
$('.modal-backdrop').remove();
}
});
});
});
But, when ever something has to be edited or deleted, the whole page reloads and nothing changes, although i'm still able to add things.
The add-button is not loaded dynamically from the script, but is in there from the start.
What in the world might the problem be?
Try code like this
$(function () {
$(document).on('submit','form', function(e) {
e.preventDefault();
var clicked = document.activeElement.getAttribute('name');
$.ajax({
type: 'post',
url: 'process-toolbox',
data: $(this).serialize() + "&" + clicked + "=success",
success: function (response) {
$("#toolbox-items").load('inc-toolbox');
$('.modal-backdrop').remove();
}
});
});
});

What is the proper way of doing long polling using jQuery and AJAX

I have a project which involves live notification. So I stumbled upon using socket io but I didn't have enough time to learn it yet. So I tried doing it with AJAX and jQuery. Below is my code structure and I was wondering if this is gonna work with no drawbacks?
setInterval(function(){
if( !element.hasClass('processing') ){
element.addClass('processing');
$.ajax({
type: 'post',
dataType: 'json',
url: ajaxurl,
data: {},
success: function( response ){
/* Success! */
element.removeClass('processing');
}
});
}
}, 2500);
Some Extra Info
The way you described will work. From Experience I would just like to point out some things.
I usually do a recursive function, allows you to wait your interval between ajax calls and not a fixed rate. //OPTIONAL BUT DOES GIVE THE SERVER SOME BREATHING ROOM.
Use window.setTimeout() with an isActive flag. //ALLOWS YOU TO STOP POLLING FOR WHATEVER REASON, AND BECAUSE FUNCTION IS RECURSIVE START UP AGAIN IF NEED BE
For Sake of being thorough, I found it is always a good idea to handle the error case of the $.ajax() post. You could perhaps display some message telling the user he is no longer connected to the internet etc.
Some Sample Code:
var isActive = true;
$().ready(function () {
//EITHER USE A GLOBAL VAR OR PLACE VAR IN HIDDEN FIELD
//IF FOR WHATEVER REASON YOU WANT TO STOP POLLING
pollServer();
});
function pollServer()
{
if (isActive)
{
window.setTimeout(function () {
$.ajax({
url: "...",
type: "POST",
success: function (result) {
//SUCCESS LOGIC
pollServer();
},
error: function () {
//ERROR HANDLING
pollServer();
}});
}, 2500);
}
}
NOTE
This is just some things I picked up using the exact method you are using, It seems that Web Sockets could be the better option and I will be diving into that in the near future.
Please refer :
Jquery : Ajax : How can I show loading dialog before start and close after close?
I hope this could help you
$("div.add_post a").click(function(){
var dlg = loadingDialog({modal : true, minHeight : 80, show : true});
dlg.dialog("show");
$.ajax({
url : "/add.php",
complete : function (){
dlg.dialog("hide");
}
});
return false;
});
//--Loading dialog
function loadingDialog(dOpts, text = "пожалуйста подождите, идет загрузка...")
{
var dlg = $("<div><img src='/theme/style/imgs/busy.gif' alt='загрузка'/> "+text+"<div>").dialog(dOpts);
$(".ui-dialog-titlebar").hide();
return dialog;
}

Get More Table Data On Page Scroll AJAX

I am populating table data with PHP and JQUERY
The problem is that the scroll function is not firing off. I do not have any errors.
I thought maybe I did not load Jquery in the page correctly so I did,
alert( "This means you have JQUERY" );
The alert function did fire off. This is a wordpress site I am working with a plugin and a template file that I wrote.
Is there any reason why the scroll effect might not work? I have never used this before. Could I possible need to load additional libraries or something of that nature?
$(document).ready(function(){
function getresult(url) {
$.ajax({
url: url,
type: "GET",
data: {rowcount:$("#rowcount").val()},
beforeSend: function(){
$('#loader-icon').show();
},
complete: function(){
$('#loader-icon').hide();
},
success: function(data){
$("#productResults").append(data);
},
error: function(){}
});
}
$(window).scroll(function(){
if($(document).height() <= $(window).scrollTop() + $(window).height()) {
if($(".pagenum:last").val() <= $(".total-page").val()) {
var pagenum = parseInt($(".pagenum:last").val()) + 1;
alert.function('Hey the scroll effect works.');
getresult('../wuno-search/inventory-search.php?page='+pagenum);
}
}
});
});
Also I am confused exactly how to add PHP to this function
getresult('../wuno-search/inventory-search.php?page='+pagenum);
For example if I wanted to change the url path to a variable like this,
getresult('<?php echo $assetPath ?> ?page='+pagenum);
Is that correct?

Categories