Calling a PHP function by onclick event - php

I am trying to call a function by "onclick" event of the button.
When I do that it shows error message.
Can anybody help me out on this so that when I click on the button it should call the function and execute it.
My PHP code is:
<?php
function hello() {
echo "Hello";
}
echo "<input type='button' name='Release' onclick= hello(); value='Click to Release'>";
?>
What is wrong with this code?

The onClick attribute of html tags only takes Javascript but not PHP code. However, you can easily call a PHP function from within the Javascript code by using the JS document.write() function - effectively calling the PHP function by "writing" its call to the browser window: Eg.
onclick="document.write('<?php //call a PHP function here ?>');"
Your example:
<?php
function hello(){
echo "Hello";
}
?>
<input type="button" name="Release" onclick="document.write('<?php hello() ?>');" value="Click to Release">

First quote your JavaScript:
onclick="hello();"
Also you can't call a PHP function from JavaScript;
you need:
<script type="text/javascript">
function hello()
{
alert ("hello");
}
</script>

Executing PHP functions by the onclick event is a cumbersome task and near impossible.
Instead you can redirect to another PHP page.
Say you are currently on a page one.php and you want to fetch some data from this php script process the data and show it in another page i.e. two.php you can do it by writing the following code
<button onclick="window.location.href='two.php'">Click me</button>

onclick event to call a function
<strike> <input type="button" value="NEXT" onclick="document.write('<?php //call a function here ex- 'fun();' ?>');" /> </strike>
it will surely help you
it take a little more time than normal but wait it will work

In Your HTML
<input type="button" name="Release" onclick="hello();" value="Click to Release" />
In Your JavaScript
<script type="text/javascript">
function hello(){
alert('Your message here');
}
</script>
If you need to run PHP in JavaScript You need to use JQuery Ajax Function
<script type="text/javascript">
function hello(){
$.ajax(
{
type: 'post',
url: 'folder/my_php_file.php',
data: '&id=' + $('#id').val() + '&name=' + $('#name').val(),
dataType: 'json',
//alert(data);
success: function(data)
{
//alert(data);
}
});
}
</script>
Now in your my_php_file.php file
<?php
echo 'hello';
?>
Good Luck !!!!!

probably the onclick handler should read onclick='hello();' instead of onclick=hello();

Use this html code it will surely help you
<input type="button" value="NEXT" onclick="document.write('<?php //call a function here ex- 'fun();' ?>');" />
one limitation is that it is taking more time to run so wait for few seconds it will work

Try this
<!DOCTYPE HTML>
<html>
<head></head>
<body>
<?php
function runMyFunction() {
echo 'I just ran a php function';
}
if (isset($_GET['hello'])) {
runMyFunction();
}
?>
Hello there!
<a href='index.php?hello=true'>Run PHP Function</a>
</body>
</html>

You cannot execute PHP functions from JavaScript.
PHP runs on the server before the browser sees it. PHP outputs HTML and JavaScript.
When the browser reads the HTML and JavaScript it executes it.

Related

How to call a php function on button click with one param

I want to call a php function with one param, id of a button, when I press that button.
This is what I tried:
<!DOCTYPE html>
<html>
<body>
<?php
include ("sterge2.html");
<button onclick="writeMsg(this.id)">Click me</button>
function writeMsg($id) {
echo $id."Hello world!";
//add that id in a database...
}
?>
</body>
</html>
But it does nothing...
you can not combine javascript and php. instead of it use ajax.
try below ajax code..
<button class="btnsubmit" id="submit" data-id="5" >Click me</button>
$(".btnsubmit").click(function() {
var id = $(this).attr('data-id');
$.ajax({
url : URL+'writeMsg',
type : 'POST',
data : {'id': id},
success : function(data)
{
}
});
});
and in writeMsg function perform database opertaion.
i hope this code will help you.
Try this:
<!DOCTYPE html>
<html>
<body>
<?php
include ("sterge2.html");
echo '<button onclick="writeMsg(this.id)">Click me</button>';
?>
<script>
function writeMsg(id) {
alert(id + "Hello world!");
// Use AJAX to call PHP file and save id into DB
}
</script>
</body>
</html>
With onclick-event you can call a javascript function. Not php.
Just try this.
<!--html -->
<button onclick="writeMsg(<?php echo $id_val ?>)">Click me</button>
<!--html -->
Function will be included in javascript
<script type="text/javascript>">
var id;
function writeMsg(id) {
alert(id."Hello world!");//give you result
}
</script>

