I am creating a real-time graph with flot library and using jquery $.get function.
I want the graph to be updated every 5 seconds retrieving the recorded data.
The X axis is in time mode. I have been trying to retrieve the necessary data but i can't get it yet. The .php file is fine because it connects to the postgresql database and writes the data into the requested variable.
I think that my problem is in the $.get function.
Can you please help me to find if my Javascript code is fine?
Thanks in advance
<script type="text/javascript">
$(function () {
var data=[];
var data_inicial = [];
var data_actual = [];
var x;
var y;
function data_init()
{
$.get("param_pozos_linea1.php", function(data1) { x= data1; });
data_inicial.push([x]);
return data_inicial;
}
function actualiza_data()
{
$.get("param_pozos_linea2.php", function(data2) { y= data2; });
data_actual.push(y);
return data_actual;
}
// control de velocidad
var updateInterval = 500;
$("#updateInterval").val(updateInterval).change(function () {
var v = $(this).val();
if (v && !isNaN(+v)) {
updateInterval = +v;
if (updateInterval < 1)
updateInterval = 1;
$(this).val("" + updateInterval);
}
});
// setup plot
var options = {
series: { shadowSize: 0 }, // drawing is faster without shadows
yaxis: { min: 0, max: 100 },
xaxis: { mode: "time",tickLength: 5, timeformat: "%d/%m - %h:%M %p"}
};
var plot = $.plot($("#placeholder"), data_init() , options);
function update() {
plot.setData([ actualiza_data() ]);
plot.draw();
setTimeout(update, updateInterval);
}
update();
});
</script>
The retrieved data from "param_pozos_linea1.php" file loooks like this:
[1355767803000,0],[1355767502000,0],[1355767202000,0],[1355766902000,0],[1355766602000,0],[1355766302000,0],[1355766002000,0],[1355765702000,0],[1355765402000,0],[1355765103000,2570.17],[1355764803000,2569.63]
And the retrieved data from "param_pozos_linea2.php" looks like this:
[1355767803000,0]
The get request is asynchronous, it is impossible for it to work in a synchronous manner like you think it does.
function data_init()
{
$.get("param_pozos_linea1.php", function(data1) { x= data1; }); <-- calls the server asynchronously
data_inicial.push([x]); <-- is called before code is set on server, so it is setting it with what ever the last value was
return data_inicial; <-- returns something you do not want
}
what you want to do is call the function that set the data
function data_init()
{
$.get("param_pozos_linea1.php",
function(data1) {
data_inicial.push([data1]);
callYourPlotFunction(data_inicial);
}
);
}
Related
I have a jQuery function that loads a PHP file (which gets a JSON response from an application) every 100ms. What I am trying to do is have two different counters, one which will increment every time a request is sent and another counter which will increment as soon as it gets a JSON response. At the moment I have the following which is not working, they are both just counting the number of requests being sent:-
JQUERY
$(function() {
var MAXNUM = 9;
var count = 0;
var countSuccess = 0;
function newAsyncRequest() {
setTimeout(function() {
newAsyncRequest();
count++;
$(".request").html(count);
$.get('test.php', function(data) {
countSuccess++;
$( ".log" ).html(countSuccess);
});
}, 100);
}
newAsyncRequest();
});
PHP
require_once('scripts/php/controllers/curl.controller.php');
$postcode = 'LE11 5';
$postcode = rawurlencode($postcode);
$uri = 'http://192.168.1.110:8290/?pc='.$postcode; // Home
$response = CurlController::request($uri);
So my question is basically, how can I count the number of successful responses I am getting from .$get command?
Need to print count to .request, you were using countSuccess in both the statements
$(function() {
var MAXNUM = 9;
var count = 0;
var countSuccess = 0;
function newAsyncRequest() {
setTimeout(function() {
newAsyncRequest();
count++;
$(".request").html(count);
//need to print here
$.get('test.php', function(data) {
countSuccess++;
$( ".log" ).html(countSuccess);
});
}, 100);
}
newAsyncRequest();
});
You can use $.ajax's success parameter. The function passed to this parameter will only run if an ajax request is successful.
$.ajax({
url:"",
type: "get",
beforeSend: function(){ requestCounter++ },
success: function(){ successCounter++ }
});
What are you defijning as a success?
The .get 'success' is that the server responded which it hopefully always will do.
If you are definign success as somthign working in the PHP script then in the PHP then in the jquery success function check what was returned in 'data' to see if it was succesful.
I generally return a Json encoded array with an element called 'result' that is either set to ture or false by the PHP and the jquery can simple act on that record.
I am trying create map with amCharts using jquery ajax but it doesnt work with ajax.
here my ajax code:
$('button#btn').click(function(){
$('div#ozellikli').html('<center><img src="assets/img/loading.gif" width="200" height="200"/></center>')
$.ajax({
type:'post',
url:'ozellikliAjax.php',
data:$('form#oz').serialize(),
success:function(msg){
$('div#ozellikli').html(msg);
}
});
});
Here my ajax php code:
<?php
include 'config.php';
$html="";
$yil=$_POST['yil'];
$tur=$_POST['tur'];
///HARITAYI CIZ
$sql="SELECT id,il,COUNT(kurum) AS kurum_Say FROM ozellikli GROUP BY id,il ORDER BY kurum_Say";
$result=$baglanti->query($sql);
$mapChart="";
while ($query=$result->fetch(PDO::FETCH_ASSOC)) {
$mapChart.=' { title: "'.$query['il'].':'.$query['kurum_Say'].'", id: "TR'.$query['id'].'",value:'.$query['kurum_Say'].', selectable: true },';
}
$html.='<script type="text/javascript">
AmCharts.ready(function() {
var map;
// *** CREATE MAP ***********************************************************
function createMap(){
map = new AmCharts.AmMap();
map.pathToImages = "http://www.ammap.com/lib/images/";
//map.panEventsEnabled = true; // this line enables pinch-zooming and dragging on touch devices
var dataProvider = {
mapVar: AmCharts.maps.turkeyLow
};
map.areasSettings = {
unlistedAreasColor: "#43B1A9",
rollOverOutlineColor: "#FFFFFF"
};
map.colorSteps=5;
map.valueLegend={
left: 10,
bottom:0,
minValue: "En Az",
maxValue: "En Çok"
};
dataProvider.areas = ['.$mapChart.'];
map.dataProvider = dataProvider;
map.addListener(\'clickMapObject\', function (event) {
// deselect the area by assigning all of the dataProvider as selected object
map.selectedObject = map.dataProvider;
// toggle showAsSelected
event.mapObject.showAsSelected = !event.mapObject.showAsSelected;
// bring it to an appropriate color
map.returnInitialColor(event.mapObject);
var states = [];
for (var i in map.dataProvider.areas) {
var area = map.dataProvider.areas[i];
if (area.showAsSelected) {
states.push(area.title);
}
}
});
map.write("mapdiv");
}
createMap();
});
</script>';
echo $html;
?>
when run the ajax code , script loading with ajax correctly but its not charting to map.
How can I solve this issue?
thanks
If you inject the resources the same way, you need to set manually it's ready state otherwise it won't work. AmCharts listens to the dom loaded event to set following property:
AmCharts.isReady = true;
I am trying to update on screen without refresh the current percentage that is updated into a database when the user checks something but failed to accomplish this.
Problem is that in the console I get the error TypeError: a is undefined ..."resolve"],fail:[b,"reject"],progress:[c,"notify"]},function(a,b){var c=b[0],e=b
and the GET request is repeated infinite. Within the get request, the response is:
{"percentage":null}. An additional problem is that the GET request seams to load complete (like getting the final response) only when the php script finishes.
I checked the database and every time I refresh the database dynamically I can see the percentage updating. So it's not a problem from the PHP or SQL, may be a problem from getter.php (file that is printing the result) and the json script.
Please help me on this issue I checked the entire day + yesterday on how to echo value from database live and tried lots of examples but did not understood complete how to do it (this is mostly related to jquery knob, want to implement it there after success). Your help is much appreciated.
Jquery:
jQuery_1_11_0('#check').on('submit', function (e) {
done();
function done() {
setTimeout(function () {
updates();
done();
}, 1000);
}
function updates() {
$.getJSON("lib/getter.php", function (data) {
$("#progressbar").empty();
$.each(data.result, function () {
percentage = this['percentage'];
if (percentage = null) {
percentage = 100;
$("#progressbar").html(percentage);
}
});
});
}
});
process.php
$urlsarray = array('google.com', 'yahoo.com', 'bing.com');
// this is a dynamic array created by the user, I am giving just a simple example
$counter = 0;
$total = count($urls1);
$session_id = rand(100000000000000, 999999999999999);
$db->query("INSERT INTO sessions (session_id, percentage) VALUES ('$session_id', '$counter')");
foreach ($urlsarray as $urls) {
doing some things
$counter++;
$percentage = ($counter/$total) * 100;
$db->query("UPDATE sessions SET percentage = '$percentage' WHERE session_id = '$session_id'");
}
$db->query("DELETE FROM sessions WHERE session_id = '$session_id'");
$percentage = 100;
getter.php
include("process.php");
global $session_id;
$readpercentage = $db->query("SELECT percentage FROM sessions WHERE session_id = '$session_id'");
$percentage = $readpercentage->fetch_assoc();
echo json_encode(array('percentage' => $percentage));
ob_flush();
flush();
EDIT 2 UPDATE
function updates() {
$.getJSON("lib/getter.html", function (data) {
$("#progressbar").empty();
$("#progressbar").html(data.percentage);
});
}
EDIT 3
var myInterval = setInterval(function(){ updates(); }, 1000);
function updates() {
$.getJSON("lib/getter.html", function (data) {
//$("#progressbar").empty();
console.log(data);
$("#progressbar").html(data.percentage);
if(data.percentage >= 100){
clearInterval(myInterval);
}
});
}
EDIT 4. changed getter.php
include("process.php");
//global $session_id;
//echo $session_id;
$readpercentage = $db->query("SELECT percentage FROM sessions WHERE session_id = '$session_id'");
$percentage = $readpercentage->fetch_assoc();
$percentage = (int) $percentage['percentage'];
if ($percentage = 100) {
$percentage = 100;
}
echo json_encode(array('percentage' => $percentage));
ob_flush();
flush();
and the js script
var jQuery_1_11_0 = $.noConflict(true);
jQuery_1_11_0('#check').on('submit', function (e) {
var myInterval = setInterval(function(){ updates(); }, 1000);
function updates() {
$.getJSON("lib/getter.html", function (data) {
var percentage = data.percentage;
$("#progressbar").html(percentage).show();
if(percentage >= 100 || typeof percentage !== 'undefined'){
clearInterval(myInterval);
}
});
}
});
// second script is for posting the result
jQuery_1_11_0('#check').on('submit', function (e) {
var validatef = $("#url").val();
var validaterror = $('#errorvalidate');
if (validatef == 'Enter Domains Separated By New Line -MAX 100 DOMAINS-') {
validaterror.text('Please enter domain names in the text area');
e.preventDefault();
} else {
validaterror.text('');
$.ajax({
type: 'post',
url: 'lib/process.php',
data: $('#check').serialize(),
success: function (data) {
$("#result").html(data); // apple
// $("#progressbar").knob().hide();
}
});
e.preventDefault();
} // ending the else
});
I cant help but wonder:
done();
function done() {
setTimeout(function () {
updates();
done();
}, 1000);
}
How does this recursion stops? Because to me it seems like this timeout will keep on firing eternally. You really need a timeInterval here, set it to a variable, and clear the interval when 100% has been reached.
Maybe replace the above with:
var myInterval = setInterval(function(){
updates();
}, 1000);
then, on the updates function
if(percentage >= 100){
clearInterval(myInterval);
}
By the way, doing:
if(percentage = null){
...
}
Did you mean to compare using = instead of == ? If you want to verify that percentage is set and is a valid number, it would probably be a good idea to do:
if(typeof percentage !== 'undefined' && !isNaN(parseFloat(percentage)){
...
}
Look at what you're sending back to your JS code from PHP:
echo json_encode(array('percentage' => $percentage));
Literally that'll be
{"percentage":42}
In your JS code, you then have:
$.getJSON("lib/getter.php", function (data) {
^^^^---the data coming back from PHP
....
$.each(data.result, function () {
^^^^^^---since when did you put a "result" key into your array?
For this JS code to work, you'd have to be doing
echo json_encode(array('result' => $percentage));
^^^^^^---note the new key.
And note that since you're sending back a SINGLE object in the JSON, with a single key:value pair, there is literally no point in using your inner $.each() loop. You could just as well have
$("#progressbar").html(data.percentage);
I have a PHP process which updates files, and writes a status report with each file.
While that is happening, I was hoping to update the user's browser until the final response.
Unless there is a better way, I simply wanted some advice on how to loop infinitely refreshing getJSON() results until the ajax response comes.
What is the best way to do this?
This ended up being the solution I used:
$(document).on('click', "#ss_batch_edit_processing", function (e) {
var ids = get_selected();
var status_location = '<?php echo symbiostock_TMPDIR . '/report.txt' ?>';
if(ids == 0){
return;
}
$('.' + loading_icon_small).show();
var data = {
action: 'ss_professional_ajax',
security: '<?php echo $ajax_nonce; ?>',
reprocessing_action: $('input:radio[name=ss_reprocessing_action]:checked').val(),
ids: ids,
};
var completed = 0;
$.post(ajaxurl, data, function (response) {
$('.' + loading_icon_small).hide();
completed = 1;
});
var get_update = function(){
$.getJSON(status_location, function (data) {
var update = '<ul><li><strong>'+data['title']+'</strong></li><li><strong>Count:</strong> '+data['count']+' / '+data['total']+'</li><li><strong>Last processed</strong>: Image # '+data['last_id']+'</li></ul>';
$('#ss-reprocessing-results').html(update).delay(1000);
});
if(completed == 1){
clearInterval(timed_requests)
return false;
}
};
var interval = 1000; // every 1 second
var timed_requests = setInterval(get_update, interval);
});
Trying to create an AJAX IM for my site...
need to load the part of page when row is inserted into mysql DB ... can anybody help me with this.. thanks in advance
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
var waittime=2000;
var intUpdate = null;
function verifDB(){
$.ajax({
type: "POST",
url: "verifdb.php",
success: function(msg){
alert(msg),;
}
});
intUpdate = setTimeout("verifDB()", waittime);
}
verifDB();
</script>
verifdb.php file is queried every 2000 ms to check on the database
you can put your file in requette verifdb.php
and you will have the answer in the variable msg
Client Side
For assyncronous requests on the client side you can use JQuery or plain Javascript XMLHTTPRequest
Server Side
I know you've specified PHP but I would recommend you to check how google channels work and make a similar implementation in PHP.
Since checking having multiple users checking for updates on the database, I would recommend you to use memcache.
Something like:
$script_called_time = time();
while($memcache->get('last_message') < $script_called_time){
usleep(100);
}
$result = $database->query("SELECT * FROM `messages` WHERE `date` > " . $script_called_time . "'");
...
This way the connection will be established and the user will receive a response when there's any...
(function() {
var chat = {
messageToSend: "",
messageResponses: [
"I Love You",
"I Wants to Kiss You.",
'Hug Me!"',
"Lets Sleep Together",
"Lets go for a date",
"Will you be physical with me?"
],
init: function() {
this.cacheDOM();
this.bindEvents();
this.render();
},
cacheDOM: function() {
this.$chatHistory = $(".chat-history");
this.$button = $("button");
this.$textarea = $("#message-to-send");
this.$chatHistoryList = this.$chatHistory.find("ul");
},
bindEvents: function() {
this.$button.on("click", this.addMessage.bind(this));
this.$textarea.on("keyup", this.addMessageEnter.bind(this));
},
render: function() {
this.scrollToBottom();
if (this.messageToSend.trim() !== "") {
var template = Handlebars.compile($("#message-template").html());
var context = {
messageOutput: this.messageToSend,
time: this.getCurrentTime()
};
this.$chatHistoryList.append(template(context));
this.scrollToBottom();
this.$textarea.val("");
// responses
var templateResponse = Handlebars.compile(
$("#message-response-template").html()
);
var contextResponse = {
response: this.getRandomItem(this.messageResponses),
time: this.getCurrentTime()
};
setTimeout(
function() {
this.$chatHistoryList.append(templateResponse(contextResponse));
this.scrollToBottom();
}.bind(this),
1500
);
}
},
addMessage: function() {
this.messageToSend = this.$textarea.val();
this.render();
},
addMessageEnter: function(event) {
// enter was pressed
if (event.keyCode === 13) {
this.addMessage();
}
},
scrollToBottom: function() {
this.$chatHistory.scrollTop(this.$chatHistory[0].scrollHeight);
},
getCurrentTime: function() {
return new Date()
.toLocaleTimeString()
.replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3");
},
getRandomItem: function(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
};
chat.init();
var searchFilter = {
options: { valueNames: ["name"] },
init: function() {
var userList = new List("people-list", this.options);
var noItems = $('<li id="no-items-found">No items found</li>');
userList.on("updated", function(list) {
if (list.matchingItems.length === 0) {
$(list.list).append(noItems);
} else {
noItems.detach();
}
});
}
};
searchFilter.init();
})();
Messenger Using Jquery And PHP
If you needs any help regarding this answer feel free to contact me at pachauriashokkumar[at]gmail[dot]com if you need complete code with css JS and HTML Drop me an email i will email the code to you
External Files are needed
https://code.jquery.com/jquery-3.4.1.js
https://cdn.jsdelivr.net/npm/handlebars#latest/dist/handlebars.js
https://raw.githubusercontent.com/javve/list.js/v1.5.0/dist/list.min.js
Messenger Using JQuery And PHP Demo Is Here Also Author of This Post on PenCode is available for clarification over email pachauriashokkumar[at]gmail[dot]com