Basic PHP - HTML flow - high level understanding - javascript

Can someone confirm that the is the basic flow for PHP - HTML.
PHP runs on the server, and pre-processes the page so it can be sent to the browser.
In the browser you can run things like javascript.
So in order to pass things to PHP (from Javascript):
you need to "fetch" the php page (with post or get args)
This re-runs the php page (on the server) allowing you to process those args, generating a new "page" to send to the browser.
PHP variables aren't "sent" to the browser, but processed and inserted in the a new page that's sent out when the page is fetched.
Am I even close ?

Related

Run PHP function when img clicked

I'm wondering if there's a way to perform a function when an image is clicked in PHP? I know it can be done in Javascript. For example, when foo.png is clicked, the following function will run.
function example() {
header('Location: example.php');
}
PHP is run on the server, and is used before and while creating the page -- and then it is submitted to the browser for rendering.
Once the page is rendered and displayed to the user, all PHP processing has stopped and the page has been served to the client. Server code no longer runs - its time has passed.
Once in the browser, only client-side code can run (javascript). Particularly when interacting with the user, client side code is all you can use.
However, you can also use client-side code (javascript/jQuery) to interact with the user (detect a click or mouse movement) and then use AJAX to send data over to another server-side PHP file. The PHP file will "wake-up" as it receives the data, and it can do some additional server-side stuff -- such as use the received data to perform a DB look-up, then take the new DB data and create some HTML code and send that back to the page. This new HTML code can be injected onto the page in the success (or .done() ) function of the AJAX code block and new data can appear on the page without refreshing or navigating away from the current page.
But for actually detecting the user click, it's javascript/jQuery.
Note that PHP can also inject javascript along with the HTML - but once the code has been served to the browser for display, it is only the javascript that can interact with the user, not the PHP.
With javascript/jQuery, you can do what you want like this (the code is correct but the example will not work properly - SO will not navigate to the Google webpage):
$('#myImg').click(function(){
window.location.href = 'http://google.com';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>Click below for Google</p>
<img id="myImg" src="http://placeimg.com/50/50/animals" />

how to access JavaScript variable in php i have tried following but doesn't work [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 6 years ago.
i have try to perform select query from tag with JavaScript variable but it is not work.
What wrong with it
function method12()
{
var value12=document.getElementById('period').value
<?php
$con=mysql_connect("localhost","root","");
if(!$con)
{
die('could not connect:'.mysql_error());
}
mysql_select_db("db_loan",$con);
$sqlstr="select bankcode from tbl_master where loanaccountnumber='".value12."'";
$result=mysql_query($sqlstr);
$row=mysql_fetch_array($result);
echo $row['bankcode'];
?>
alert(value12);
}
PHP is run server-side. JavaScript is run client-side in the browser of the user requesting the page. By the time the JavaScript is executed, there is no access to PHP on the server whatsoever. Please read this article with details about client-side vs server-side coding.
What happens in a nutshell is this:
You click a link in your browser on your computer under your desk
The browser creates an HTTP request and sends it to a server on the Internet
The server checks if he can handle the request
If the request is for a PHP page, the PHP interpreter is started
The PHP interpreter will run all PHP code in the page you requested
The PHP interpreter will NOT run any JS code, because it has no clue about it
The server will send the page assembled by the interpreter back to your browser
Your browser will render the page and show it to you
JavaScript is executed on your computer
In your case, PHP will write the JS code into the page, so it can be executed when the page is rendered in your browser. By that time, the PHP part in your JS snippet does no longer exist. It was executed on the server already. It created a variable $result that contained a SQL query string. You didn't use it, so when the page is send back to your browser, it's gone. Have a look at the sourcecode when the page is rendered in your browser. You will see that there is nothing at the position you put the PHP code.
The only way to do what you are looking to do is either:
do a redirect to a PHP script or
do an AJAX call to a PHP script
with the values you want to be insert into the database
You can't use JS variables in PHP. JS code is run on the client and PHP code is run on the server.
To do what you want you have to send the JS value via a GET or POST request to the server and then get that value via $_POST["varname"] or $_GET["varname"]

How to retrieve a succession of text messages/status reports from a PHP script that is the action of a form submission?

I have a form that currently is processed by an action in a PHP script when submitted. The PHP script contains a number of procedures that take time to process. I'd like to print to the parent script (the one with the form, which remains visible on screen until the PHP script is finished) status reports from the PHP script, e.g.:
Procedure 1 has begun... Procedure 1 is finished.
Procedure 2 has begun... Procedure 2 is finished.
Procedure 3 has begun... Procedure 3 is finished.
etc.
I understand that the primary way to do this is by intercepting the form submission with an AJAX call, like this:
$('#formID').on('submit',function(e){
e.preventDefault();
$.ajax({
type : "POST",
cache : false,
url : $(this).attr('action'),
data : $(this).serialize(),
success : function(data) {
// do something with the returned data from the PHP script
}
});
});
However, that would seem just to return/report the return value (echo message, etc.) from the PHP file that is called by the form. I want a series of messages to be returned to the parent form indicating the progress of the PHP script as it processes values from the form.
For reasons I don't fully understand, the form page remains visible until the PHP action is completed, at which point the page is redirected to a different page in the site by use of a header() directive at the end of the PHP script. (The code was originally written by a different developer; my understanding of his routine is imperfect. The submit() is called within a JQuery PLUpload function, which may or may not be why the form page remains on screen until the PHP action script is finished.)
Without breaking up the PHP form processing into a series of individual scripts, each processed separately, how can I use AJAX (or another technique) to intercept the default form processing and execute the PHP processing script such that status text messages may be echoed to the screen or appended as styled text on <div> elements in the form page? (The PHP processing script relies on a series of variables that are derived from the values on the form, and it would be inelegant, to say the least, to have to recreate them in a succession of individual PHP files called sequentially, since the current PHP form processing script is efficient and works fine, albeit slow because of the nature of its operations.)
On my localhost, and perhaps on many live servers, the solution requires a header <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> followed by while (#ob_end_flush()); and then an explicit flush(); after each text echo. A simple example of this would be this short routine:
<?php
header( 'Content-type: text/html; charset=utf-8' );
while (#ob_end_flush());
function sendMsg($msg) {
echo $msg;
flush();
}
function sleep_test($sleep_time) {
$x = "Beginning process:<br>";
sendMsg($x);
$y = "Waiting $sleep_time seconds ...<br>";
sendMsg($y);
sleep($sleep_time);
$z = "Done.<br><br>";
sendMsg($z);
}
sleep_test(1);
sleep_test(2);
sleep_test(3);
?>
However, I'm on a shared hosting plan on my live server whose admin settings (i.e., those I cannot alter via php.ini and Apache overrides, etc.) will not display its text until it is entirely processed; only then will the buffer be fully flushed. The script above works perfectly on my XAMPP and WAMP localhosts, and should for anyone else's, but if it doesn't and you're trying to get this kind of performance on your live host, then if this script doesn't flush the buffer until it is fully processed, it may not be possible; contact your liveserver's admin for info.
For my purposes, a very carefully constructed set of AJAX calls worked for the processing script from which I desired status text updates as the processing proceeded.

Web: How do we display content on the Client after making a slow Server Side Call?

I am working on a Web Application for which I am currently doing something like this:
Page1.php posts to Page2.php.
Page2.php contains an HTML file with 2 Javascript files. The first Javascript file uses an AJAX call to trigger Page3.php. The second Javascript file listens to Result.json for results.
Page3.php invokes a Python Script, Task.py.
Task.py takes about 15 minutes to run, writes results to Result.json which I need to display on Page2.php.
The problem here is 1st that the since Task.py is such an expensive call, I end up on Page2.php on Chrome and Chrome pops open the window asking me if I would like to kill or wait for the page to load and the Web Page eventually becomes unresponsive (Times Out).
As a result, I become unable to display the results stored in Result.json on the page.
Another problem that I am having is that the Task.py file that I am executing appears to be a blocking call, so when my first Javascript makes the AJAX call, it prevents my 2nd Javascript from listening to Result.json for results (When Javascript makes an AJAX call, it waits there until it gets the response back). So even if there was content already in the Json file, it wouldn't pick up on it until the 1st AJAX call returns.
The Listening Javascript file looks something like this:
while(true){
result = setTimeout(myFunction, 60000);
if(result === true){
console.log("Quitting the loop");
break;
}
}
where myFunction parses the Json file and manipulates the DOM to display the content.
Any Advice?
You can use Server Push/Websocket for it. If your server is ready to serve the data, it can notify the client side to get the data. Just search for socket.io / nodejs.
first Ajax call starts page3 and set event listener to server push message. If it receives the message, simply get content of Result.json.

Checking external session variable on each page before loading, with javascript

I've created a php login system which saves the username as a session variable, on the server where the php is hosted.
I need to check this session before loading any pages within my stand alone phonegap (html, css & javascript) project which is hosted separately.
Is there a javascript call I can make at the start of each page to check it and then redirect it if they aren't logged in?
you should not do that, somebody could turn off javascript and bypass your check.
instead, do normal php check on eatch page. you can put check into separate file (say, check.php) and just put on etach page require ('check.php');
EDIT (reply to comment/question edit):
a) how to make your own session:
as simple as session_start();
b) how to pair it with remote session:
if (!isset($_SESSION['remoteid']))
$_SESSION['remoteid'] = sesion id that you recived as response prom remote php server.
once again, you can not do it simply with html, css & javascript. javascript can be turned off. you need php/python/ruby/etc...
needless to add that javascript can not be persistent, since it is not executed on server.

Categories

Resources