I'm trying to dynamically update text on a PHP page via AJAX. But, instead of the text coming through at different intervals, it all comes at once. Maybe this is the wrong approach.
index.html
<html>
<head>
<title>Please Update!</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$.post("hello.php", function(data){
var success = $("#update");
success.css("color", "green");
success.html("> \r " + data + ".");
});
});
</script>
</head>
<body>
<div id="update"></div>
</body>
</html>
hello.php
<?php
echo "Hello World\n";
sleep(1);
echo "\rFoobar\n";
sleep(1);
echo "\rBazboo\n";
?>
I'd like the text to overwrite itself after one second but it comes barreling down the pipe all at once. ;_;
Not sure about this, but it might help you to do...
in PHP
<?php
$result[] = "Hello World\n";
$result[] = "\rFoobar\n";
$result[] = "\rBazboo\n";
print_r($result);
?>
in Ajax result
$.post("hello.php", function(data){
for(let i = 0; i < data.length; i++) {
setTimeout(() => {
// your stuff to do is here by 1 second interval...
var success = $("#update");
success.css("color", "green");
success.html("> \r " + data[i] + ".");
}, 1000*i);
}
});
Simple Representation
var data = ["Hello World\n","\rFoobar\n","\rBazboo\n"];
for(let i = 0; i < data.length; i++) {
setTimeout(() => {
console.log(data[i]);
}, 1000*i);
}
Like Antony suggested. You could create an array in php and encode it as Json
and then create a settimeout().
php
$data = array("Hello World","Foobar","BazBoo");
echo json_encode($data);
jQuery ~ JavaScript
$.ajax({
method: "GET",
url: "hello.php",
success: (res) => {
for (let i = 0; i < res.length; i++) {
setTimeout(() => {
// or use .html(res[i])
$("#update").text(res[i] + "<br>");
}, 1000 * i);
}
}
})
Related
I am having trouble getting the success call to fire in my ajax request. I know the communication is working fine, but the last call in my PHP script, which is a return json_encode($array); will fire as if it is a part of the onprogress object. I would like to "break" the onprogress call and run the success function on the last data sent via return json_encode when the PHP script has terminated...
Here is my AJAX call:
$( document ).ready(function(e) {
var jsonResponse = '', lastResponseLen = false;
$("#btn_search").click(function(e){
var firstname = document.getElementById('firstname').value;
var lastname = document.getElementById('lastname').value;
$.ajax({
type: "POST",
url: 'search.php',
data: $('#search_fields').serialize(),
dataType: "json",
xhrFields: {
onprogress: function(e) {
var thisResponse, response = e.currentTarget.response;
if(lastResponseLen === false) {
thisResponse = response;
lastResponseLen = response.length;
} else {
thisResponse = response.substring(lastResponseLen);
lastResponseLen = response.length;
}
jsonResponse = JSON.parse(thisResponse);
document.getElementById('progress').innerHTML = 'Progress: '+jsonResponse.msg;
}
},
success: function(data) {
console.log('done!');
document.getElementById('progress').innerHTML = 'Complete!';
document.getElementById('results').innerHTML = data;
}
});
e.preventDefault();
});
});
And here is the basic PHP server script:
<?php
function progress_msg($progress, $message){
echo json_encode(array('progress' => $progress, 'msg' => $message));
flush();
ob_flush();
}
$array = array('msg' => 'hello world');
$count = 0;
while($count < 100){
progress_message($count, "working....");
$count += 10;
sleep(2);
}
return json_encode($array);
?>
I made your code work, there were 2 errors. First, in your while loop, your function name is incorrect, try this:
progress_msg($count, "working... ." . $count . "%");
Secondly, the very last line outputs nothing, so technically you don't get a "successful" json return. Change the last line of your server script from:
return json_encode($array);
to:
echo json_encode($array);
UPDATE: Full working code with hacky solution:
Ajax:
$( document ).ready(function(e) {
var jsonResponse = '', lastResponseLen = false;
$("#btn_search").click(function(e){
var firstname = document.getElementById('firstname').value;
var lastname = document.getElementById('lastname').value;
$.ajax({
type: "POST",
url: 'search.php',
data: $('#search_fields').serialize(),
xhrFields: {
onprogress: function(e) {
var thisResponse, response = e.currentTarget.response;
if(lastResponseLen === false) {
thisResponse = response;
lastResponseLen = response.length;
} else {
thisResponse = response.substring(lastResponseLen);
lastResponseLen = response.length;
}
jsonResponse = JSON.parse(thisResponse);
document.getElementById('progress').innerHTML = 'Progress: '+jsonResponse.msg;
}
},
success: function(data) {
console.log('done!');
dataObjects = data.split("{");
finalResult = "{" + dataObjects[dataObjects.length - 1];
jsonResponse = JSON.parse(finalResult);
document.getElementById('progress').innerHTML = 'Complete!';
document.getElementById('results').innerHTML = jsonResponse.msg;
}
});
e.preventDefault();
});
Search.php:
<?php
function progress_msg($progress, $message){
echo json_encode(array('progress' => $progress, 'msg' => $message));
flush();
ob_flush();
}
$array = array('msg' => 'hello world');
$count = 0;
while($count <= 100){
progress_msg($count, "working... " . $count . "%");
$count += 10;
sleep(1);
}
ob_flush();
flush();
ob_end_clean();
echo json_encode($array);
?>
The problem with the "success" method of the ajax call was that it couldn't interpret the returning data as JSON, since the full return was:
{"progress":0,"msg":"working... 0%"}{"progress":10,"msg":"working... 10%"}{"progress":20,"msg":"working... 20%"}{"progress":30,"msg":"working... 30%"}{"progress":40,"msg":"working... 40%"}{"progress":50,"msg":"working... 50%"}{"progress":60,"msg":"working... 60%"}{"progress":70,"msg":"working... 70%"}{"progress":80,"msg":"working... 80%"}{"progress":90,"msg":"working... 90%"}{"progress":100,"msg":"working... 100%"}{"msg":"hello world"}
Which is not a valid JSON object, but multipje JSON objects one after another.
I tried removing all previous output with ob_end_clean(); , but for some reason I can't figure out, it didn't work on my setup. So instead, the hacky solution I came up with was to not treat the return as JSON (by removing the dataType parameter from the AJAX call), and simply split out the final Json element with string operations...
There has got to be a simpler solution to this, but without the use of a third party jQuery library for XHR and Ajax, I couldn't find any.
I have been at this some time trying to get highcharts to chart some data returned by php. I have done many searches and nothing works. I can write the php to deliver the data however it needs to be but how do you get it to dynamically chart it?????
I can deliver it as:
[["1372875867","44.8782806"],["1372875885","46.2020226"]]
or
[[1372876686,44.0655823],[1372876693,43.3360596], etc ]
but how do I get the data from the php output into the dyname example they display?????
!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highstock Example</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
Highcharts.setOptions({
global : {
useUTC : false
}
});
// Create the chart
window.chart = new Highcharts.StockChart({
chart : {
renderTo : 'container',
events : {
load : function() {
// set up the updating of the chart eachsecond
var series = this.series[0];
setInterval(function() {
var x = (new Date()).getTime(),
y = Math.round(Math.random() * 100);
series.addPoint([x, y], true, true);
}, 1000);
}
}
},
rangeSelector: {
buttons: [{
count: 1,
type: 'minute',
text: '1M'
}, {
count: 5,
type: 'minute',
text: '5M'
}, {
type: 'all',
text: 'All'
}],
inputEnabled: false,
selected: 0
},
title : {
text : 'Live random data'
},
exporting: {
enabled: false
},
series : [{
name : 'Random data',
data : (function() {
// generate an array of random data
var data = [], time = (new Date()).getTime(), i;
for( i = -999; i <= 0; i++) {
data.push([
time + i * 1000,
Math.round(Math.random() * 100)
]);
}
return data;
})()
}]
});
});
</script>
</head>
<body>
<script src="../../js/highstock.js"></script>
<script src="../../js/modules/exporting.js"></script>
<div id="container" style="height: 500px; min-width: 500px"></div>
</body>
</html>
my current php is:
<?php
// include("$_SERVER[DOCUMENT_ROOT]/config/config.php");
include("adodb5/adodb.inc.php");
$connection = new COM("ADODB.Connection") or die("Cannot start ADO");
$result_set = $connection->Execute("
SELECT tag, TIME, value
FROM picomp
WHERE TIME >= '*-3m' AND tag = 'xxx:xx_xxx.xxx'
");
$result_count = 0;
// $labels = array();
while (!$result_set->EOF) {
$pidate = date("U", strtotime($result_set->fields[1]) );
if ($result_count <> 0){
print ",";
}else{
print "[";
}
print "[".$pidate.",".$result_set->fields[2]."]";
// array_push("{$result_set->fields[2]}");
$result_count = $result_count +1;
$result_set->MoveNext();
// echo "testing";
}
print "];";
You can use HighchartsPHP which is a wrapper for Highcharts, which basically allows you to write all that JS code in PHP. It's very useful and pretty simple to use.
HighchartsPHP on GitHub
Your timestamp should be multiplied by 1000, and both values should be numbers.
Please familair with soultion, how to prepare JSON, because you only print "as JSON", but it is not.
Take look at http://php.net/manual/en/function.json-encode.php where some examples are introduced.
I am attempting to code the following script using jquery / ajax / php.
What happens is the php pulls all the records from the database and puts them into a select dropdown. When I select an item from the dropdown ajax pulls the price from the database and adds it into the span called priceeach1 . Well thats what its supposed to do, but my jquery is useless :-S .
The stockID comes from the select box value.
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#stock1').on('change', function (){
var newValue1 = $.getJSON('select2.php', {stockID: $(this).val()}, function(data){
var options = '';
for (var x = 0; x < data.length; x++) {
options += data[x]['priceeach'];
}
$('#priceeach1').text( options);
});
});
});
</script>
The HTML :
Price Each : £<span id="priceeach1"></span>
The select2.php :
<?php include 'connectmysqli.php'; ?>
<?php
$id = $_GET['stockID'];
$sql = 'SELECT * FROM stock WHERE stockID = ' . (int)$id;
$result = $db->query($sql);
$json = array();
while ($row = $result->fetch_assoc()) {
$json[] = array(
'priceeach' => $row['priceeach'],
);
}
echo json_encode($json);
?>
EDIT >> Ok I have now updated the code with the latest edits, this now WORKS.....apart from an odd problem......If I select the first or last item in the list no price is displayed, anything in between appears just fine..........
Try this,
var options = [];
for (var x = 0; x < data.length; x++) {
options = data[x]['priceeach'];
}
$('#priceeach1').text(options.join(','));
It should be like this you have to store price in the array options[] instead of option and then join them by any separator
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#stock').on('change', function (){
var newValue1 = $.getJSON('select2.php', {stockID: $(this).val()}, function(data){
var options = '';
for (var x = 0; x < data.length; x++) {
options[x] = data[x]['priceeach'];
}
$('#priceeach1').text(options.join(','));
});
});
});
</script>
You have to parse your JSON data to actual JSON Object before iterating it.
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#stock').on('change', function (){
var newValue1 = $.getJSON('select2.php', {stockID: $(this).val()}, function(data){
var jsonParsed = JSON.parse(data);
var options = '';
for (var x = 0; x < jsonParsed.length; x++) {
options[] = jsonParsed[x]['priceeach'];
}
$('#priceeach1').text(options.join(','));
});
});
});
</script>
Try to use this snipt:
for (var x = 0; x < data.length; x++) {
options += data[x]['priceeach'];
}
$('#priceeach1').text( options);
How to pass my php array to this jquery code ?
i have tried json_encoding but couldnt use it in my jquery function.
my json string looks like this:
{"1":{"id":"1","league":"england","team1":"Arsenal","team2":"Chelsea"},"2":{"id":"2","league":"spain","team1":"Deportivo","team2":"Real Madrid"}}
JS:
<script type="text/javascript">
$(document).ready(function(){
var shownIds = new Array();
setInterval(function(){
$.get('livescore_process.php', function(data){
for(i = 0; i < data.length; i++){
if($.inArray(data[i]["id"], shownIds) == -1){
if(data[i]["league"]=="england"){
$("#eng").append("id: " + data[i]["team1"] + " [ "+data[i]["team1"]+ " - "+data[i]["team1"]+" ]"+ data[i]["team2"] +"<br />");
}
shownIds.push(data[i]["id"]);
}
}
});
}, 3000);
});
</script>
try $.getJSON instead of $.get and use php json_encode:
$.getJSON('livescore_process.php', function(data){...
however the response data is not an array but a json object, so to handle it you can try:
$.each(data, function (index, item) {
if (item.hasOwnProperty('id')) {
if (item.league == "england") {
$("#eng").append("id: " + item.team1 + " [ " + item.team1 + " - " + item.team1 + " ]" + item.team2 + "<br />");
}
shownIds.push(item.id);
}
});
jsfiddle
I thought I solved the issue in a preceding question but it is sill not working. I want to change the php variables ($start and $end called by var b1 and var b2) if the admin clicks on button. After this the new code should be availble for every visitor, so it should make a server request. Here is my updated code:
<?php
if(date('w') == 4){ // day 2 = Tuesday
$start = strtotime('9:30');
$end = strtotime('12:30');
$timenow = date('U');
if ($timenow >= $start && $timenow <= $end) {
echo'<div id="iar_eu">';
echo quick_chat(200, 'default', 1, 'left', 0, 0, 1, 1, 1);
echo'</div>';
} }
?>
</div>
<?php if ( is_user_logged_in() ) { ?>
<input type="submit" value="Start Chat" id="start_chat" style="position: absolute; top: 30px; left: 10px;" />
<?php
} ?>
<script type="text/javascript">
if(jQuery('#start_chat').data('clicked')) {
// change var b1 and b2
$.ajax({
type: "POST",
url: "/web/htdocs/www.fattorefamiglia.com/home/wp-content/themes/child_care_creative/chat.php",
dataType: 'json',
data: { b1: "1:00", b2: "23:00" }
}).done(function(data) {
b1 = data.b1;
b2 = data.b2;
});}
else {
$.ajax({
type: "POST",
url: "/web/htdocs/www.fattorefamiglia.com/home/wp-content/themes/child_care_creative/chat.php",
dataType: 'json',
data: { b1: "9:00", b2: "18:00" }
}).done(function(data) {
b1 = data.b1;
b2 = data.b2;
});}
jQuery('#start_chat').click(function(){
$(this).data('clicked', true);
var b1 = '<?php echo $start; ?>';
var b2 = '<?php echo $end; ?>';
});
</script>
chat.php:
<?php
// variables
if (!empty($_POST)) {
$data['b1'] = $_POST['b1'];
$data['b2'] = $_POST['b2'];
}
// to not lose them
$_SESSION['chat'] = $data;
// to keep it compatible with your old code
$start = $data['b1'];
$end = $data['b2'];
// send the JSON formatted output
echo json_encode($data);
?>
Nothing happens when I click the button. What am I doing wrong?
There is a problem with the way jQuery is being used. All jQuery references should be made in functions that are only called after the page is ready, or in a wrapper that makes sure the page is ready.
For example, this code needs to be wrapped:
jQuery('#start_chat').click(function(){
$(this).data('clicked', true);
var b1 = '<?php echo $start; ?>';
var b2 = '<?php echo $end; ?>';
});
Like this:
jQuery(function(){
jQuery('#start_chat').click(function(){
$(this).data('clicked', true);
var b1 = '<?php echo $start; ?>'
var b2 = '<?php echo $end; ?>';
});
});
Setting the .data() isn't going to do you any good here. You're setting some info to the actual var instead of the element because of the way that method works.
But there's another problem with the way you're deciding to make AJAX requests, simply putting an if statement there won't make it happen. You would need a listener to make an action actually happen. But rather than get into that why don't you just simplify and do it like this?
<script type="text/javascript">
var b1 = '<?= $start ?>', b2 = '<?= $end ?>';
$(function(){
$('#start_chat').click(function(){
$.post('/web/htdocs/www.fattorefamiglia.com/home/wp-content/themes/child_care_creative/chat.php', { b1: '1:00', b2: '23:00' },
function(data) {
b1 = data.b1;
b2 = data.b2;
}, 'json');
});
});
</script>
This line
if(jQuery('#start_chat').data('clicked')) {
will never be true since .data('clicked') is not set until #start_chat is clicked which always will happen after the check has been made.
You need to rethink your process of what you want to accomplish.