Ajax text to PHP duplicates text and button when passing value

I am working on a bit of ajax that gets the value from a text input and passes it into a php variable. I have got the following code doing what I want, however it duplicates the text input and the button when it passes the value into php and I can't work out why, any ideas:
<html><head><title>Ajax Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
function callAjaxAddition() {
arguments0 = $("input[name='arg1']").val();
$.ajax({
type: "POST",
url: "refresh.php",
data: {arguments: arguments0},
success: function(data) {
$("#answer").html(data);
}
});
return false;
}
</script>
</head>
<body><div id="exampleForm">
<input name="arg1" /><div id="answer"></div>
<br />
<button onClick="callAjaxAddition()">Click Me to Add</button>
</div>
<?php
if(isset($_POST['arguments']))
{
$a = $_POST['arguments'];
echo $a;
var_dump($a);
}
?>
</body></html>
You are sending request to a php file that has html code in it. So it renders current html, it has text box in it. And you are putting it in answer div. That's why it is duplicating. If you make a request to refresh.php, it response whole page not only echo $a; part. Create aseparate page like service.php and
service.php:
<?php
if(isset($_POST['arguments']))
{
$a = $_POST['arguments'];
echo $a;
}
?>
Use service.php in your ajax call

How to dynamically load a PHP page inside another PHP page's <DIV>?

I currently have two PHP pages: test1.php and test2.php. Inside test1 are 2 DIVs: one named "SubmitDiv", and one named "DisplayDiv". Inside SubmitDiv is a Submit button. When the user clicks on the Submit button, it should load test2.php inside DisplayDiv. Currently test2.php will only display "Hello World". I want it to load test2.php inside the DisplayDiv so that the test1.php page doesn't need to break stride or otherwise reload.
And this is where I am stuck. I am aware that I likely have to make use of AJAX in order for it to dynamically load the test2.php page inside DisplayDiv. How this is done, however, has bested me, and my attempts at it have so far failed. Using the below scripts, which I have pieced together from online searches of this issue, when I try to click on the Submit button - which should load test2.php inside DisplayDiv - instead it just refreshes the whole page and no test2.php is loaded.
test1.php:
<html>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
function loadSubmitResults() {
$(function() {
$('#DisplayDiv').load('test2.php');
});
}
</script>
<body>
<div id="page">
<form id="SubmitForm" method="post">
<div id="SubmitDiv" style="background-color:black;">
<button type="submit" form="SubmitForm" onclick="loadSubmitResults();">Submit</button>
</div>
</form>
<div id="DisplayDiv" style="background-color:red;">
<!-- This is where test2.php should be inserted -->
</div>
</div>
</body>
test2.php:
<html>
<meta charset="utf-8">
<body>
<div id="page" style="background-color:yellow;">
<?php
echo "Hello World.";
?>
</div>
</body>
</html>
If this were something I was working on, I'd change:
<button type="submit" form="QueryForm" onclick="loadQueryResults();">Submit Query</button>
to
<button type="submit" form="QueryForm" onclick="return loadQueryResults();">Submit Query</button>
Then I'd change your loadQueryResults function to:
function loadQueryResults() {
$('#DisplayDiv').load('test2.php');
return false;
}
What this is doing is then returning the value of false to the onclick of the button which as a type of "submit" will, by default, submit the form. Returning any false value on a form submit will cause the form to not submit. Returning false is a general rule when trying to prevent default events from running.
The structure here is a little strange:
function loadQueryResults() {
$(function() {
$('#DisplayDiv').load('test2.php');
});
}
You're declaring a function, but inside of that function you call the jQuery function and pass it a function with the code you want to run? Normally the latter is for running something when the document is ready. It shouldn't be needed here. My guess is that this inner code (the one line you want to run) never actually gets executed.
Does a simpler version like this work for you?:
function loadQueryResults() {
$('#DisplayDiv').load('test2.php');
}
This should just run the code you want when the function is called, without the various decorations of the jQuery function.
For good measure, you should also return false to try to prevent the default submit action:
function loadQueryResults() {
$('#DisplayDiv').load('test2.php');
return false;
}
You can further improve this by using a selector in the call to .load() to pick out only the parts of the DOM that you want. Things like html and body might be stripped out automatically, but explicitly doing things is better than guessing:
$('#DisplayDiv').load('test2.php #page');
Of course, now you're also in a situation where you may end up with multiple elements of the id page in the same DOM, which is invalid. You may want to consider changing some of your ids.
The best way to do this is with the code below:
test1.php:
<html>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
// Handler for .ready() called.
$('#SubmitForm').submit(function( event ) {
$.ajax({
url: 'test2.php',
type: 'POST',
dataType: 'html',
data: $('#SubmitForm').serialize(),
success: function(content)
{
$("#DisplayDiv").html(content);
}
});
event.preventDefault();
});
});
</script>
<body>
<div id="page">
<form id="SubmitForm" method="post">
<div id="SubmitDiv" style="background-color:black;">
<button type="submit" class="btnSubmit">Submit</button>
</div>
</form>
<div id="DisplayDiv" style="background-color:red;">
<!-- This is where test2.php should be inserted -->
</div>
</div>
</body>
test2.php:
<div id="page" style="background-color:yellow;">
<?php
echo "Hello World.";
?>
</div>

