Acces PHP function with clicking an html-button - php

<html>
<body>
<button type="button" onclick="myFunc()">Click</button>
</body>
</html>
<?php
function myFunc() {
echo "Hello world";
}
?>
I made a code like that and tested it but nothing happened. So is it even possible to do it like that or should I just use JavaScript instead?

Use javascript instead. PHP is not meant to do that.
PHP runs on server side but javascript runs on client side.
<html>
<head>
<script>
function myFunc(){
document.getElementById('content').innerHTML = "Hello world";
}
</script>
</head>
<body>
<button type="button" onclick="myFunc()">Click</button><div id="content"></div>
</body>
</html>
jsFiddle
To understand it simply, the PHP interpreter first pre-process your PHP file (hence its name - PHP: Hypertext Preprocessor), and interpret anything inside <?php and ?> tags and turn it into HTML, response header, and so on...
In your case, you define a PHP function and that's all. The function is unused - but the interpreter doesn't care.
After that, the server sends the preprocessed HTML to client side, and anything inside PHP tags are stripped.
Client (mostly, web browsers) will then parse the HTML as is. Client does not receive any PHP at all as they are gone before they are sent, and of course, the browser won't see your PHP function.
And yes, if the PHP depends on client input, you have to use form submission, Ajax, or anything like that.

You have to do JavaScript for this, all PHP code is only executed on server-side.
If you need some dynamic information from a PHP file you have to call it via Ajax (so again JavaScript)

Related

Calling PHP from Java Script

I'm new at dealing with web programming and not used to dealing with the flow of data through a site.
I was looking for a way to call PHP from Java Script or from HTML and came across the following code with many other answers from this site. One thing that I got from Stack Overflow was that Ajax was the only good way to do this and JQuery would be the best way to go about that.
Is the code below safe? Are there holes in it that I don't know about at this point of learning?
<?PHP
$a="hello";
?>
<script>
function echoHello(){
alert("<?PHP hello(); ?>");
}
</script>
<?PHP
FUNCTION hello(){
GLOBAL $a;
ECHO $a;
}
?>
<button onclick="echoHello()">Say Hello</button>
This is not AJAX, but server-side code that only loads at first request.
A mockup of your functionality using AJAX is:
functions.php file:
<?php
$clientSideMethodRequested = $_POST['method'];
if ($clientSideMethodRequested == "sayhello"){
tellHimHello();
}
function tellHimHello(){
echo 'Hello!';
}
?>
client-side AJAX call:
$(document).ready(function(){
$.ajax({
type: "POST",
url: "mydomain.com/functions.php?method=sayhello",
success: function(returnedString){
alert(returnedString);
}
});
});
It will not work. PHP is executed on server, JS is executed in your browser. When you are opening page, the server will at first interpret your code. The result of your code, after this will be like that:
<script>
function echoHello(){
alert("hello");
}
</script>
<button onclick="echoHello()">Say Hello</button>
As you see, everything what was between <?php and ?> was "removed" from the origin file. By "removed" I mean executed.
Sometimes, when your server is not configured to interpret PHP, you will see PHP code in page source in browser. But it still won't work, because no browser supports PHP.
PHP is a server side language, so the code that your browser will "receive" will contain nothing related to PHP. What will happen is that this PHP file will be parsed and executed still in the server, and your browser will get only the following code:
<script>
function echoHello(){
alert("hello");
}
</script>
<button onclick="echoHello()">Say Hello</button>
which is the result of your server's PHP execution. This might be just what you expected in this particular case, but what if we wanted to pass parameters to echoHello function?
<script>
function echoHello(speech){
alert("<?PHP hello(speech); ?>");
}
</script>
<?PHP
FUNCTION hello($speech){
return $speech;
}
?>
<button onclick="echoHello('hello')">Say Hello</button>
<button onclick="echoHello('bye')">Say Bye</button>
One could expect this to alert 'hello' when the user clicks the first button, or 'bye' for the second one. This is not true, as the server starts executing this code before the buttons even exist (as they will only exist when the browser downloads the processed document to render the elements), and thus won't even be able to execute echoHello since speech isn't a valid variable. For this case and many others, AJAX is indeed the most appropriate way to go.
This tutorial should be good for a start.

How can I prevent a page from loading if there is no javascript, but using php instead of <noscript>?

