retrieve value from mysql database with php/javascript in refreshing window - javascript

i have script that works as follows:
there is main page with 'start' button that initializes javascript function which loads a php page into a div frame, then via setTimeout it calls a 'refresh' function thats supposed to work indefinitelly and refresh the page inside frame
the refreesh timer is in database and is forwarded to java like this:
var min_refresh_time = ;
$min_refresh_time_sec is taken from database earlier in the code
what i wanted to modify is so the refresh min_refresh_time would be taken each time a refresh function is run, to my surprise this worked (or at least i thought so):
var min_refresh_time = ;
(custom sql functions are defined in separate php file included in main.php which is my main page)
unfortunatelly it seems that it 'worked' only due to some strange caching on java part and my pseudo-php code to take value from database is just a hoax - it looks like it is run only initially and then stores output somehow
simplified code of what is done and what i want to do:
function refresh_code(){
refresh_time = <?php Print(sql_result(sql_execute("SELECT value FROM settings WHERE setting='min_refresh_time'", $connection), 0, 0)); ?>;
refresh_time = 5;
alert(refresh_time);
$.post("index.php",{refresh_time:refresh_time_post, account_group: "1"},
function(data)
{
$.ajaxSetup ({
cache: false,
});
$("#frame_1").html(data);
});
setTimeout(function(){refresh_code()}, refresh_time);}
lets say min_refresh_time is 1 in database, i run it, it alerts 1 then 5 each time it self-refreshes, now if i go to database and change 1 to 3 i would want it to alert 3 then 5 obvious, it still does 1 then 5 tho...
i need a way to execute a dummy php file that only takes value from database, then sends it via post back to java and it gets intercepted there, any simple way to do that?
or do i need to use entirely different method for retrieving database value without js...
thx in advance
update:
i actually came back to it and analyzed potential solutions with fresh mind
first of all, i dont think my initial code had chance to work, java cant execute serverside code by itself, i took some of my aax code from other script and reworked it to launch php file that grabs the value from database, then i intercept output data and put into variable
looks like that:
$.ajax({
method: "POST",
url: "retrieve_refresh.php",
data: { retrieve_data: "max"},
cache: false,
timeout: 5000,
async: false,
cache: false,
error: function(){
return true;
},
success: function(msg){
if (parseFloat(msg)){
return false;
}
else {
return true;
}
}
}).done(function(php_output2) {
max_refresh_time = php_output2;
});
retrieve_refresh.php returns only the variable i want but the solution is unelegant to say the least, i havent searched yet but could use a way of sending variables as post back to ajax...

Related

Auto Refresh PHP Function without reloading page Javascript / Ajax

Is it possible to use Ajax, Jquery or Javascript to call a specific PHP Function and refresh / reload it every 10 seconds for example inside a specific Div or areas?
Connection.php
function TerminalStatus ($IPAddress, $portStatus ) // Responsible for current terminal status
{
$connectStatus = fsockopen($IPAddress, $portStatus, $errno, $errstr, 10); // Build cconnection to Terminal socket 25001
if (!$connectStatus) {
echo "$errstr ($errno)<br />\n";
} else {
$Status = fgets($connectStatus) ;
echo $Status ();
}
}
This connection is just to see the current status of a terminal.
I want to see the status of this function at the bottom of my index.php without refreshing the whole page.
I can accomplish this by putting this function in its own PHP Files (status.php) and using Javascript in the following way:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#Status').load('status.php');
}, 1000); // refresh every 1000 milliseconds
</script>
But i just want to utilise the function instead.
Is this possible?
The solution you have already is the correct way to do this: the JavaScript fetches a URL, and that URL renders the appropriate piece of content.
It's important to remember that, as far as the web browser is concerned, PHP doesn't exist. Any request from the browser - whether you've typed in a URL, followed a link, submitted a form, made an AJAX request, etc - is just a message to some remote server for a particular URL, perhaps along with some extra headers and body data. When the server receives that request, it can do whatever it likes to generate a response to the browser.
So when you write $('#Status').load('status.php');, the browser is sending a request to the server, which happens to be configured to execute the PHP script status.php. You can then do what you like in PHP to produce the response - but there is no direct link between a request and a PHP function.
However, as others have pointed out, you don't have to create a new PHP file for every piece of behaviour you want, because inside the PHP code you can check things like:
the query string parameters, in $_GET
submitted form data, in $_POST
the HTTP headers from the request
These can be set by your JavaScript code to whatever you like, so you could for instance write $('#Status').load('index.php?view=statusonly'); and then at the top of index.php have code like this:
if ( $_GET['view'] === 'statusonly'] ) {
echo get_status();
exit;
}
How you arrange this is entirely up to you, and that's what programming is all about 🙂
That's impossible to do this operation just with the PHP function.
you should use javascript as you use that or use socket in javascript to connect you status.php and update without refresh the whole page.
I'm not sure if i understood the problem but you can use AJAX to execute specific function. Something like this:
First build your ajax:
$.ajax({
type: "POST",
url: "URL_TO_PHP_FILE",
data: "refreshStatus", // this will call the function
success: function(status){
$('#Status').text(status); // this will load the info you echo
},
});
Since you want to do it every second - wrap the whole thing with interval (i use your code from the question):
var auto_refresh = setInterval( function () {
$.ajax({
type: "POST",
url: "URL_TO_PHP_FILE",
data: "refreshStatus",
success: function(status){
$('#Status').text(status);
},
});
}, 1000);
Then, on you PHP_FILE add condition the execute the specific function when POST been done:
if ($_SERVER["REQUEST_METHOD"] == "POST" && $_POST['refreshStatus']) {
// run this code
}
Is that what you aimed to achieve?
jQuery::load() supports fragment identifiers. So you can just load the part that you want to replace:
$( "#Status" ).load( "status.php #PartId" );
This will load the HTML output of the script and extract the part. The PHP script will run completely - the rest of the HTML output will be thrown away on the JS side.

