Call PHP function on click of a html button - javascript

I would like to call a php function after clicking a button.
I already found a way to do this (kind of).
This is my code:
info.html
<html>
<head>
</head>
<body>
<input type=button value="test" onClick="self.location='http://127.0.0.1/info.php?runFunction=main'">
</body>
</html>
info.php
<?php
if(isset($_GET['runFunction']) && function_exists($_GET['runFunction']))
call_user_func($_GET['runFunction']);
else
echo "Function not found or wrong input";
function readCSV($csvFile){
$file_handle = fopen($csvFile, 'r');
while (!feof($file_handle) ) {
$line_of_text[] = fgetcsv($file_handle ,1024,";");
}
fclose($file_handle);
return $line_of_text;
}
function main($csvFile){
//Set path to CSV File
$csv = readCSV($csvFile);
echo '<pre>';
print_r($csv);
echo '</pre>';
}
?>
My button is able to call the main function, but I do not know how to pass on a variable with a button click, could anybody help me with this?

You could pass the argument as another URL parameter:
<input type=button value="test" onClick="self.location='http://127.0.0.1/info.php?runFunction=main&arguments[]=File.csv'">
Then the PHP would be:
if(isset($_GET['runFunction']) && function_exists($_GET['runFunction'])) {
if (isset($_GET['arguments'])) {
$args = $_GET['arguments'];
} else {
$args = array();
}
call_user_func_array($_GET['runFunction'], args);
} else {
echo "Function not found or wrong input";
}
Putting [] after the parameter name in the URL tells PHP to collect all the parameters with this same name into an array.
However, this is extremely dangerous, since it allows someone to execute any PHP function. Someone could connect to a URL like info.php?runFunction=unlink&arguments[]=.htaccess.
You should check the function name against a list of allowed functions to call.

You have to make a AJAX call. You can pass any arguments in that via GET or POST method. AJAX is simplest way to do this.

Change
<input type=button value="test" onClick="self.location='http://127.0.0.1/info.php?runFunction=main'"
to
<input type=button value="test">

You should use Ajax to send data to the server
<script>
function sendData(){
var data1 = "Hello";
var data2 = "World";
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
alert(xmlhttp.responseText);
}
xmlhttp.open("GET", "ajax.php?data1=" + data1 + "&data2=" + data2, true);
xmlhttp.send();
}
</script>
You call the sendData function, when the button is clicked:
<input type=button value="test" onClick="sendData()">
The server reads the GET-Parameter
if(isset($_GET['data1']) && isset($_GET["data2"])){
$data1 = $_GET["data1"];
$data2 = $_GET["data2"];
return $data1 . " " . $data2 . " was sent to the server";
}

Related

Javascript and PHP in one file (form handling and XMLHTTPRequest)

I am confused about my homework requirements: we need to put JS, HTML and PHP code in the same file xxx.php.
There is a form in the HTML, and once I submit the form, I need to send a request (XMLHTTPRequest) to myPHP.php with the form inputs (using POST to transfer the form data PHP). The PHP file will retrieve the form inputs, reformat it to the syntax of the API and send it to the Google API to get JSON object.
I am a beginner of PHP and JS, and I don't know how to combine them in the same file and do the homework based on the requirements. Like, how to send the JSON object obtained in PHP to Javascript.
Here is framework of my code (myPHP.php):
<html>
<head>
<script type="text/javascript">
// show the result
function show() {
var xmlhttpreq = new XMLHttpRequest();
var keyword = document.getElementById("keyword").value;
var post_data = "keyword=" + keyword;
xmlhttpreq.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var jsonObj = JSON.parse(this.responseText);
createTable(jsonObj);
}
};
xmlhttpreq.open("POST", "myPHP.php", true);
xmlhttpreq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttpreq.send(post_data);
}
function createTable(object) {
var out = "xxx";
document.getElementById("display").innerHTML = out;
}
</script>
</head>
<body>
<div id="display"></div>
<form action="myPHP.php" name="myForm" method="POST">
<b>Keyword </b><input type="text" id="keyword" name="keyword">
<br>
<button type="submit" onclick="show()" name="search">Search</button>
</form>
<?php
if (isset($_POST["search"])) {
// extract the form data
$keyword = $_POST["keyword"];
// geocode the address
$location = urlencode($location);
// google map geocode api url
$url = "xxxxxxxx";
$res_json = file_get_contents($url);
echo $res_json;
}
?>
</body>
</html>
You can try something like this:
<?php
if (isset($_POST["search"])) {
// extract the form data
$keyword = $_POST["keyword"];
// geocode the address
$location = urlencode($location);
// google map geocode api url
$url = "xxxxxxxx";
echo file_get_contents($url);
} else {
echo '<html>
<head>
<script type="text/javascript">
// show the result
function show() {
var xmlhttpreq = new XMLHttpRequest();
var keyword = document.getElementById("keyword").value;
var post_data = "keyword=" + keyword;
xmlhttpreq.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var jsonObj = JSON.parse(this.responseText);
createTable(jsonObj);
}
};
xmlhttpreq.open("POST", "myPHP.php", true);
xmlhttpreq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttpreq.send(post_data);
}
function createTable(object) {
var out = "xxx";
document.getElementById("display").innerHTML = out;
}
</script>
</head>
<body>
<div id="display">
<?php echo $result; ?>
</div>
<form action="myPHP.php" name="myForm" method="POST">
<b>Keyword </b><input type="text" id="keyword" name="keyword">
<br>
<button type="submit" onclick="show()" name="search">Search</button>
</form>
</body>
</html>';
}
?>
You first have to test in myPHP.php if there is some data send. If so, the form already has been display and the browser is sending the form data back. If not, it is the first time the php-page is loaded and you can display the html and javascript.
So:
<?php
//test if there is data from the form
if( isset( $_POST['some-form-variable'] ) ){
// YES
// process data an display something
}
else{
// NO DATA
// display form and javascript
}