I have a page with php and other stuff in the code. What I need to do is a way to check with php if there is javascript enabled in the browser.
This way, the whole page source will be prevented to be loaded, instead of using that only prevents the page from loading, but allows the source code.
PHP is a server-side language. There is no way to do this with PHP since it is run on the server, and then the result is sent to the client. The server has no knowledge of whether the client has JavaScript enabled or not.
If you don't want to show the code in your .html file when JS is disabled, then you don't have to use PHP. You could put the essential stuff in the .html file and load the rest in with JavaScript. If JavaScript is disabled, the rest of the stuff never gets loaded in the first place. (This is called progressive enhancement.)
This example will use the <noscript></noscript> tag inside an echo directive.
<?php
echo "<noscript>You need JS enabled to view the text on this page.</noscript>";
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
document.write("<h1>Heading Text</h1>");
document.write("<p>This message appeared because you have JS enabled.</p>");
</script>
</body>
</html>
You could make JavaScript fire a request to a page, setting a session variable enabling access to the website, then reload the page. This is by no means secure.
In all files except enable.php (could be done via an include/etc) before anything is echoed.
...
if (!isset($_SESSION['enabled']) { ?>
<!doctype html>
<html>
<head>
...
<script>
var xhr = new XMLHttpRequest();
xhr.open('GET', '/enable.php', false);
xhr.send();
window.location.reload();
</script>
</head>
<body></body>
</html>
<?php die();
}
....
In enable.php, you would then do
$_SESSION['enabled'] = 1;
enable.php would only need to be hit once-per-session and if JavaScript was disabled afterwards, or it was hit manually by pointing the browser there, your server will not know the difference. The assumption is the client must have JavaScript enabled for this session if the page was reached this session.

How to code this ActiveX function in PHP?

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function ShowFile(sFilePath){
var oFileSystem = new ActiveXObject("Scripting.FileSystemObject");
frmEditHTML.tarHTMLText.value = oFileSystem.OpenTextFile(sFilePath.value).ReadAll();
}
function SaveAfterEditing(sFilePath){
var oFileSystem = new ActiveXObject("Scripting.FileSystemObject");
var oFile = oFileSystem.CreateTextFile(frmEditHTML.filPath.value,1);
oFile.WriteLine(sFilePath.value);
oFile.Close();
}
</script>
</head>
<body>
<form name="frmEditHTML">
Select the File you want to Edit
<input type=file name="filPath" onchange="ShowFile(this)">
<textarea name="tarHTMLText" cols=60 rows=20></textarea>
<input type="button" value="Save" name="cmdSave" onclick="SaveAfterEditing(this.form['tarHTMLText'])">
</form>
</body>
</html>
I read this link and this link but they could not help!
I don't want to use ActiveX as then this function will be restricted to IE.
IE Tab in FireFox is also causes problems!
How can I replicate this whole function in PHP without using ActiveX ?
Please Help!
Short answer:
With PHP you can't convert this script exactly as it is, since ActiveX is client side and PHP is server side. Javascript can't do this for you either, since modern browsers are sandboxed, and JavaScript cannot access local file systems.
Not so short answer:
You have other options, however, depending on which behavior (and implementation method) you wish to mimic.
You can use a Java Applet that is able to do pretty much what you could do with ActiveX. Works consistently across browsers but user have to have installed Java Runtime Environment.
You can use a mix of PHP + Javascript (AJAX). You upload a file to the server and then control PHP actions with Javascript (HTTP Requests via Ajax).
Hackish way
There is an hackish simple way to handle this situation. Requires a server somewhere though.
Create a page that uploads a file to the server.
Then send the file back to the browser, via AJAX (or any request, doesn't matter).
Manipulate the file in the client side (browser) with javascript.
Give the file to the user to download.

about combine ajax ,php and javascript

I have a main html file and I am using ajax to call another php file in same directory.
Inside that php file, I call some external Javascript functions. But my javascripts functions are not working. Is it not possible?
I see generated source in my web browser and it is normal. If i call those functions with using php file (without using ajax), then my functions are working and the generated source same as the previous case. Please help me.
In my html file I am using ajax as follows:
xmlhttp.open("GET","end_location_drop_down.php?q="+str,true);
xmlhttp.send();
in my php file functions as follow,
<?php
echo '<script type="text/javascript" src="../js/pointing.js"></script>'; //external script
$btn8="'btn8'";
$q=$_GET["q"];
echo '<script type="text/javascript">
nextpoint('.$at_id.'); //$at_id mean a variable,nextpoint() is my java script function
</script>';
?>
in my JavaScript function have some image swapping functions.they can call by nextpoint(). But it didn't work.
Javascript functions are executed only when you load the page directly in a browser, as your browser is the one who interprets and executes the javascript code. However when the javascript code is in a different page and that page is being called through AJAX, there is no browser to execute the javascript code before the ajax response is sent back to you. SO it won't work.
Javascript must be executed in browser, so you must insert that script in DOM to current document. Try to insert result of ajax call to DOM.

php in javascript?

i need to have some php code inside javascript
<script ...>
<?php
echo " ... ";
?>
</script>
but this doesnt work. how can u implement php inside javascript that is in a own file javascript.php?
That doesn't do what you probably think it does. It'll work, but the PHP gets run once, when the page is loaded, not every time the JavaScript function is called.
Just for clarification, this is what will happen
index.php
<script type="text/javascript">
<?php echo "alert('hello!');"; ?>
</script>
output html in browser
<script type="text/javascript">
alert('hello!');
</script>
If that is what you want to do, then you can output all the javascript you like. What you cannot do is execute PHP code in the user's browser.
your can use php to dynamically generate javascript code, but you cannot execute php client side. If you need to execute php you will need to postback or use AJAX
There seems to be a good bit of misunderstanding of the question... Here is what you want to do to generate JS from PHP on the server:
file javascript.js.php
<?php
header('Content-Type: text/javascript');
?>
// javascript code here
function PrintTime()
{
alert("The time is " + <?php echo json_encode(time()); ?>);
}
Now, include it on the HTML page using normal script tags:
<script type="text/javascript" src="/url/to/javascript.js.php"></script>
The server will process the PHP file, and return javascript from it.
You can't run PHP inside a javascript file. Primarily because PHP runs server side and is processed before the client is sent any actual http info. JavaScript is processed by the browser on the client side and is sent as text.
It looks like you want to pass some kind of dynamic info to the JavaScript. You can do this by passing a variable like this:
<?php $variable="its me"; ?>
<script>
alert('<?php print($variable)?>')
</script>
The output passed to the client is:
<script>
alert('its me')
</script>
What are you trying to accomplish and maybe we can help you come up with a better solution?

Categories