Javascript function onload to block other functions running

Is there a way in JavaScript where I can execute some functions only after page is loaded. Other functions should execute only on an event.
The problem is, I have some calculations in my php page and after doing all the calculations, the data is saved in mysql. Now when I come to the edit mode some functions are executing which makes the total field as NaN. I just want the code to take the total field from the db only not from any function. Hope l'm clear.
Fiddle
You can try like this:
Make an AJAX call to the server to get the count from Database when the user clicks on edit mode and avoid getting from the html document.
function JQueryGETAjaxCall(servletPath,callBck){
var path = window.location.origin
var url = path+servletPath;
console.log(url)
$.ajax({
'type':'GET',
'url':url,
'async': true,
'success':function(res){
callBck(res);
},
'error':function(res){
}
});
}

Ajax: live display of JSON file values too slow

I have a button on my site, that when pressed sets the corresponding value in an JSON file to either 0 or 1. A function is continuously running and updating the color of the button depending of the JSON file. This is needed so the button has the same state on all devices.
Now my Problem: It is slow. I want it to be instantly on at least the device the button is clicked. I tried it by setting the color at the same time as the JSON file is updated, but this is buggy since the Ajax call takes some time and the button sometimes flickers. I made the following test: Every time the getStatus() function was called it would add either 1 or 0 to a div. I noticed that after the JSON changed it would still print out the old state a few times before printing the correct one, eventhought i turned cache off
Is there a way to make it faster? Here is the code:
Inex.html:
function getStatus() {
$.ajax({
url: 'status.json',
dataType: 'json',
cache: 'false',
success: function(data) {
varstatus = data;
setColor();
getStatus();
}
})
}
Index.php
$jsonString = file_get_contents('status.json');
$data = json_decode($jsonString);
$data[$_GET['id']] = "$f";
$newJsonString = json_encode($data);
file_put_contents('status.json', $newJsonString);
Another problem I have is that the page is not alway working at the first time. I have to reload to make the updates show, but then it works without.
Or is there another way to do this, without continuously downloading the file?

Calling ajax from within js file on users browser

I have a bookmarklet which a user adds to their own browser bookmarks toolbar which collects images from a page they are looking at.
I want to log each time a user is clicking on any site and store the data in a mysql table. So i'm using an ajax call to post to a php file which processes the data sent to it.
However, this sometimes works and sometimes does not. Meaning, it works on some sites and not others.
What I'm trying is this:
(function()
{ // declare variables e.g. div.ids, div content etc then display it
......
//log the click
var dataString = '&url=' + encodeURIComponent(window.location.href) + '&page_title=' + encodeURIComponent(document.title);
$.ajax({
type: "POST", // form method
url: "http://myurl.com/includes/log_clicks.php",// destination
data: dataString,
cache: false
});
//END log the click
})();
When it doesn't work and i use Firebug to find out why, i sometimes get the error: TypeError: $ is undefined $.ajax({
Sometimes it still posts to the php file but with no data
Is there a better way to call ajax from within a js file on a user's browser?
As per suggestions, I've tried loading jquery by simply amending one of the variables like so:
div.innerHTML = '<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script><div class=....';
But that made no difference
You need jQuery present on the page in order to perform this. You will need to load jQuery if not present. A great approach is outlined here using the jQuerify code which actually just loads a portion of jQuery functionality that is needed.