PHP value inside JavaScript

The following code works fine, the function load() sends the selected radio button info to the PHP page and display the returned:
<head>
<script>
$(document).ready(function(){
$('#myButtons input:radio').change(function() {
var buttonValue = $("#myButtons input:radio:checked").val();
$("#myDiv").load('myPHPfile.php', {selectedButtonValue : buttonValue});
});
});
</script>
</head>
<body>
<div id="myButtons">
<input type="radio" name="category" value="10" />ButtonA
<input type="radio" name="category" value="20" />ButtonB
<input type="radio" name="category" value="30" />ButtonC
</div>
<div id="myDiv">Click the button to load results</div>
</body>
myPHPfile.php
<?php
if( $_REQUEST["selectedButtonValue"] )
{
$buttonPHP = $_REQUEST['selectedButtonValue'];
echo "Value button is ". $buttonPHP;
}
?>
I need an alert box message of the returned PHP value, inside the script, as follows:
;
$("#myDiv").load('myPHPfile.php', {selectedButtonValue : buttonValue});
alert(<?php $buttonPHP ?>);
;
Would it be possible to write the PHP value inside JavaScript?
You can just add a callback function in .load(), like this:
$("#myDiv").load('myPHPfile.php',
{selectedButtonValue : buttonValue},
function(data){
alert(data);
});
If you only want the value of the $buttonPHP to be displayed in the alert, change your echo to
echo $buttonPHP;
instead of
echo "Value button is ". $buttonPHP;
*Note: There is an issue with .load() function. It will not work if you access your html page locally/directly, you need to put it on a server. Or you can use xampp, wampserver, etc. *
Hope it helps.
Yes, almost had it:
alert('<?php echo $buttonPHP; ?>');
Your doing it right now, but you need to output the value:
alert(<?php echo $buttonPHP ?>);
On a sidenote, it seems like you don't have it really clear to you what happens.
HTML, css and javascript runs on the clients(the visitors) computer and the PHP code runs on the server, that means that the you can always combine php output with client-side code, and this is done regularly, just as you have done.
This is also one of the reasons why PHP is so flamed as a language, because of it low threshold to get started with, it is way to easy to create code that works, but that is a hell to maintain.
This is not a comment to your code, but a general reflection on php.
Either, you have to put the alert in the PHP generated code:
echo "<script type=\"text/javascript\">alert('Value button is ". $buttonPHP . "');</script>";
Or you have to use $.get function:
$.get('myPHPfile.php', {selectedButtonValue : buttonValue}, function(data) {
alert(data);
});

passing variables w/o using <form>

<a href='new.php?logi_jo=$_POST[jo]'>submit</a>
<input type='text' style='width:50px' name='logi_jo'>
is there a way of getting the the value of logi_jo and pass it to another web page? w/o using <form>
the first line of code is the link. and the the 2nd line of code is the textbox.. and then the value of that textbox will pass to another page w/o using form action. I decide to not use form action="??" because that link is inside of a form.. thank you for reading
you can do this simple task via javascript, ajax isn't necessary.
Your HTML
<a href='javascript:void(0)' onclick='submitMe()'>submit</a>
<input type='text' style='width:50px' name='logi_jo' id='logi_jo'>
Your javascript
<script type="text/javascript">
function submitMe(){
var val=document.getElementById("logi_jo").value;
document.location.href="new.php?logi_jo="+val;
}
</script>
in news.php page fetch variable by $_GET["logi_jo"]
AJAX to the rescue!
var logi_jo = $('input[name=logi_jo]');
$.post(
'test.php',
{ logi_jo: logi_jo },
function(data) { // do something to the DOM }
);
i suggest to begin with this:
http://www.w3schools.com/jsref/obj_location.asp

Categories