Auto Refresh PHP Function without reloading page Javascript / Ajax - javascript

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.

Related

JS redirect after setting a session var with AJAX

Been working on a project that requires me to perform a JS redirect to a page, by setting up a session variable in PHP via an AJAX query, and then checking to make sure the session is set. After a successful check, the redirect URL would then be constructed in JS and the redirection performed.
What I've got so far is:
<?php
$v_ip = $_SERVER['REMOTE_ADDR'];
$hash = md5($v_ip);
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$.ajax({
type : 'POST',
url : './session.php',
dataType: "json",
data: "<?php echo $hash; ?>",
success : function(data){},
error : function(){}
});
</script>
<script>
<?php
if(isset($_SESSION['allow'])) {
echo "var url = \"url-here/?token=\";
var token = \"token\";
var redirect = url.concat(token);";
}
?>
window.location.replace(redirect);
</script>
</head>
</html>
And the PHP code that sets the variable:
<?php
session_start();
$v_ip = $_SERVER['REMOTE_ADDR'];
$hash = md5($v_ip);
if(isset($_POST["$hash"])) {
$_SESSION['allow'] = true;
}
?>
On an initial visit to the page, everything is processed correctly and works up to the point of the actual redirect. The session variable is set, the JS code is correctly outputted in the code of the page, and for some weird reason, the actual window.location.replace function is not activated. The page just remains blank - upon inspection the source code displays everything correctly, and yet the redirect does not happen. If I visit the page one more time, the redirect is done fine.
If I change the name of the session variable in both files, and have to re-set it all over again, the same thing happens - upon initial visit the redirect is not processed, but clearly everything up until the actual redirect is processed correctly again.
Why is this happening?
The first time you go to the page, the session variable isn't set yet. So the if will fail, and the variable assignments won't be put into the <script>. The browser will then perform the AJAX call that sets the session variable, but it's too late to affect that original page, you have to go to the page again to see the effect of it.
Remember, all the PHP in the page is executed on the server first, the output is sent to the browser, then the JS is executed.
I suggest you put the code that performs the redirect into the success: function of $.ajax.
I think there are several things need to be manipulated.
First of all, php itself is a template engine. What does that mean? It means it will translate php script into html as possible as it can. so this block below will be translate into html and remain static.
<?php
if(isset($_SESSION['allow'])) {
echo "var url = \"url-here/?token=\";
var token = \"token\";
var redirect = url.concat(token);";
}
?>
That is, the redirect variable is determined before your Ajax call. That also can explain why the second time you visit the page the redirect work but not the first time.
Secondly, although you place Ajax related code before window.location.replace doesn't mean they will shoot in a desired order as you expect. That's because Ajax call is a async operation and you can't predict when you will get the response. In this situation I will put the window.location.replace thing into Ajax call successful callback like:
$.ajax({
type : 'POST',
url : './session.php',
dataType: "json",
data: "<?php echo $hash; ?>",
success : function(data){
window.location.replace(data.url)
},
error : function(){}
});
Third, you should detect isset($_SESSION['allow']) thing in server side and response in a JSON-like format:
{
url: desired_url
}
Hope this help. Good luck.

How do I reload a page without the user noticing?

