Call php function on click of a button - javascript

I am trying to call a php function on click on a button using Javascript. It does not seem to be working fine.
Is there a better way to call php function on click of a button
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function executeShellScript(clicked)
{
var x="<?php ex(); ?>";
alert(x);
return false;
}
</script>
</head>
<body>
<input type="button" id="sample" value="click" onclick="executeShellScript()"/>
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
function ex(){
echo "Trying to run shell script from the web browser";
echo "<br>";
$contents = file_get_contents('/var/www/shellscriptphp/helloworld.sh');
echo shell_exec($contents);
$result = shell_exec('sh /var/www/shellscriptphp/helloworld.sh');
echo $result;
}
?>
</body>
</html>

You cannot invoke a php function just like the way you have explained above. Because php script executions happen before the source of the webpage is sent to the client browser from the server.
However you can do it via an ajax call in which you invoke a client side side js function onclick of the button and and that function inturn makes an ajax call to a server side page and returns the result back.
example:
Here is a sample code which you may refer. This page makes a POST ajax request to itself and gets the response back. Let me know incase of errors as i havent run it here.
<?php
/** this code handles the post ajax request**/
if(isset($_POST['getAjax'])) {
/* you can do this below settings via your php ini also. no relation with our stuff */
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
/* setting content type as json */
header('Content-Type: application/json');
$result = shell_exec('sh /var/www/shellscriptphp/helloworld.sh');
/* making json string with the result from shell script */
echo json_encode(array("result"=>$result));
/* and we are done and exit */
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.1.js" type="text/javascript"></script>
<script type="text/javascript">
function executeShellScript(clicked)
{
//$_SERVER["REQUEST_URI"] is used to refer to the current page as we have the ajax target as this same page
$.post('<?PHP echo $_SERVER["REQUEST_URI"]; ?>',{"getAjax":true}, function(data) {
alert(data['result']);
return false;
});
}
</script>
</head>
<body>
<input type="button" id="sample" value="click" onclick="executeShellScript()"/>
</body>
</html>

Related

Javascript function triggers on page refresh

I have a hyperlink and clicking on that link will run a JavaScript function. I also have a PHP variable $counter. Inside the JavaScript function, the value of $counter is increased by 1 i.e., $counter++. It works fine. But the same function also runs whenever the page is refreshed. So the value of the $counter is increased by 1 whenever the page is refreshed. I tried all the solutions available on the net like preventDefault(), clickevent handler etc., But nothing works. Please help to fix this. In the below code, I have set $counter as 0. But it loads with 1 as output. I want it to count only when the hyperlink is clicked. Here is my sample code.
<?php
session_start();
require("dbconfig.php");
$counter=0;
?>
<html>
<head>
<script>
function onclick() {
<?php
$counter++;
?>
}
</script>
</head>
<body>
link text
</body>
<?php
//tracing counter value
echo $counter;
?>
</html>
TL;DR:
You can't mix PHP and JS code expecting that JS function will execute PHP code.
First PHP prepares output to browser, then Browser parses your JS and HTML. JS never knows about PHP code.
Click CTRL+U to view source as browser sees it - there is no PHP code.
JS function is not run on page refresh. PHP code is run on page refresh.
First goes PHP parser:
session_start();
require("dbconfig.php");
$counter=0;
$counter++;
echo $counter;
Then goes JS/Html parser.
At this point your JS code looks like this:
function onclick() {
}
Content of function is empty because you output nothing from PHP side.
To fix it move PHP var to JS var:
<?php
session_start();
require("dbconfig.php");
$counter=0;
?>
<html>
<head>
<script>
var jsCounter = <?= $counter; ?>
function onclick() {
jsCounter++;
console.log(jsCounter);
}
</script>
</head>
<body>
link text
</body>
</html>
Note never output after closing body tag.

Ajax query not working

I have spent some time looking at examples of Ajax, sending a variable to PHP and getting back a different variable. This is from another page (how to get variables from php using AJAX) but it seems something is not working for me. I do not get an error, just no actions appear to happen. My goal is to simply post some data to the php page and get variables back and put them in different DIVs.
htmlpage.html
<html>
<head>
<script>
$(document).ready(function() {
$("#ajaxButton").click(function() {
$.ajax({
url:'phppage.php',
data:{username: $('#username').val()},
type:'POST',
success: function(data) {
$('#result').html(data);
}
});
});
});
</script>
</head>
<body>
<input type="text" name="username" id="username"/>
<input type="button" value="Find" id="ajaxButton"/>
<div id="result">This should change on click</div>
</body>
</html>
phppage.php
<?php
$_POST['username'];
$username = $_POST['username'];
$result = '<div class="result">' .$username. "</div>";
echo $result;
?>
It is the whole scripts of yours? If it is, I think that you don't import the jquery in your frontend scripts
Please add the jquery in your code, for example :
<script src="http://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>

Opening url retrieved with PHP inside Javascript

Need to open $link with javascript, that is retrieved from an XML file using PHP. Here's the code:
<?php
$url = "map.xml" ;
$xml = simplexml_load_file($url);
$link = $xml->url[mt_rand(0,count($xml->url)-1)]->loc ; // Get Random Location
?>
<html>
<head>
<title></title>
</head>
<body>
<script>
$(document).ready(function(){
window.open($link, "_blank"); // will open new tab on document ready
});
</script>
</body>
</html>
You cannot access php variables from javascript. With php you can render html and javascript on server. So you need to print your $link variable to the page:
window.open("<?= $link ?>", "_blank");
Note that short echo tag <?= is only guaranteed to be available on php 5.4+, if you are stuck supporting an older version use <?php echo instead

how to convert javascript variable to php variable in the same file

I have file named test6.php having javascript variable i need to convert this variable to php variable but when i run it give me an e error (PHP Notice: Undefined index: variable in /Applications/MAMP/htdocs/test6.php on line 14)
<!doctype html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
var variableToSend = 'foo';
$.post('test6.php', {variable: variableToSend});
</script>
</head>
<body>
<?php
$x = $_POST['variable'];
echo $x;
?>
</body>
</html>
note that i have only one file (test6.php) containing javascript code and php code and i am trying to convert javascript variable to php variable in the same file and i need to use post not get or submit form
Why error
you should know the processing of a php file rendering from the server to the client , it is :
1. client request the page
2. PHP parser (in server) -> php 2 HTML -> send to client
2. web browser load HTML
3. JavaScript running ~
so you can't get variable of "variable" when you run your php file . Becuase Js has not been running ~ . you should print the value of php echo at JS after ajax .
how about change the JQuery code
$.post('test6.php', {variable: variableToSend});
to
$.post('test6.php', {variable: variableToSend} ,
function(returnValue){
console.log(returnValue) ;
});
I think it will be ok , but i am sorry i can't test it ~
Check to see if it is set before you output it
<?php
if( isset($_POST['variable']) ) {
$x = $_POST['variable'];
echo $x;
}
?>
But I do not think this is what you actually want. The Ajax call is not going to update the current view.
Bring the php section to the top and use isset($_POST['variable']) to check if the variable exist or not.
<?php
if( isset($_POST['variable']) ){
$x = $_POST['variable'];
echo $x;
return;
}
?>
<!doctype html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
var variableToSend = 'foo';
$.post('test6.php', {variable: variableToSend});
</script>
</head>
<body>
</body>
</html>

AJAX / PHP Reload a part of a page

I have made a RESTful API in PHP. To do shortly, I can register some information by calling an address like http://api.website.com/addInfos
This request is a POST request. Here my method:
File: api.php
<?php
/* Page api.php */
private function addInfos()
{
// Check if it's a POST request and if all fields are correct
// Insert data in my MySQL database
// TODO: make an automatic refresh for page named infos.php
}
?>
Second file, where the data are displayed from my database:
File: infos.php
<?php
/* Page infos.php */
// Connection to database
// Prepare the request using PDO
// Execute the request
// Display infos in a while loop
?>
My question is: How can I refresh the part of code where the data is displayed just after the function named "AddInfos" of my API is called ?
EDIT 1:
Here is what I can do:
File: index.php
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<title></title>
<script src="js/jquery.js"></script>
</head>
<body>
<div id="infos"></div>
<script>
function displayInfo(r) {
$.post("infos.php",
{ refresh : r},
function(data){
//alert("Data Loaded: " + data);
$("#infos").html(data);
}
);
}
$(document).ready(function() {
displayInfo(1);
$('a.info_link_text').click(function(){
alert($(this).text());
});
});
</script>
</body>
</html>
File: infos.php
<?php
require_once('database.php');
if(isset($_POST['refresh'])){
$selectInfos = getAllInfos();
$selectInfos->execute();
echo "<table>";
echo "<th>User</th>";
echo "<th>Email</th>";
while($row = $selectInfos->fetch(PDO::FETCH_OBJ)){
$fullname = $row->user_fullname;
$email = $row->user_email;
echo "<tr>";
echo "<td>".$fullname."</td>";
echo "<td>".$email."</td>";
echo "</tr>";
}
echo "</table>";
}
?>
When I load index.php, I can get the infos from the page infos.php. But I really don't know how can I do this when the method "addInfos" of my API is called, because I need to make a POST request on infos.php (it's OK) but put the result data on index.php (not ok, I don't know how to do that). Please, could you let me know how to achieve this ?
Thank you so much for your help.
Best regards,
Lapinou.
I think what you need is a library based on WebSocket HTML5. The server can retain and send notifications to all clients connected at the same time. Then in your javascript handler, you can process anything you want.
In PHP, you could try these examples WebSocket HTML5 PHP on Google
The other way would be to send multiple REST queries on a regular basis to the server to update your page, but it seems you want real-time updates only.

Categories