This question already has answers here:
Call php function from JavaScript
(5 answers)
Closed 7 years ago.
I was wondering how would I make it so that when a button is clicked in my form, it runs a php function that is on the same file?
I tried doing something like this:
<form>
<input type=button name="button" value="Submit" onClick="hello()">
</form>
<?php
function hello(){
echo "Hello"
}
?>
But when the button is clicked, nothing happens, neither of my functions are called. How would I go about doing this?
PHP is a server side language.
You need a client side language "JavaScript".
If you need really php execution : You need ajax requests on a url (script.php).
This:
<?php
function hello(){
echo "Hello"
}
?>
exists on the remote server and the rest of HTML in your browser. Even though they are in the same file they don't see each other.
Use AJAX PHP to make PHP functions run from within HTML pages
Here is the link AJAX PHP
Related
following is the code with start button and its function which is not working but when im trying to echo hello in place of button tag then the function is working well
<button onclick="startexam()" id="btn" class="btn btn-primary btn-sm" title="Start
exam">Start Exam</button>
<?php
function php_func(){
echo '<select class="form-select" aria-label="Default select example"><option >
asdf</option></select>';
}
?>
<script>
//function called when user click on start exam button
function startexam() {
var result = "<?php php_func(); ?>"
document.write(result);
}
</script>
First, you need to understand what the technical difference between PHP and JavaScript is:
JavaScript executes scripts directly in your browser, e. g. Firefox. So, when JavaScript is executed, the page is already loaded.
PHP executes scripts on the server before the page is even in the browser.
So, if you want JavaScript to communicate with the server (the PHP script), you have to make a request to the server. To do so, use AJAX.
How does AJAX work?
From W3Schools:
An event occurs in a web page (the page is loaded, a button is clicked)
An XMLHttpRequest object is created by JavaScript
The XMLHttpRequest object sends a request to a web server
The server processes the request
The server sends a response back to the web page
The response is read by JavaScript
Proper action (like page update) is performed by JavaScript
How to use AJAX?
You can find a complete and clear introduction on W3Schools.
This question already has answers here:
html or java script code to create a text file in hard disk
(2 answers)
Closed 5 years ago.
What I have done so far is a PHP code which is running when the page is refreshed:
<?php
$pageRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';
if($pageRefreshed) {
$file01 = file_get_contents("file01.txt");
$path = "file02.txt";
$file02= file_get_contents($path);
if ($file01!== $file02){
file_put_contents($path, $file01);
}
}
?>
but, I have an HTML button:
<button class="btn" id="refreshPanel" onclick="refresh_panel()">Refresh Panel</button>
and I want to copy the content of file01 into file02 if this button is clicked using pure javascript.
Both files and .html and .js files stored in the same folder in my computer.
Thanks for your help and time in advance!
If you are trying to write a file on client machine, You can't do this in any cross-browser way.
If you want to do something like this, you must pass the execution of these actions to server-side
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
So in my php page I have this code :
<div id="test"></div>
<script src="test.js"></script>
And in my external javascript I have :
document.getElementById('test').innerHTML=
"<div id='abc'><a href='index.html'><?php echo 'Welcome '.$_COOKIE['user'].'<br>' ;?></a></div>";
Cookie has been set and if I put the script inside the php page, it does work but why isn't it working when it is external script ? Did I do something wrong here ? or is there a rule for doing this ?
Please educate me.
Thx in advance. =D
While using PHP and javascript together is absolutely possible, you have to remember, that PHP is executed on server-side while javascript is executed on client-side.
So you cannot have PHP in your javascript, as the page lifecycle is like this:
Get the request from client browser
Execute the PHP of the requested page and provide the html
Send the html to the client browser
Render the html in the client browser
Execute the javascript of the page
So after the page is sent, the php processing is done.
You can however embed variable via php for later use with javascript. If you echo out something like this, your java scripts can use it:
<script type="text/javascript">
var myCookie = "<?php echo $_COOKIE['user'];?>";
</script>
If you do a lot of stuff with cookies in your javascript, you may even better have a look at jQuery Cookies and fetch the cookie value directly. This will make you end up with much cleaner code.
You can't use PHP in a javascript file like that. They are two totally different languages.
You can't render php on a Javascript file, but you can do this:
on your php file:
<script>
var cookie = "<?php echo 'Welcome ' . $_COOKIE['user'] . '<br>'; ?>";
</script>
<div id="test"></div>
and in your js file:
document.getElmentById('test').innerHTML = cookie;
Regards
We cannot add php code inside the js file.
PHP is server side scripting language which will executed in the server and response will returned to the browser, while Javascript is client side scripting language which is executed in the browser.
This is a solution but just use ajax to get the required information from the server.
<div id="dom-target" style="display: none;">
<?php
$output = "42"; //Again, do some operation, get the output.
echo htmlspecialchars($output); /* You have to escape because the result
will not be valid HTML otherwise. */
?>
</div>
<script>
var div = document.getElementById("dom-target");
var myData = div.textContent;
</script>
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 8 years ago.
I have a php class with a function and I want to call that function with an onclick event of a button. I wanted to know if there are any ways to do that. here's the code:
<?php
class myClass{
function myClass(){
echo "myClass called";
}
}
?>
<html>
<title>sample project</title>
<body>
<form action="">
<input type="button" value="click" onclick="myClass()">
</form>
</body>
</html>
I'll appreciate if you can help me with this.thanks
I'm not going to go into detail about the difference between server and client side programming, since it's outside the scope of this question.
The short answer is that you can't. PHP is executed on an interpreter. The client that you are serving the web page to may have a PHP interpreter.
The answer you're looking for is JavaScript, which is also executed on an interpreter, but unlike PHP it is built into all modern browsers.
The high level solution is to split your PHP and HTML into separate files. You serve the HTML, which contains Javascript, which then calls your PHP script.
In your HTML, here's how you include JQuery in your web page:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script></head>
Now you have access to all sorts of useful Javascript goodies.
Next step is to serve your PHP script at a publicly accessible URL. e.g.
http://example.com/myphpscript.php
Inside it would contain your code:
<?php
class myClass{
function myClass(){
echo "myClass called";
}
}
$myClassInstance = new myClass();
?>
Assuming you are running a version lower than PHP 5.3.3, myClass() is treated as a constructor. That is, it is called automatically when MyClass is instantiated, i.e. new MyClass.
If you are running PHP 5.3.3 or higher, just change the name of the function myClass() to __construct().
When you are done this step, it's time to write some Javascript. What you need to do is use Javascript to register an event listener that listens for when the button is clicked, and executes some Javascript code when that happens.
I don't want to duplicate an answer, so you can find it here: ajax post within jquery onclick
you could do this... (but this isnt to advise)
<?php
class myClass{
function myClass(){
echo "myClass called";
}
}
if($_POST['go']){
$foo = new myClass();
}
?>
<html>
<title>sample project</title>
<body>
<form action="" methode="post">
<input type="hidden" name="go" value="1" />
<input type="submit" value="click" />
</form>
</body>
</html>
but in your case you reall should use ajax, mixing php with html and/or javascript is not really nice coding.
So this is an issue with web development as html/css/javascript are client side, and PHP is server side. Properly you can still achieve your goal with ajax, but I use a simple jQuery trick that can call PHP code. Here it is:
Add this to HTML
<div class="holder"></div>
Then CSS
.holder {
display: none;
}
And then javascript
function myClass() {
$('.holder').load('path/to/php/file');
}
Any HTML returned by the php file (like echo or print_r will be put into the holder div, but won't be displayed.
I am trying to send mails using PHP's mail() function.
I have a button (Send Mail), clicking on which the mail has to be triggered. Since PHP is a server side scripting language, I used Javascript to trigger the PHP function. A very unusual event occurs. Whenever I load the page, the mail gets triggered. So, I put alerts and echos to check if the code logic is correct.
Funny thing is that the mail does not get triggered when I click the button. Where am I going wrong?
Please see my code:
<input type="button" onclick="jMail()" value="Send Mail"/>
<script>
function jMail()
{
alert("Inside Javascript Function");
alert("<?php PHPFunction(); ?>");
}
</script>
<?php
function PHPFunction(){
echo("Inside PHP Function");
mail("to#example.com", "Help Mee", "Definitely Help me", "From:from#example.com");
echo("Mail Sent");
}
?>
PHP is a server side language, while Javascript is a client side language. I think you are confusing the two, and trying to mix their use in a way that would never work.
When the page is loaded, these steps occur in sequence:
The server interprets the PHP code in your page, and renders a page that does not contain any PHP code.
The client, viewing the page, does not obviously have access to any PHP function, because it sees only the result of the elaboration. It still can use Javascript to achieve dinamic behavior of the page (i.e. changes without refreshing), and things like AJAX to make requests to the server still without re-rendering the page.
<input type="button" onclick="jMail()" value="Send Mail"/>
The event onclick is indeed triggered when you press the button, but after the page has been fully loaded. At this time, all the PHP code has been already interpreted by the server, and there is no chance to execute it again without reloading the page.
EXAMPLE: here you can see the result of the elaboration of your code (under stdout). As you can see, the client is left with a PHP-free web page.
If you're looking for a way to trigger PHP code when an event occurs after the page has been loaded, I suggest you take a look at this question.
Also, this question on programmers.stackexcange.com could help you clarify the difference between client side and server side if it isn't clear.
You cannot trigger PHP from javascript that way. Create another PHP file, and call it using AJAX javascript requests.
<form method="post">
<input type="submit" value="Send Mail" />
</form>
<?php
if(isset($_POST)){
///do sent mail here
mail("to#example.com","Help Mee","Definitely Help me","From:from#example.com");
}
?>
PHP is a server side scripting language which has already been interpreted by the server and then sent to client(i.e browser) for interpretation of any client side script( ex JavaScript).
But if want a responsive webpage to be handled by your server try to use Form and inputs tags and their attributes to send your request back to server
But if you want a Quick way Try using AJAX.
every time you do
<?php PHPFunction();
you send the mail..
maybe you could play with something like
<?php
if(array_key_exists('postMail',$_POST)){
echo ("Inside PHP Function");
//if(empty($_POST['mailContent'])){/*angry blablabla*/}
mail("to#example.com","Help Mee",$_POST['mailContent'],"From:from#example.com");
echo ("Mail Sent");
die();
}?>
<input type="button" onclick="jMail()" value="Send Mail"/>
<script>
function jMail()
{
alert("Inside Javascript Function");
var xhr=new XMLHttpRequest();
xhr.open("POST","?");
var fd=new FormData();
fd.append("postMail","true");
fd.append("mailContent","fooooobar");
xhr.send(fd);
}
</script>