I'm trying to make a log parser, that updates the log every 10 seconds. It's mostly functional, but when I try to update it, it just appends the whole log again, instead of just the new data.
My Javascript:
$(document).ready(function() {
var data;
var lines;
$.ajax({
async: false,
type: 'GET',
url: 'test.log',
success: function(log) {\
data = log;
lines = data.split("\n");
console.log("Received log");
}
});
function updateLog()
{
$.ajax({
async: false,
type: 'GET',
url: 'test.log',
success: function(log) {
data = log.replace(data, "");
lines = log.split("\n");
console.log("Received log");
}
});
$.each(lines, function(n, elem)
{
$('#text').append('<div>' + elem + '</div>');
});
}
$.each(lines, function(n, elem)
{
$('#text').append('<div>' + elem + '</div>');
});
setInterval(function(){updateLog();}, 10000);
});
Example test.log content:
Hello
How are you?
But instead of it only adding potential new lines, it just copies the whole thing even though I think it shouldn't happen because of the replace, which is supposed to take the old data and change it into '' in the new data (only leaving new lines).
It looks to me like you save only the new part of last request to data, so you are actually only replacing the part of the log that was new the last time you updated the log by an empty string. Moreover, you are not using data but log (which is the full log) to compute lines, and are appending all the lines in lines to your div.
I think something like this should work:
$(document).ready(function() {
var processed_data = '';
function updateLog() {
$.ajax({
async: false,
type: 'GET',
url: 'test.log',
success: function(log) {
var new_data = log.replace(processed_data, '');
processed_data = log;
console.log("Received log");
var lines = new_data.split('\n');
$.each(lines, function(n, elem) {
$('#text').append('<div>' + elem + '</div>');
});
}
});
}
updateLog();
setInterval(function(){updateLog();}, 10000);
});
Note that I also got rid of some of the code duplication that was in your example by just calling updateLog() on load instead of copying its contents.
It would also probably be more efficient to just keep track of the length of the part of the log that is already printed. Something like this:
$(document).ready(function() {
var processed_data_length = 0;
function updateLog() {
$.ajax({
async: false,
type: 'GET',
url: 'test.log',
success: function(log) {
var new_data = log.substring(processed_data_length, log.length);
processed_data_length = log.length;
console.log("Received log");
$.each(lines, function(n, elem) {
$('#text').append('<div>' + elem + '</div>');
});
}
});
}
updateLog();
setInterval(function(){updateLog();}, 10000);
});
Strings are immutable, so the log variable isn't updated by the .replace() call. Your ajax should probably look like:
$.ajax({
async: false,
type: 'GET',
url: 'test.log',
success: function(log) {
data = log.replace(data, "");
lines = data.split("\n");
console.log("Received log");
}
});
Related
I'm trying to make a notification system that gets data every 5 secs but I don't know why it doesn't work properly. It outputs the notification endlessly but it should get the data and compare it to the last data it stored and if the data is not the same it should append the notification(s) and when it's the same it should alert "same".
var appliedData;
setInterval(getNotifications, 5000);
function getNotifications(){
$.ajax({
type: 'GET',
url: 'includes/socialplatform/friendsys/notifications.inc.php',
dataType: "json",
async: false,
success: function(data) {
if ( appliedData != data ) {
appliedData = data;
for(i=0; i < data.length; i++){
$( ".notification-container" ).append('<div class="notification"><p>' + data[i].user + '</p></div>');
}
}else{
alert("sammee");
}
}
});
}
Objects (any non-primitive: an array is an object) will never be equal to each other unless they reference the same place in memory. When comparing, your appliedData will always be different from your data, so that condition will always fail. If the response strings can be guaranteed to be the same when they represent the same object, you can simply compare the strings, as shown below. If not, you'll have to carry out a deep comparison instead.
let lastDataStr;
setInterval(getNotifications, 5000);
function getNotifications() {
$.ajax({
type: 'GET',
url: 'includes/socialplatform/friendsys/notifications.inc.php',
dataType: "text", // change here, then parse into an object in success function
async: false,
success: function(newDataStr) {
if (newDataStr === lastDataStr) {
alert('same');
return;
}
lastDataStr = newDataStr;
const newData = JSON.parse(newDataStr);
newData.forEach(({ user }) => {
$(".notification-container").append('<div class="notification"><p>' + user + '</p></div>');
})
}
});
}
I want to try to display my notification json through ajax, but however when I try first show me undefined, and then show me my json what am I doing wrong?
$(function (doc, win, $) {
var notification = win.Notification || win.mozNotification || win.webkitNotification;
var $badge = $("#notifications-badge");
var $list = $("#notifications-list");
var $button = $("#notifications-button");
URL_GET_NOTIFICATION = BASE_URL + 'notifications/getNotification';
function check_notifications() {
$.ajax({
type: 'GET',
url: URL_GET_NOTIFICATION,
//data: { timestamp : timestamp },
dataType: 'json',
async: true,
success: function (data) {
console.log(data);
}
});
}
$button.click(function (e) {
alert(check_notifications());
});
}(document, window, jQuery));
All functions return undefined by default when called, unless something else is specified.
You'd get the same with just
function go() {};
alert( go() ); // undefined
And that's basically what you're doing, alerting a function that doesn't return anything.
If you return something from the function, it works
function go() { return 'Hello Kitty' };
alert( go() ); // Hello Kitty
But, as you're using ajax inside the function, you can't really return the result from that, as it's asynchronous and executes some time after the result is returned.
You'd have to use a callback or promise to make it work.
function check_notifications() {
return $.ajax({
type: 'GET',
url: URL_GET_NOTIFICATION,
//data: { timestamp : timestamp },
dataType: 'json'
});
}
$button.click(function (e) {
check_notifications().done(function(data) {
alert(data);
});
});
As a sidenote, use the console when debugging, not alerts.
I have an each() loop in my AJAX handler to do push into my temp array, but in the end I still get an empty array. It's strange, I remember I once use promise on each() so it has no problem.
var temp = [];
$.ajax({
type: 'GET',
url: '/endpoint',
success: function(data) {
$(data).each(function() {
//do some stuff
console.log(something); // working
temp.push(something);
}).promise().done(function() {
console.log(temp); // still empty array?!
});
});
update: here's how people has done it https://stackoverflow.com/a/8941358/7095330
Reducing your script to what your question is asking, everything seems to be working fine. Hopefully this will help you find out that your problem is somewhere else in your code:
var temp = [];
var data = [1,2,3,4,5,6,7,8];
$(data)
.each(function(thing) {
//do some stuff
console.log(thing); // working
temp.push(thing);
})
.promise()
.done(function() {
console.log(temp); // still empty array?!
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
However the promise().done() is pretty weird; I can't see why you'd need that there.
Sounds like a case for map, where you have an input array and you want to transform its contents.
var data = [1,2,3,4,5,6,7,8]
var changedData = data.map(function (datum) {
// do stuff
return 'did stuff to ' + datum;
});
console.log(changedData)
Unless what you were trying to do was the following, which still works. PEBKAC error perhaps?
var temp = [];
$.ajax({
type: 'GET',
url: 'https://google.com/',
// replaced success: with error:, for example's sake
error: function(data) {
$(data).each(function() {
//do some stuff
console.log('something');
temp.push('something');
}).promise().done(function () {
console.log('each done', temp);
});
},
done: function() {
console.log('ajax done:', temp);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You forgot a bracket }
var temp = [];
$.ajax({
type: 'GET',
url: '',
success: function(data) {
$(data).each(function() {
//do some stuff
console.log('something'); // working
temp.push('something');
}).promise().done(function() {
console.log(temp); // still empty array?!
});
}});
see https://jsfiddle.net/gw10un58/
I have the following AJAX function that has 2 variables i.e. sTitle, sValue. I need these two variables to be added to an Array in the format of ArrayName[sTitle, sValue]. I have tried this using a for loop but couldn't get the result I expected. I'm hoping to use this array to draw a Google chart. The data source is an XML.
I'm trying to implement this For Loop and array within the AJAX Call.
So how can I solve this matter?
AJAX Function
$(document).ready(function() {
$.ajax({
type: "GET",
url: "ChartData.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('Pie').each(function() {
var sTitle = $(this).find('Title').text();
var sValue = $(this).find('Value').text();
});
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
});
You can do it like this
var values = [];
function callback(val) {
// Do something with the array here
};
$(document).ready(function() {
$.ajax({
type: "GET",
url: "ChartData.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('Pie').each(function() {
var sTitle = $(this).find('Title').text();
var sValue = $(this).find('Value').text();
values.push([sTitle, sValue]);
});
callback(values);
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
});
I am sending a request by post using jquery ajax, but some of the words i send have + to join words like: HTA+HIPERAQUITISM+DBLR, the php recieve HTA HIPERAQUITISM DBLR changing the + by blank spaces, i post the code below. help!
function getItemInfo(itemName, itemField, itemComparative, itemTable){
var result = "";
var nombreItem = itemName;
var campoItem = itemField;
var comparativeItem = itemComparative;
var tableItem = itemTable;
$.ajax({
type: 'POST',
async: false,
url: 'modules/medicos/controller.php?fun=consul_item&nombre_item=consul_item'+
'&nombre_item='+nombreItem+
'&campo='+campoItem+
'&comparador='+comparativeItem+
'&tabla='+tableItem,
success: function(data) {
result = data.toString();
},
failure: function() {
result = "";
}
});
return result;
}//end function
This is because in a URL + means space.
You'll need to URL encode the data first before adding it to the query string.
You can use the encodeURIComponent() function to encode your value before adding it to the query string.
Once your PHP code picks it up you can then decode the value with the urldecode function
So your code should update to something like this:
url: 'modules/medicos/controller.php?fun=consul_item&nombre_item=consul_item'+
'&nombre_item='+encodeURIComponent(nombreItem)+
'&campo='+encodeURIComponent(campoItem)+
'&comparador='+encodeURIComponent(comparativeItem)+
'&tabla='+encodeURIComponent(tableItem),
Your code seems to be correct. You are passing those variables one by one (nombreItem, campoItem, comparativeItem and tableItem). So I don't really understand what you say is not working.
A suggestion to make passing data easier:
$.ajax({
type: 'POST',
async: false,
url: 'modules/medicos/controller.php',
data : ({ fun : consul_item,
nombre_item : nombreItem,
campo : campoItem,
comparador : comparativeItem,
tabla : tableItem }),
success: function(data) {
result = data;
},
failure: function() {
result = "";
}
});
If you want to pass all your info as one textual string you should do:
...
data: ({ test : consul_item + '+' + nombreItem + '+' + campoItem + '+' + comparativeItem + '+' + tableItem }),
...