Pass div id into PHP variable

I have passed a javascript variable into a div id element in HTML. I am now trying to send that div id to a php variable so I can access it.
However, when I try a POST request it is not grabbing what is assigned to div id. Any help is appreciated, thanks.
<?php
session_start();
$un = $_POST["result"];
echo "the username is". $un;
?>
<!DOCTYPE html>
<html>
<body>
<div id="result"></div>
<script>
if (typeof(Storage) !== "undefined")
{
var getUser = document.getElementById("result").innerHTML = sessionStorage.getItem("username");
}
else
{
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
</script>
</body>
</html>
First of all, to make a post request you'll need to be using XMLHttpRequest. You really should be using a GET request in a separate file, though.
PHP file, named getId.php:
<?php
session_start();
$_SESSION["id"] = $_GET["id"];
?>
JavaScript code, to retrieve data:
var getData = function( url, callback ) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
callback(xhr);
};
xhr.open( "get", url, true );
xhr.send();
};
getData('./getId.php?id=' + /* id goes here */, function(json){
if(json.status == 200){
data = json.response;
//Do something with data...
}
})
And finally, to reference the session data, back in the HTML file:
<?php
session_start();
echo "value of username is: " . $_SESSION["id"];
?>

Javascript code not working on PHP include

So I have a main page which have buttons, each buttons contain names, when I click that button I want to pop up div which shows information of that person, I used ajax to retrieve info from php,
var strURL="searchSender.php?ID="+ID;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
outMsg=req.responseText;
var prevWin = document.getElementById("senderInfo");
prevWin.innerHTML = outMsg;
prevWin.style.top = 50+"px";
prevWin.style.right = 80+"px";
prevWin.style.visibility = "visible";
} else {
alert("Problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
searchSender.php basically redeem info of that specific person from the database, that returns these codes (i didn't include here the code that retrieves data from database)
<label>Name: <?php echo $row['Name'];?> </label></br>
<label>Address: <?php echo $row['Address'];?></label></br>
<label>Contact: <?php echo $row['ContactNumber'];?></label></br>
<div id="divSenderMap">
<?php
$url = "mapSender.html";
$_SESSION['SenderID'] = $row['ID'];
include $url ?>
</div>
<input type="button" id="btnSendReply" value="SEND"/>
<input type="button" id="btnCloseDiv" value="X" onclick="closeDiv()"/>
mapSender.html is supposed to return a map where the person is, the code is working on any other file/page, but it does not do it here. It is returning php and html codes but not javascript codes. What could be wrong?
As #MichaelLonghurst told it seems your file is named mapSender.html. So the server does not call PHP before return the HTML.
You should rename mapSender.html into mapSender.php.

Ajax. Sending data to php file

Good day, I'm trying to use Ajax in my web application. But I have a little problem with it. I try to control a form if some username has already been registered or not. But my JavaScript seem does not send $_POST value to PHP. And responses that user in not defined on the line where I have $_POST['user'].
Here what I have.
PHP:
<?php
$opt = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
$dsn ='mysql:dbname=someone;host=127.0.0.1;charset=utf8';
$user='someone';
$pswd='aaa';
$dbh = new PDO($dsn, $user, $pswd, $opt);
$query="SELECT 1 FROM users WHERE username = :username";
$query_p=array(':username' => $_POST['user']);
try
{
$statment = $dbh->prepare($query);
$result = $statment->execute($query_p);
}catch(PDOException $e)
{
echo "Can't run query: " . $e->getMessage();
}
$row = $statment->fetch();
if($row){
return 0;
}else {
return 1;
}
?>
So it opens a connection to database and runs a query
JavaScript:
function checkUser(e){
var state1 = document.getElementById("alert_text");
var u = document.getElementById("user").value;
if(u != ""){
state1.innerHTML = 'processing...';
var request = new XMLHttpRequest();
request.open("POST", "validation.php", true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
var result=request.responseText;
alert(result);
if(result==1){
state1.innerHTML="OK";
}else{
state1.innerHTML="Alredy exists!";
}
}
};
request.send(u);
var slova = request.responseText;
}
}
document.getElementById("user").addEventListener("blur",checkUser,false );
So technically it is ajax.
HTML:
<form id="check" name="signUp" method="post">
<p class="alert_text"></p>
<label for="user">Username:</label><br />
<input id="user" name="user" type="text" ><br />
</form>
I don't really see what's the problem...
You're not passing the username into the PHP script. Your PHP is looking for a POST variable, $_POST['user'] – in your JavaScript you make a GET request, so the PHP script has nothing to look up.
Based on the edited question: You are not sending any key-value pairs to the server, just a single value.
You need to change:
var u = document.getElementById("user").value;
to:
var u = 'user=' + encodeURIComponent(document.getElementById("user").value);
And then later on the pair will be sent correctly:
request.send(u); // sends a single key-value pair
Note that I have just added the encodeURIComponent function to make sure the value gets encoded correctly.

AJAX call to php not working

I'm working on AJAX programming in which I have a little problem. In the below code, I think my php script is not echoing back success. I'm trying to insert values into my database table. Accordingly, the values are getting inserted into the table. I have a span element on my page which by default shows nothing. But if the php script is echoing back success, it must show "AJAX worked". If my PHP script is not echoing back "success", it must show "AJAX didn't work". But it is showing "AJAX didn't work" though the values are getting inserted. If I didn't include the database code, then my script is echoing back success and the span element is showing "AJAX worked". But if I include database code, I think it is not echoing back success and the span elemnt is showing "AJAX didn't work". Below is my code:
<head>
<meta charset="UTF-8">
<title></title>
<script src="js/main.js"></script>
<script src="js/ajax.js"></script>
<script>
function insert(){
var elem = _("myTextArea").value;
var result = _("result");
result.innerHTML += elem + "<br>";
elem.value = "";
var ajax = ajaxObj("POST", "dynamicdiv_parser.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "success"){
_("status").innerHTML == "AJAX worked";
}
else{
_("status").innerHTML == "AJAX didn't work";
}
}
}
ajax.send("post="+elem+"&type=a");
}
</script>
</head>
<body>
<form name="dynamicdivform" id="dynamicdivform" onsubmit="return false;">
<p id="result"></p>
<textarea name="myTextArea" id="myTextArea" cols="100" rows="14"></textarea><br>
<input type="button" id="postBtn" value="POST" onClick="insert()">
<span id="status"></span>
</form>
</body>
I have included two JavaScript files in my program which are main.js and ajax.js. Below is their code.
This is main.js:
function _(x){
return document.getElementById(x);
}
This is ajax.js:
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
This is my PHP script which is echoing back success
<?php
if(isset($_POST["post"])){
include_once("php_includes/dbconsampledb.php");
$data = $_POST['post'];
$type = $_POST['type'];
$sql = "INSERT INTO posts(data, type)
VALUES('$data','$type')";
$query = mysqli_query($db_conx, $sql);
echo "success";
}
?>
Before posting this question, I have tried the works but I didn't find any solution. This is very important to me. So please can anyone debug it and tell me what the problem is... Thanks in advance!!
_("status").innerHTML == "AJAX worked";
should be
_("status").innerHTML = "AJAX worked";
with one = only
My suggestion is to use a console.log() for debuging your ajax response.
if(ajaxReturn(ajax) == true) {
console.log('Response: ', ajax.responseText);
if(ajax.responseText == "success"){
Probably there is some errors with DB functionality.

Categories