How to refresh a specific div of a page in PHP? - javascript

I am making an online game using PHP and JavaScript, I have more knowledge in PHP than I do in JavaScript, though I am new in both languages, so keep that in mind.
So what I was trying to make in PHP / JavaScript and of course HTML was to refresh only the div or the area of code that I need, and I can't make the page reload every time that it gets new information or data because when the PHP is ran and done then I can't have anything else running, unless I was to use a loop though that sounds a bit sketchy and not sure if that's the method. I have tried: (PHP)
header("reload: 1");
Though that only refreshed the page, that is what I want to happen when I get data not always to be happening, so for example the program would get the information that someone is ready then it would send the client to another page as asll as the other client.
Though I would just like an explination if it is possible to only refresh a specific area when told to by example getting MySQL data.

function refresh_box()
{
$("#myDiv").load('path your PHP file');
setTimeout(refresh_box, 60000);
}
$(document).ready(function(){
refresh_box();
});
this setTimeout call your function for every 1 minute and load content dynamically in mydiv.

Related

how to commuincate between php and JS?

I am new to web development and I am trying to build my first website.
I am having some troubles because web development is dependant on several programming languages like PHP and JS, and the most difficult part for me is to communicate between these languages.
For example, I am trying to create a function that compresses a folder and generate a download link to that new archive, this can be easily done by PHP. However, when the user clicks the zip button, I also wish to display a pop-up window that tells the user to wait while the folder is being compressed, and when the compression is done I want to change the text on that pop-up and display the download link, and this, of course, requires JS.
I've tried many solutions but none of them seemed perfect for me, and I feel like that these solutions are quick and dirty, which I don't want.
If there is a secret I do not know, please tell me about so I can finally work with these languages as if they are a single language.
Also, if you can help me with my current problem, I would be extra grateful.
I just want to know how to construct a form that can call the JS function that displays the pop-up, then calls the PHP Zip_Folder function, and once the PHP function is done, I want to display the download link on the pop-up window.
This is my form code: (It only calls the javascript function that displays the pop-up)
<input type = 'button' onclick = 'Show_PopUP(\"Folder_to_zip\")' value = 'Download Folder'>
And this is the Show_PopUP function code:
function Show_PopUP(folder) {
var e = document.getElementById('Folder_Download_PopUp');
if(e.style.display == 'block')
e.style.display = 'none';
else {
e.style.display = 'block';}}
I already have the PHP function that compresses and generate a download link for the archive, so what I need now is a way to call it after the pop-up is displayed, and a way to print the download link on the pop-up once the function is done.
This might not be the best approach since I am a beginner, so if you have suggestions on how to get my task done without this complexity, I would be very happy.
Sorry if my question is too long, and thanks in advance for your help.
What you need to do is use these things called XHRs, or XMLHttpRequest (Google it), from within JavaScript to php, which basically is kind of like an invisible browser going to the php page behind the scenes and "loading" whatever the php page gives back, only this is all happening within JavaScript itself, so you can read that this "invisible page" loaded, which is from php, and do stuff with that, without actually refreshing the page. This process is known as AJAX (look it up)
What you can do is, when you set up this "invisible page", you can also send certain kinds of information along with it that the php page can read, and when it's done the php page can echo something back to the invisible page, which can then be read with JavaScript. This easy you can communicate between php and JavaScript, by sending certain values, in JavaScript, along with this invisible page, and waiting for php to echo something back to it, then reading that with JavaScript
So how do we actually do this?
First on the JavaScript side, we need to make this "invisible page", which is really not technically a page, it just does the sane thing as what is done to display any other web page, which is technically called a "request" since it's like asking the server for some data, it's basically "requesting" it, then when the server echoes something back, that's called he "response" to what was requested
So to make this new request in JavaScript we can do the following
var asking= new XMLHttpRequest ()
now that it as if an invisible page was created, but not yet navigated to anything, but we have to now metaphorically "enter in the URL" to this invisible page (without actually "navigating" to it yet) to do that we do
asking.open("GET", "pathToPHPpage.php?hi=there")
So the first part is called "GET" because we want to simply get a response back, without actually sending anything (if we were sending a file though, we would instead use "POST" then put the file date in the next step), then we enter in the URL to the php page that you want to get. If it's the same as the JavaScript page just put location.href instead, but it's important to add at least something to the end of the URL, notice the "?hi=there", you can call it anything, but it's important to have a question mark immediately following the .php page, then the name of something (in this case"hi") followed by it's value (in this case "there"), because the php page is able to read that, and give a different response back depending on what it says
Ok so now we have to actually "send" that request to the server, which is like metaphorically "navigating" to the URL on the invisible page, to do that
asking.send()
(And if you put "POST" before, you can add the date you want to send in between the parenthesis, usually in the form of a string but it can be different depending on the data, look it up for more reference)
Now, before we continue in the JS side, let's quickly switch over to PHP (doesn't have to be in this order though) to see what happened
We need to listen for any "requests" on the php page, that contain the name "hi" (since that's what we at the end of the URL before), to do that, around the top of PHP (technically anywhere in php though) we do
$isHi = $_GET["hi"];
if(isset ($isHi)) {
//Do some php code
echo "hi back!".$isHi;
}
Basically we just looked for the *hi" name in our "GET" request that was sent to PHP, we checked if it is "set", meaning not nulll, then we echoed some message back to JS, now let's listen for that message on the JavaScript side
Back to JS, after the .send line (or before), we need to listen for when the page echoes back.
To do that we check if it successfully loaded, because sometimes there can be errors, so let's do
asking.onreadstatechange= function () {
if(asking.readyState == 4 && asking.status==200) {
alert(asking.responseText)
} else alert("ooh something happened")
}
Now we have access to the response the php code gave us
You can extend this to other forms of communication, let me know if you have any questions

Can I reload a page that loaded with .load?

I'm adding new data to database
but to load the new data I have to reload the page
I was wondering is there anyway to reload a loaded page without refreshing the
whole page ?
P.S : I have used the .html thing and it won't load new data
$(document).ready(function () {
$(".container").load("../../public/include/menu/add.php");
$("#add_from").ajaxForm(function () {
$(".container").reload("../../public/include/menu/add.php");
});
You may be overthinking this. Consider how you load your data from the server:
$(".container").load("../../public/include/menu/add.php");
Now, at a later time in the page, you wish to load your data from the server. You would just repeat the process:
$(".container").load("../../public/include/menu/add.php");
You're trying to repeat an action at a later time, you would do so by calling the same code again. You can encapsulate it in a function if you don't want to duplicate the code, but overall you just repeat the process any time you want to repeat the results.
Though it's not really clear what you mean by "used the .html thing". And this probably isn't the most performant approach, as you could likely return updated data directly to the AJAX form post instead of requiring another request entirely. But if this is easier for you, go for it.
If your default data is being fetched with ajax, you probably just need to call the fetch method. You can use location.reload() instead, if you aren't fetching with ajax.

Create content which updates asynchronously PHP

I'm trying to create a trading bot with PHP.
I would like to get the value of the currency and update it even without refreshing the page.
In order to do this I should execute this call every 5-10 seconds.
Is that correct?
$summ = $d->getMarketSummary("USDT-BTC");
Is there a way to do this asynchronously? Even if user doesn't reload the whole page.
I've heard of AJAX, but it's Javascript.
Thank you in advance.
You've heard it correctly, you need to do this in JavaScript, with AJAX. There are two parts for this:
1) You need to make an API in PHP, a route that will only respond with the data you want. So a page that when called:
<?php
$summ = $d->getMarketSummary("USDT-BTC");
echo $summ;
?>
And mapped to a url, let's say /data.
2) You need to make a JS in your page that calls that newly created route every-so-often; for that your need to use ajax (xmlhttprequest or Fetch API), and use the setInterval function to call it regularly and update the data in your page accordingly.
If you can't use javascript (AJAX) for this task, your only way is to create a CRON job that fires that PHP script every minute. Unfortunatelly, CRON jobs can't be configured to execute every X seconds, but you can fire it all minutes of the day.

Showing image when available

I am trying to create a web interface for a scientific code. The user will provide some inputs and submit through a HTML form. A php script will take the input and run code on server. In the end of it, one or more (not more than 10) images will be created. The code may take few seconds to hours, depending upon the inputs.
How can I show these images on the webpage after completion, and make them available for download?
You will need to have a method that creates a unique identifier upon completion.
So this can be as simple as checking to see if the image exists, and if not notify the user that it is still in progress.
so something like:
if (file_exists($image_file)) { do something... }
else { echo 'Files still in progress....'; }
Assuming your going todo the scientific code in a background process, the issue would be the frontend.
To make it simple, I would assign the job/calculation a unique url, that relates to the results, much like codepad, viper7, JSFiddle do, then while there on the page poll (AJAX) the server for the images/results. Dont even attempt todo any submitted code, while the user waits or on the request thread.

Get dynamically changed data from web page using javascript / jquery

I'll be as direct and as specific as possible.
I'm trying to create Greasemonkey addon that would create graph of winnings/loses on: dead link
As you can see, site has front page which dinamicly shows results of wins / loses and how much did which user win/loose. What I'm trying to do is catch every new entry so I can draw some grapsh and or statistics for user / users.
When I access div/span that should have data, it turns out to be empty. I know that reason behind this is that all divs with data relevant to me are empty on load and that they get populated later on.
What I don't know is how to access that data. I can see (using firebug console) that there are GET requests executed all the time and that in those get requests is data that I need.
Can someone tell me or at least point me into right direction, how to access that data every time it gets refreshed / inserted?
You can try using the $.ajaxSuccess function to specify a function in your script to be called everytime an ajax request completes in the main page. This'll be fired for every successful ajax request, whether it pertains to the data you're talking about or not, but should allow you to re-scrape that section of the document to grab any and all data in it after every successful request. You may want to wrap your callback function in a setTimeout of some kind to make sure their own callbacks have a chance to fire and inject/modify the content before you scrape it. It should still seem instantaneous to the user if you set a timeout of, say, 1-10ms.
http://api.jquery.com/ajaxSuccess/

Categories