I've been trying to figure out how to reload a page and pull dynamic info from a server without users noticing the page has been reloaded. For instance, if I want to create a 'live' message board system when the board updates every time other people make a comment or post a message.
I noticed that Javascript has a boolean function .reload() that when set to false reloads the page from the cache and when set to true reloads the page from the server, but from what it looks like, the function does something similar to reloading the browser. Is there another way do what I'm trying to do?
Something like this...
function getContent()
{
return new Promise(function(resolve, reject){
var url = "http://yourendpoint.ext"
$.ajax({
url: url,
success: function(data)
{
resolve(data);
},
error: function(err)
{
reject(err);
}
});
}));
}
// Usage
getContent()
.then(function(data)
{
$('#some-element').html(data);
});
Are you sure you really want to do an reload?
What you could do is make an AJAX Request to the server and display the result, without even reloading the Page. I would recommend using jQuery for this, just out of comfort.
AJAX stands for Asynchronous JavaScript and XML. In a simple way the process could be:
User displays page, a timer is started
Every 10s (or 20s or whatever) you do an AJAX Request using JavaScript, asking the server for new data. You can set a callback function that handles the result data.
Server answers with result data, your callback function inserts the new data.
Code Example (taken from jQuery Docs):
$.ajax({
method: "POST",
url: "target.php",
// Data to be sent to the server
data: { name: "John", location: "Boston" },
// success will be called if the request was successfull
success: function( result ) {
// Loop through each Element
$.each(result.newElements, function(index, value) {
// Insert the Element to your page
$('.classOfYourList').append(value);
}
});
});
Just set the proper endpoint of your server as the target and insert whatever you want to do in the success function. The function will get an answer containing whatever you sent to it from the server. More Information in the jQuery Documentation:
You can Achive what you want using AJAX. you can use ajax with either javascript or jquery. You can load the content you want dynamically without reloading the entire page. here is a quick example.
Here is a <div> with id load where your content will be loaded.
<div id="load">Loaded Content:</div>
<button id="load_more">load more</button>
JQuery to request for the data, where getdata.php is the php file which will send data you want to display.
<script type="text/javascript">
$(document).ready(function(){
$("#load_more").click(function (){
$.post("getdata.php", {variable1:yourvariable, variable2:ifneeded},function(data){
//data is the string or obj or array echoed from getdata.php file
$('#load').append(data); //putting the data into the loaded div.
}
});
});
});
</script>`
finally getdata.php file
<?php
//fetch data from Databas eif needed. or echo ut what you want to display in the div.
echo "This is a small example of using JQuery AJAX post request with PHP.";
?>
Hope that helps!

PHP print string in while loop

I have a function in file do.php like this:
<?php
if(isset($POST['submit']))
{
for($i=0;$i=10;$i++)
{
$reponse = array(
'content' = > "This is an example - process #" . $i;
);
echo json_encode($response);
sleep(1); // sleep one second each loop
}
}
?>
and I have some short JQUERY codes use ajax to post data...
<button onclick="post()">Submit</button>
function post()
{
$.ajax({
type: "POST",
url: "do.php",
data: data,
success: function (data){
var json = jQuery.parseJSON(data);
$('#result').html(json.content);
}
});
}
and this is the output...
This is an example - process #1
This is an example - process #2
This is an example - process #3
....
When I click on Submit button, I can see a request on firebug run 10 seconds to finish and show the result. Now I want each result showed line by line when it finish in the while loop. I can build a websocket system but this system take very much my times and to big system, I just need a simple way to do this if possible.
I still try to save output in to txt file and use JQUERY read it every 500ms but this way take too much request and it doesn't work well.
What are you trying to achieve ?
From what I understand you try to execute several processes in SERVER side, and you want, from CLIENT side, to query their status(which process is still running/finished...)
If so, IMO you can execute those processes(using fork() or whatever), and let the parent process to return a list of unique token identifier for each process, to your AJAX request.
Now for every 500ms, using setInterval(), query the of the tokens your received.
Hope it help a bit.

Javascript Variable passing to PHP with Ajax

I've started working with ajax a little lately, but I'm having trouble with something I feel is incredibly simple: storing a JS variable in PHP.
Say I want to store a zip code (assigned with Javascript) and pass that to a PHP variable via AJAX: Why doesn't this work?
Keeping it simple for demonstration purposes, but this is the functionality I desire..
zipCode.js:
$(document).ready(function() {
var zip = '123456';
$.ajax({
url: 'zip.php',
data: {zip_code:zip},
type: 'POST'
});
});
zip.php:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="zipcode.js"></script>
</head>
<body>
<?php
echo $_POST['zip_code'];
?>
</body>
</html>
An error: "Notice: Undefined index: zip_code" is all that is returned. Shouldn't "123456" be echo'd out?
You are supposed to put this:
<?php
// query database before echoing an associative array of `json_encode()`ed data if a response is needed
echo json_encode(array('zip_code' => $_POST['zip_code']);
?>
on a separate page, that is not an HTML page. AJAX just sends to that page, so you can use it and echo it out, making database queries before that, or what have you. Upon success you will see the result of your echo as the argument passed to the success method in this case if you used data as the argument the result for zip_code would be held in data.zip_code. Also, set your dataType:'JSON' in $.ajax({/*here*/}).
Here:
var zip = '123456';
$.ajax({
url: 'zip.php',
data: {zip_code:zip},
type: 'POST',
dataType: 'JSON',
success: function(data){
// in here is where you do stuff to your page
console.log(data.zip_code);
}
});
When you load the page, a call is being made to the server for zip.php, however that request is in no way linked to the page you're currently viewing.
If you look at the response to your ajax request - you'll see a copy of the page with the correct zip code echo'd
The actual answer then depends on what exactly you're trying to do (and a less simplified version of the code) to give you the best option.
The current setup you have doesn't make sense in practice
That is not how AJAX works. Thake a look at the example below. It will make an AJAX post to handle_zip.php and alert the results (Received ZIP code 123456)
start_page.html:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="zipcode.js"></script>
</head>
<body>
This is just a static page.
</body>
</html>
zipcode.js:
$(document).ready(function() {
var zip = '123456';
$.ajax({
url: 'handle_post.php',
data: {zip_code:zip},
type: 'POST',
success: handleData
});
});
}
function handleData(data) {
alert(data);
}
handle_post.php:
<?php
die ('Received ZIP code ' . $_POST['zip_code']);
As others have mentioned, it sounds like you're expecting the two bits of code to run at the same time. The reality is that:
zip.php will be parsed on the server (and resulting in the error)
Server will then serve up the HTML to the browser (which will have a blank body due to the $_POST not existing when the PHP was parsed)
browser will see the javascript .ready() and run that code
server will handle the POST request to zip.php, and generate the HTML you're expecting. It'll be returned in the AJAX response, but as you're not handling the response, nothing is shown in the current session. (you can see the POST response using any of the common web developer tools)
Remember, PHP runs on the server, then any javascript runs on the client. You're also missing the step of handling the response from the request you made in your javascript.
try this to give you better idea of what's happening.
$.ajax({
url: 'zip.php',
data: {zip_code:zip},
type: 'POST'
});.done(function(data ) {
console.log(data)
});
In your code, the server is creating the page first, so no javascript is run yet, therefore it creates an error because $_POST['zip_code'] doesn't exist. Then it sends this page to your browser and you can see that. At this point is when your browser executes the javascript, it sends the request again, now with POST data, the server should return the response of the request and you should be able to see it in the console.
You could make this 2 separate pages, one for viewing the page, and anotherone for processing the ajax request, or if for your application you want to do it in the same page, you would need an if statement to get rid of that error, something like
if(isset($_POST['zip_code'])){
echo $_POST['zip_code];
}

Ajax Call Confusion

before we start apologies for the wording and lack of understanding - I am completely new to this.
I am hoping to run a php script using Ajax - I don't need to send any data to the php script, I simply need it to run on button press, after the script is run I need to refresh the body of the page. What I have so far:
HMTL Button with on click:
<font color = "white">Next Question</font>
JS Ajax call:
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'php',
success:function(content,code)
{
alert(code);
$('body').html(content);
}
});
}
this runs the php script but doesn't stay on the current page or refresh the body - has anyone got any ideas - apologies if this is completely wrong I'm learning - slowly.
Many thanks in advance.
**As a small edit - I don't want a user to navigate away from the page during the process
How about using load instead of the typical ajax function?
function AjaxCall() {
$(body).load('increment.php');
}
Additionally, if you were to use the ajax function, php is not a valid type. The type option specifies whether you are using GET or POST to post the request.
As far as the dataType option (which is what I think you mean), The Ajax doesn't care what technology the called process is using (like ASP or PHP), it only care about the format of the returned data, so appropriate types are html, json, etc...
Read More: http://api.jquery.com/jquery.ajax/
Furthermore, if you are replacing the entire body content, why don't you just refresh the page?
your ajax should be
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'post',
success:function(data)
{
console.log(data);
$('body').html(data);
}
});
}
if you want to learn ajax then you should refer this link
and if you just want to load that page then you can use .load() method as "Dutchie432" described.
If you are going to fire a javascript event in this way there are two ways to go about it and keep it from actually trying to follow the link:
<font color = "white">Next Question</font>
Note the return false;. This stops the following of the link. The other method would be:
<font color = "white">Next Question</font>
Note how this actually modifies the href to be a javascript call.
You can study about js and ajax here http://www.w3schools.com/ajax/default.asp will help a lot. Of course all js functions if called from internal js script should be inside <script></script> and if called from external you call the js gile like <script src"somejs.js"></script> and inside js there is no need for <script> tags again. Now all those function do not work by simply declaring them. So this:
function sayHello(){
alert("Happy coding");
}
doesn't work because it is just declared and not called into action. So in jQuery that you use after we declare some functions as the sayHello above we use:
jQuery(document).ready(function($){
sayHello();
});
Doing this we say that when everything is fully loaded so our DOM has its final shape then let the games begin, make some DOM manipulations etc
Above also you don't specify the type of your call meaning POST or GET. Those verbs are the alpha and omega of http requests. Typically we use GET to bring data like in your case here and POST to send some data for storage to the server. A very common GET request is this:
$.ajax({
type : 'GET',
url : someURL,
data : mydata, //optional if you want to send sth to the server like a user's id and get only that specific user's info
success : function(data) {
console.log("Ajax rocks");
},
error: function(){
console.log("Ajax failed");
}
});
Try this;
<script type="text/javascript">
function AjaxCall() {
window.location.reload();
}
</script>
<body>
<font color = "white">Next Question</font>
</body>

Categories

Resources