Calling a PHP function in a button [duplicate] - javascript

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.

Related

Php code to modify a document element

I am trying to build a PHP webpage with the following behaviour:
1- A client access the webpage (that contains some buttons);
2- When the webpage is loaded, the PHP script opens a file stored on the server and, based on the information in this file, enables/disables some of the buttons, so that the client can see the webpage with the correct buttons enabled or disabled.
To enable/disable buttons, I know I can use javascript, while to read the file on the server I use PHP as stated above.
How do I put the two things together? Or should I use a PHP code equivalent to the following javascript line:
<script>document.getElementById("button1").disabled = true;</script>
At first I thought that inserting this line in the PHP code was the solution, but then I found out that this can't work for obvious reasons.
Thanks for the help!
Is it correct if I add the following javascript function in the head section of my webpage?
<script>
function enableButtons() {
<?php
if($state=="state1") {
echo 'document.getElementById("button1").disabled = true;';
}
else if($state=="state2") {
echo 'document.getElementById("button2").disabled = true;';
}
?>
}
</script>
I call the enableButtons() function when loading the page by using
<body onload="enableButtons()">
The php code above is just an example, the number of states and buttons is higher, that's why I would like to use this solution.
The common thing to do is to have php read the settings file, and echo the "disabled" attribute on the buttons before sending the output to the user browser. You can get more info about the attribute here here.
You do not need javascript.
Do something like this:
<button type="button" <?php if($state === 'state1') echo 'disabled'; ?>>Button text</button>
Usually you send to the client the buttons already disabled and use js to respond to any event that happens after sending the page, like selecting a combo box value..
You can omit the code, using an if sentence, or hide them using css. First approach is preferred.
Script
<script>
function isValid(f){
if(f.test.value==''){
alert('please enter name');
return false;
}else{
$(".bbutton").html("Processing please wait");
return true;
}
}
</script>
HTML
<form method="post" onsubmit="return isValid(this);">
<input type="hidden" name="te">
<input type="text" name="test">
<div class="bbutton">
<input type="submit" value="send">
</div>
</form>
When you submit the form then it will automatically hide the submit button to avoid pressing again and again, and you can redirect it to other page. May be this idea helpful.

Call javascript function within a PHP form

The architecture I use to load contents onto a common area on the web page is as below
I have a java script function within the form as shown below called javaScriptFunc which never gets invoked.
Is it possible to invoke a java script function within a form?
Please do let me know if more clarity is needed. I'll try to clarify. I'm stuck with this for a while now. I'd appreciate any help please
I think you are missing some PHP tags if I understand what you are trying to do correctly. Try this:
<form method="post" action="" id='somdId'>
<?php
require_once 'some_php_file.php';
if (isLoggedIn()) {
// Some PHP code here
?>
<script>
javaScriptFunc(<?php echo formatJson(someArgs); ?>);
</script>
<?php
}
?>
Not very clear what you want. You need to echo the script like this
echo ("<script type='text/javascript'>javaScriptFunc(" . formatJson(someArgs) . ");</script>");
provided you have already defined the function javaScriptFunc somewhere else in script.
For some reason, I the JS function doesn't seem to fire from within a form. I've worked around by re-writing the load logic to load the whole PHP page instead of a form. just a different way of doing things.

Accessing a php script using a button on the same page? [duplicate]

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

PHP mail function gets triggered every time i load the page

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>

How to execute javascript without click or onload event from php?

I have one javascript named func.js, in that there is one function called show which takes 2 arguments, what I need to do is I want to call that function from php, I can't use any click or onload event here my script looks like this
<html>
<head></head>
<script type='text/javascript' src='path/to/func.js'></script>
<body>
some div etc
<form method='post' action="" >
.....
.....
</form>
</body>
</html>
<!-- after submit of form validation is in php -->
<?php
/* here I want to call javascript, where arguments are php variables
show('argument1','argument2'); */
// I tried to echo like this
echo "<script>show('$argument1',$argument2')</script>";
?>
So what's the solution for my case ?
The code you have should work… most of the time. Unfortunately, you haven't told us why it doesn't work - is there a PHP error? Is there a JS error? — and you haven't shown us either the resulting JavaScript that PHP is outputting or the contents of the variables so we can figure it out for ourselves.
The two most likely explanations (and the only ones that occur to me at the moment) for the problem are:
There is a problem with the data in the variables
That the variables contain characters which cannot appear inside JavaScript strings or ' characters which must be escaped inside JavaScript strings.
JSON is a sufficient subset of JavaScript that the json_encode function will escape (and quote) most data so it is suitable for use in JS.
<script>
show(<?php echo json_encode($argument1); ?>, <?php echo json_encode($argument2); ?>)
</script>
There is a problem with your timing
You have an HTML comment saying "after submit of form validation is in php", but there is nothing in the code you have shared to enforce that.
You need to have something like if (isset($_POST['some_data_from_your_form'])) { ... } wrapped around the generation of the script so it only appears when the form is submitted and not when it initially loads.
If that doesn't work, then you really do need to look at what the variables are, what the generated JS is, and what your JavaScript error console says.
Script elements are not allowed after the end of the HTML element. While browsers will recover from that error, you really should move the script inside the BODY.
It could be to do with the data inside the arguments, what sort of data is it?
echo "<script>show('".str_replace("'", "\'", $argument1)."', '".str_replace("'", "\'", $argument2)."')</script>";
If you're passing information such as J'min it will cause an issue. Does the data have multiple lines? Then it needs to be filtered.
First of all, your tags are broken
<script type='text/javascript' href='path/to/func.js'</script>
You should change href to src and close the script tag, so it becomes
<script type='text/javascript' src='path/to/func.js'>
Also, javascript is client-sided which means you can't call javascript functions in PHP.
I think a good solution here would be to use an AJAX call to validate your form.
Have you tried putting the arguments outside the quotes?
echo "<script>show('".$argument1."', '".$argument2."')</script>";
echo '<script type="text/javascript">show(' . $argument1 . ',' . $argument2 . ');</script>';
above might work for you.

Categories

Resources