Load .txt file using JQuery or Ajax

How can I fix the script below so that it will work EVERY TIME! Sometimes it works and sometimes it doesn't. Pro JQuery explains what causes this, but it doesn't talk about how to fix it. I am almost positive it has to do with the ajax ready state but I have no clue how to write it. The web shows about 99 different ways to write ajax and JQuery, its a bit overwhelming.
My goal is to create an HTML shell that can be filled with text from server based text files. For example: Let's say there is a text file on the server named AG and its contents is PF: PF-01, PF-02, PF-03, etc.. I want to pull this information and populate the HTML DOM before it is seen by the user. A was ##!#$*& golden with PHP, then found out my host has fopen() shut off. So here I am.
Thanks for you help.
JS - plantSeed.js
var pageExecute = {
fileContents:"Null",
pagePrefix:"Null",
slides:"Null",
init:function () {
$.ajax({
url: "./seeds/Ag.txt",
success: function (data){
pageExecute.fileContents = data;
}
});
}
};
HTML - HEAD
<script type="text/javascript">
pageExecute.init();
</script>
HTML - BODY
<script type="text/javascript"> alert(pageExecute.fileContents); </script>
Try this:
var pageExecute = {
fileContents:"Null",
pagePrefix:"Null",
slides:"Null",
init: function () {
$.ajax({
url: "./seeds/Ag.txt",
async: false,
success: function (data){
pageExecute.fileContents = data;
}
});
}
};
Try this:
HTML:
<div id="target"></div>
JavaScript:
$(function(){
$( "#target" ).load( "pathToYourFile" );
});
In my example, the div will be filled with the file contents. Take a look at jQuery .load() function.
The "pathToYourFile" cand be any resource that contains the data you want to be loaded. Take a look at the load method documentation for more information about how to use it.
Edit: Other examples to get the value to be manipulated
Using $.get() function:
$(function(){
$.get( "pathToYourFile", function( data ) {
var resourceContent = data; // can be a global variable too...
// process the content...
});
});
Using $.ajax() function:
$(function(){
$.ajax({
url: "pathToYourFile",
async: false, // asynchronous request? (synchronous requests are discouraged...)
cache: false, // with this, you can force the browser to not make cache of the retrieved data
dataType: "text", // jQuery will infer this, but you can set explicitly
success: function( data, textStatus, jqXHR ) {
var resourceContent = data; // can be a global variable too...
// process the content...
}
});
});
It is important to note that:
$(function(){
// code...
});
Is the same as:
$(document).ready(function(){
// code
});
And normally you need to use this syntax, since you would want that the DOM is ready to execute your JavaScript code.
Here's your issue:
You've got a script tag in the body, which is asking for the AJAX data.
Even if you were asking it to write the data to your shell, and not just spout it...
...that's your #1 issue.
Here's why:
AJAX is asynchronous.
Okay, we know that already, but what does that mean?
Well, it means that it's going to go to the server and ask for the file.
The server is going to go looking, and send it back. Then your computer is going to download the contents. When the contents are 100% downloaded, they'll be available to use.
...thing is...
Your program isn't waiting for that to happen.
It's telling the server to take its time, and in the meantime it's going to keep doing what it's doing, and it's not going to think about the contents again, until it gets a call from the server.
Well, browsers are really freakin' fast when it comes to rendering HTML.
Servers are really freakin' fast at serving static (plain-text/img/css/js) files, too.
So now you're in a race.
Which will happen first?
Will the server call back with the text, or will the browser hit the script tag that asks for the file contents?
Whichever one wins on that refresh is the one that will happen.
So how do you get around that?
Callbacks.
Callbacks are a different way of thinking.
In JavaScript, you perform a callback by giving the AJAX call a function to use, when the download is complete.
It'd be like calling somebody from a work-line, and saying: dial THIS extension to reach me, when you have an answer for me.
In jQuery, you'll use a parameter called "success" in the AJAX call.
Make success : function (data) { doSomething(data); } a part of that object that you're passing into the AJAX call.
When the file downloads, as soon as it downloads, jQuery will pass the results into the success function you gave it, which will do whatever it's made to do, or call whatever functions it was made to call.
Give it a try. It sure beats racing to see which downloads first.
I recommend not to use url: "./seeds/Ag.txt",, to target a file directly. Instead, use a server side script llike PHP to open the file and return the data, either in plane format or in JSON format.
You may find a tutorial to open files here: http://www.tizag.com/phpT/fileread.php

Categories

Resources