Complete rewrite of my question
The task I am trying to do is update the display of five variable without reloading the whole page.
I have a php file (check_conf_update.php) which runs a query that produces data and I am scripting it into JSON.
In the PHP file that runs the query I have at the end:
echo json_encode($record);
The JSON result looks like this:
[{"ClientName":"Another","RoomFromDateTime":"2016-02-25 01:00:00","RoomToDateTime":"2016-03-13 23:00:00","ClientImageName":"anothernew.png","DisplayText":"System Testing"}]
I now need to use the data on a page called "template.php). How can I read the data from the Json result and assign each of the result elements in variables I can use on my "template.php" page. I need the Json script to run every x seconds so the display is always shows up todate information.
I have five php variables:
$CientName
$ImageName
$DisplayText
$FromTime
$ToTime
which I use on my web page to display the data on the same page as the script below.
$(document).ready(function() {
function runupdate() {
$.ajax({
url: 'check_conf_update.php',
type: 'GET',
data: 'record',
dataType: 'json',
success: function(data){
// not sure what I need to do here
}
});
};
// run it initially
runupdate();
// run it every 30 seconds
setInterval(runupdate, 30 * 1000);
});
Sorry if have confused anyone, and it looks like I did.
Can anyone help. Many thanks in advance for your time.
Regards
It's not really clear on what happens in your PHP script that produces the data. If you can update the post with the complete code for PHP also, it would be helpful. However, I'm assuming you want to use the data in the produced json string to populate the PHP variables in the destination file (check_conf_update.php)? In this case,
// check_conf_update.php
// $_POST['record'] == '[{"ClientName":"Another","RoomFromDateTime":"2016-02-25 01:00:00","RoomToDateTime":"2016-03-13 23:00:00","ClientImageName":"anothernew.png","DisplayText":"System Testing"}]'
$json = $_POST['record'];
$array = json_decode($json, true)[0];
$ClientName = $array['ClientName'];
$ImageName = $array['ClientImageName'];
$DisplayText = $array['DisplayText'];
$FromTime = $array['RoomFromDateTime'];
$ToTime = $array['RoomToDateTime'];
echo $ClientName . ', ' . $ImageName . ', ' . $DisplayText . ', ' . $FromTime . ', ' . $ToTime;
Edit:
All the PHP code in the template.php file is run on the server side before its rendered in the browser, so it will be too late to assign the updated json data into PHP variables by then. The only way to update information without reloading the page is to replace text or elements with javascript. After each successful ajax request, you can update the values in the page,
$('.clientname').html(data[0].ClientName);
$('.childbox').html(data[0].ClientImageName);
$('.clientndisplaytext').html(data[0].DisplayText);
$('.clientndisplaytime').html(data[0].RoomFromDateTime);
$('.clientndisplaytime').html(data[0].RoomToDateTime);
Related
I am making a WordPress template, mytemp.php in wordpress 3.9. In this I can use wordpress functions. For example, below works perfectly.
$(document).ready(function() {
alert(<?php echo get_current_user_id() ?>);
}
However, this template file calls some ajax scripts too depending on user input. Over there it doesn't work. For example, below statement returns fatal error "call to undefined function get_current_user_id"
$sql = 'SELECT x,y FROM table WHERE user_id = ' . get_current_user_id();
I am guessing, I need to tell the ajax script to include some wordpress file or some global variable but I am not sure how.
I solved it. All I needed to do was to have below include statement.
include '../../../../wp-load.php';
By including this, it started recognizing the function get_current_user_id()
Try to include wp-load.php file in ajax file, after including this file wordpress functions are working properly in your ajax file or you need to write a plugin like ajax.php, and then use this plugin file for your ajax file.
After that you can access the wp functions.
Hope it'll helps.
Try this. I just answered a question not too long ago with this style of sql syntax using the function get_current_user_id();
$sql = "SELECT x,y FROM table WHERE user_id = %d", get_current_user_id();
Another solution would be to establish a contract between your ajax script and the javascript that posts to it.
So, in your calling php script, you could set up some JSON in your header:
<script>
<?php echo "wp-data = {current_user_id: " . get_current_user_id() "}"; ?>
</script>
And then put it in your ajax call:
$.ajax({
url: "http://yourdomain.com/process_wp_ajax.php",
method: "post",
data: {
. . . //your post data
current_user_id: wp-data.current_user_id;
})
.success(function(response) {})
.fail(function(response) {} )
.complent(function(response, status) {};
Your receive should expect "current_user_id" to be on the POST (or GET).
This involves more work, but you save yourself from loading the WP framework each time you make an ajax call.
Don't use the php above if you want to set multiple values. Set an object instead and just call json_encode on it:
<?php
wp_object = (object) array('wp-val1' => wp_func1(), 'wp-val2' => wp_func2());
?>
<script>
<?php echo "wp-data =" . json_encode(wp_object) . ";"; ?>
</script>
DRY, just pass the wp-data object directly in your ajax:
$.ajax({
url: "http://yourdomain.com/process_wp_ajax.php",
method: "post",
data: {
. . .
wp-object: wp-data,
}
. . .
So in your calling script, you would eventuall arrive at:
$sql = "SELECT x,y FROM table WHERE user_id = %d", $_POST['current_user_id']
or `$_POST['wp-object']['current_user_id']
(of course you would set the $_POST value in a ternary prior to this right?
i want to fetch country source and destination from XML files , it works perfectly in localhost but not in server , in server it shows different destination country if i move cursor fastly on map.
in jquerymap.php I am calling price_by_countries.php file on mouseover and mouseclick event and I am also passing 2 variables in price_by_countries.php and in this file i am loading XML document , I think by loading XMLfile each and every time may cause this problem .. I am new to programming and wants to sort it out this issue asap .. thanks
jquerymap.php file code
jQuery.ajax({ type: "POST",
url: "price_by_countries.php",
data: "s="+source+"&d="+destination,
dataType: 'HTML',
success: function (msg) {
jQuery("#rightinput").html(msg);
}
});
price_by_countries file code
$xml = simplexml_load_file("rd.xml") or die("Error: Cannot create object");
function processXML($node){
foreach($node->children() as $books ){
if($books['source'] == trim(ucfirst($_REQUEST['s'])) &&
$books['destination'] == trim(ucfirst($_REQUEST['d'])))
{
echo "<pre>";
//echo $books ;
echo 'Source Country from XML file = '.$books['source'] . ' ------ Source Country from Textbox = '. trim(ucfirst($_REQUEST['s'])) ;
echo '<hr>';
echo 'Destination Country from XML file = '.$books['destination'] . ' ------ Destination Country from Textbox = '. trim(ucfirst($_REQUEST['d'])) ;
exit();
}
}
}
processXML($xml);
website url : http://realwebit.com/jquerymap/jquerymap.php
The problem seems to be bound to the datarequests on onmouseover. If you move the cursor too fast onmouseover triggers many requests at the same time to the server ! That works on localhost because there is no delay, but not ! You should install firebug for firefox and take a look at the requests made to the server.
If you dont want to load the xml every time you need a cache:
Save the response of the price_by_countries.php on the client side in an array using source & destination as keys !
If someone clicks or hovers over a country don't call the jquery ajax function right away. Check the array first if you already requested the data and return it ! If not do the ajax request. If it's successfull store the data in the array !
Lucian
Background Info
I'm fiddling around with some PHP and AJAX at the moment, to try and get the code working for an auto refreshing div (every 10 seconds), that contains comments.
Here is javascript code I am using to refresh the div..
<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('#content_main').load('/feed_main.php');
}, 5000);
});
// ]]></script>
The code that will populate the div called "content_main", which is in feed_main.php, essentially accesses the database and echo's out the latest comments ...
Question
Is it possible, to only load the div "content_main" if the data inside of it, hasn't changed since the last time it was loaded?
My logic
Because I'm relatively new to javascript and AJAX I don't quite know how to do this, but my logic is:
For the first time it is run..
load data from feed_main.php file
Create a unique value (perhaps a hash value? ) to identify say 3 unique comments
Every other time it is run...
load the data from feed_main.php file
create a NEW unique value
check this value with the previous one
if they're the same, don't refresh the div, just leave things as they are, but if they're different then refresh..
The reason why I want to do this is because the comments usually have pictures attached, and it is quite annoying to see the image reload every time.
Any help with this would be greatly appreciated.
I've faced similar problem not too long ago, i assume that you using mysql or something for your comments storage serverside ?
I solved my problem by first adding timestamp integer column to my mysql table, then when i added a new row, i'd just simply use time() to save the current time.
mysql row insert example:
$query = "INSERT INTO comments (name, text, timestamp) VALUES ('". $name ."', '". $text ."',". time() .");";
step two would be to json_encode the data you sending from serverside:
$output = array();
if ($html && $html !== '') { // do we have any script output ?
$output['payload'] = $html; // your current script output would go in this variable
}
$output['time'] = time(); // so we know when did we last check for payload update
$json = json_encode($output, ((int)JSON_NUMERIC_CHECK)); // jsonify the array
echo $json; // send it to the client
So, now instead of pure html, your serverside script returns something like this:
{
"payload":"<div class=\"name\">Derpin<\/div><div class=\"msg\">Foo Bar!<\/div>",
"time":1354167493
}
You can grab the data in javascript simply enough:
<script type="text/javascript"> // <![CDATA[
var lastcheck;
var content_main = $('#content_main');
pollTimer = setInterval(function() {
updateJson();
}, 10000);
function updateJson() {
var request = '/feed_main.php?timestamp='+ (lastcheck ? lastcheck : 0);
$.ajax({
url: request,
dataType: 'json',
async: false,
cache: false,
success: function(result) {
if (result.payload) { // new data
lastcheck = result.time; // update stored timestamp
content_main.html(result.payload + content_main.html()); // update html element
} else { // no new data, update only timestamp
lastcheck = result.time;
}
}
});
}
// ]]> </script>
that pretty much takes care of communication between server and client, now you just query your database something like this:
$timestamp = 0;
$where = '';
if (isset($_GET['timestamp'])) {
$timestamp = your_arg_sanitizer($_GET['timestamp']);
}
if ($timestamp) {
$where = ' WHERE timestamp >= '.$timestamp;
}
$query = 'SELECT * FROM comments'. $where .' ORDER BY timestamp DESC;';
The timestamps get passed back and forth, client always sending the timestamp returned by the server in previous query.
Your server only sends comments that were submitted since you checked last time, and you can prepend them to the end of the html like i did. (warning: i have not added any kind of sanity control to that, your comments could get extremely long)
Since you poll for new data every 10 seconds you might want to consider sending pure data across the ajax call to save substantial chunk bandwidth (json string with just timestamp in it, is only around 20 bytes).
You can then use javascript to generate the html, it also has the advantage of offloading lot of the work from your server to the client :). You will also get much finer control over how many comments you want to display at once.
I've made some fairly large assumptions, you will have to modify the code to suit your needs. If you use my code, and your cat|computer|house happens to explode, you get to keep all the pieces :)
How about this:
<script type="text/javascript">
// <![CDATA[
$(function () {
function reload (elem, interval) {
var $elem = $(elem);
// grab the original html
var $original = $elem.html();
$.ajax({
cache : false,
url : '/feed_main.php',
type : 'get',
success : function (data) {
// compare the result to the original
if ($original == data) {
// just start the timer if the data is the same
setTimeout(function () {
reload(elem, interval)
}, interval);
return;
}
// or update the html with new data
$elem.html(data);
// and start the timer
setTimeout(function () {
reload(elem, interval)
}, interval);
}
});
}
// call it the first time
reload('#content_main', 10000);
});
// ]]>
</script>
This is just an idea to get you going it doesn't deal with errors or timeouts.
Best And Easy Code
setInterval(function()
{
$.ajax({
type:"post",
url:"uourpage.php",
datatype:"html",
success:function(data)
{
$("#div").html(data);
}
});
}, 5000);//time in milliseconds
I'm having a little trouble with retrieving some JSON data from a field stored in my website's cache. The script I'm writing fetches the latest tweets from a twitter list, stores the JSON data it receives in a .txt file in the cache of the website. This is then read and turned into a string displaying the tweet, or at least it should. I have it working when I don't cache the tweets and just access them directly, but as soon as I try to cache the tweets then access them from cache I'm hitting a wall. The cache-tweets.php file is run as a cron job on the server, and works fine, it creates a text file that contains the JSON data no problems. The code for cache-tweets.php is below.
$cache = dirname(__FILE__) . '/cache/twitter-json.txt';
$data = file_get_contents('https://api.twitter.com/1/lists/statuses.json?slug=tab&owner_screen_name=swoophoop&per_page=15&page=1&include_entities=true');
$cachefile = fopen($cache, 'wb');
fwrite($cachefile,utf8_encode($data));
fclose($cachefile);
This should then be used by this code:
<script type ="text/javascript">
$(document).ready(function(){
$.ajax({
dataType: 'json',
url: 'http://sotontab.co.uk/wp-content/cache/twitter-json.txt',
success: function (data) {
var strTweet = '';
$.each(data, function(index, tweet){
var user_link = '\x3Ca href="http://twitter.com/' + tweet.user.screen_name + '">' + '\x3Cb>' + tweet.user.name + '\x3C/b>\x3C/a>';
strTweet=strTweet + user_link + ' :  ' + tweet.text.linkify() + ' ' + '\x3Cdiv class="time">' + relative_time(tweet.created_at) + '\x3C/div>   ';
});
tweetMarquee = new Marquee($('div#marquee'),strTweet,$('div#marquee').width);
}
});
});
</script>
If I replace the url in the above code with the url from cahe-tweets.php it works perfectly and the tweets display inside the marquee on my site. But if I run it as it is, nothing appears. The marquee doesn't even show up as empty. Does anyone know why it doesn't work with the site url as above?
One thing you could try is mark the dataType as text and then do data = JSON.parse(data); and sees if it works. Alternatively it might work if you save the file with a json suffix instead of as a text file.
Ok so I'm experimenting with the in HTML5 and have made a simple "paint" application in Javascript to draw where the user's mouse is on the screen. Works fine.
I then wanted to save the coordinates to a file. My program already had an array of the x coordinates and an array of the y coordinates from the Javascript code.
When the user presses a button, the onClick calls a function in the Javascript, which using jQuery, as in the Top Answer here How to get JavaScript function data into a PHP variable attempts to pass this into a php file to save.
However it isn't working. Should I be passing the data back into the original php document that contains the canvas? If so how do I then get it to do the code to save as the PHP is run when the document is loaded no?
CODE:
Ok this is in the original php file which contains the HTMl for the webpage including the canvas. Here's the relevant save button:
<button type="button" onclick="saveDrawing()" id="saveButton">Save</button>
This calls the following in a separate JS file
function saveDrawing(){
// First check that not drawing and have data
if (!readyToDraw && clickX!=null){
// If ready then pass back to the PHP file the data
$url = 'file_save_test.php';
$.get($url, {x_coords: getXCoords(), y_coords: getYCoords()});
}
else {
alert("Please add some coordinate points and press Finish before saving");
}
}
and file_save_test.php contains only the following
<?php
// retrieve data from the JS
$buffer_data['x_coords'] = $_GET['x_coords'];
$buffer_data['y_coords'] = $_GET['y_coords'];
$x_s = $_GET['x_coords'];
$y_s = $_GET['y_coords'];
// first want to open a file
$file_name = "data_test.txt";
$file_handler = fopen($file_name, 'w');
// now to loop through arrays and write!
/*for ($i = 0; $i < sizeof($x_s); i++){
fwrite($file_handler, "$x_s[i], ");
fwrite($file_handler, "$y_s[i]\n");
} */
fclose($file_handler);
?>
In your PHP file it looks like your fwrite code is commented out. Are you expecting it to write to that data_test.txt file? Try changing your PHP file to print the results and have it echoed back to your javascript to see if the data is getting communicated properly.
$.get($url, {x_coords: getXCoords(), y_coords: getYCoords()},
function(data){
alert("Data Loaded: " + data);
});
PHP
print_r($_GET);
EDIT
Change your PHP file to something like this if it's alerting the data properly (it should append the coords to your file):
<?php
// retrieve data from the JS
$x_s = $_GET['x_coords'];
$y_s = $_GET['y_coords'];
$file_name = "data_test.txt";
$file_handler = fopen($file_name, 'a');
fwrite($file_handler, "$x_s, $y_s \n");
fclose($file_handler);
?>
EDIT 2
Update your for loop to your original code
for ($i = 0; $i < count($x_s); $i++){
fwrite($file_handler, $x_s[$i] . ", ". $y_s[$i] . "\n");
}
What I would do is have your save button call jQuery's $.post() method. Post the data to another PHP file that either inserts it into a database or saves it as a file. I don't recommend using the original document to post the data to because the client would have to download the entire DOM and the server would run any other code that you don't need.
That's as much as I can really help you without seeing any of your code.
I would send the data into a new php script called saveCoords.php or something..
You say you already have the coordinates in a JavaScript array, so it would look something like this...
//JAVASCRIPT FUNCTION which will request php file to store info
function storeCoords(xCoordArray, yCoordArray){
var xCoords = JSON.stringify(xCoordArray);
var yCoords = JSON.stringigy(yCoordArray);
var request = new XMLttpRequest(); //will need to change for older ie
request.onreadystatechange = function(){
//functions to handle returning information from php file..
}
request.open("GET","saveCoords.php?xCoords="+xCoords+"&yCoords="+yCoords, true);
request.send();
}
And then saveCoords.php file would look something like this:
<?php
$xCoords = json_decode($_GET['xCoords']);
$yCoords = json_decode($_GET['yCoords']);
//now you have a php array of xCoords and yCoords, which you can store
?>
Thats a skeleton but I think it hits on the major points, but comment with any questions.