Trigger PHP function by clicking HTML link - php

Is it possible to trigger a PHP function by just clicking a link? Or should I stick with the form submit method? If clicking the link will work, where should the link refer to?
Here is a sample code:
<?php
session_start();
function listMe($username){
$username = mysql_real_escape_string($username);
$query = mysql_query("INSERT INTO List (Usernames) VALUES ('$username')") or die(mysql_error());
}
?>
<html>
<head>
<title>SAMPLE</title>
</head>
<body>
Add my username to the list
<?php
listMe($_SESSION['Username']);
?>
</body>
</html>
Maybe someone can point me in the right direction. Thanks!

You can do this by means of loading the entire page over again by the use of form submission, or by loading specific page contents directly into the page without needing to go from page to page. The second method is called "AJAX" (Asynchoronous Javascript and XML). Here are two examples, one of each specified.
Form submission approach
form.php
<?php
function get_users(){
}
if(isset($_GET['get_users']))
{
get_users();
}
?>
...
<form method="get">
<input type="hidden" name="get_users">
<input type="submit">
</form>
AJAX approach
ajax_file.php
<?php
function call_me(){
// your php code
}
call_me();
?>
form.html
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
// do something if the page loaded successfully
}
}
xmlhttp.open("GET","ajax_file.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
click to call function
</body>
</html>

HTML
list me
PHP
<?php
if (isset($_GET['list_me'])) listMe();

(EDIT although this works, it's a bad idea as it is. One should never read from $_GET without sanitising it first)
You can pass it as a query parameter of the link.
http://example.com/?command=listMe&username=tom
However that way everybody will be able to run the function by loading that URL
List me
and in the PHP
<?php
if( isset($_GET['list_me']) && isset($_SESSION['Username'] ) ){
listMe( $_SESSION['Username'] );
}
?>

To trigger a function on link click with php the only way I know would be to append a param in the url of the link and then listen for that
Add my username to the list
Then check for link
if (isset($_GET['function'])){
runFunction();
}
This is because php is a server side technology if you want to fire something without refreshing the page you would need to look at something like javascript

I found this code in a plugin, they have user a foreach look to trigger the action:
$actions = unset($meta[$key]);
foreach ( $actions as $action => $value ) {
echo '<li>' . '<i class="fa fa-times"></i></li>';
}

Related

Script Function how to send call to php page

Basically I want to have a button on my HTML/PHP page which will once clicked send a call to another php page which will update a value in mysql table.
<html>
<head>
<script>
src = "https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
function toggleText(button_id){
if(document.getElementById(button_id).innerHTML == "Uninstall All"){
document.getElementById(button_id).innerHTML = "Cancel Uninstall";
//ajax////////////////////
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "valueChange.php?uninstalled=1&type=all", true);
xmlhttp.send();
////////////////////////
}
}
</script>
</head>
I'm curious why this isn't working.
I had tested my toggleText function without the ajax and it changed the HTML properly.
But once I add in the ajax to visit this valueChange.php page and update an sql value it doesn't work.
I've tested the php page by itself and it properly updated the value in sql.
I've never used ajax so I'm curious if I'm doing it wrong? I thought my src = "google/ajax/jquery" was the way to install it. Or is there a library I need to install on the VPS hosting my site?
The only mistake I see in above code is just a typo. See line 3 you closed the script tag before the second attribute it should have been <script src="*link to jQuery*" ></script>
And another thing you don't need to use the jQuery library to use XMLHttpRequest() method.
The modified code:
<html>
<head>
<script>
function toggleText(button_id)
{
if(document.getElementById(button_id).innerHTML == "Uninstall All")
{
document.getElementById(button_id).innerHTML = "Cancel Uninstall";
//ajax////////////////////
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "valueChange.php?uninstalled=1&type=all", true);
xmlhttp.send();
////////////////////////
}
}
</script>
</head>

I need to grab the $_GET['loc'] that is sent via AJAX

I have an index.php page where there are 2 kinds of queries first is location and secondly the search query. I am using ajax on location query
html structure :
<ul class="dropdown">
<li>City</li>
<li>North</li>
<li>South</li>
</ul>
<form action="" method="post">
<input type="text" name="search" id="search">
</input value="submit" type="submit"/>
</form>
<div id="content_from_AJAX">
<ul id="li_start">
</ul>
</div>
The ajax.js code :
$(document).ready(function(e) {
function getLoc(param){
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("li_start").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getresult.php"+param,false);
xmlhttp.send();
}
//handle anchor clicks
$("ul#location li a").click(function(){
var loc = $(this).attr("href");
getLoc(loc);
return false;
});
});
the getresult.php code :
require ('connect_to_mysql.php');
if(isset($_GET['loc']) && empty($_GET['loc'])===false){
$loc = mysql_real_escape_string($_GET['loc']);
$query = "SELECT * FROM TB_name WHERE loc=";
}
else{
$query = "SELECT * FROM TB_name";
}
$query_run = mysql_query($query);
$count = mysql_num_rows($query_run);
if($count<1){
echo 'no result found';
}
else{
while($result == mysql_fetch_assoc($query_run)){
echo "ALL results";
}
// Here is what I want to be able o access on index.php
return $_GET['loc']
}
I want the $_GET to be accessed on index.php so I can use it to filter result on search queries on the form above ie:
"SELECT * FROM `TB_name` WHERE `keyword` LIKE '$keyword' AND `loc`='".$_GET['loc']."'"
//I need to do this on index.php not on getresult.php
And also I want the AJAX.js to send queries on getresult.php if a user clicks on the loc links if the $_POST['search'] isset.
Please help really need this project and I am starting to be so depressed X_X.. Thank you any help is appreciated alot :)
change this
xmlhttp.open("GET","getresult.php"+param,false);
to
xmlhttp.open("GET","getresult.php?loc="+param,false);
^^^^ // forgot ?loc=
then use $_GET["loc"] in your getresult.php page.
Why have you put your function in document.ready() ?
If it would be me then i would have done like this
function getLoc(param){
$.get('getresult.php',{loc:param},function(data){
//Do some stuff with data
});
}
Your code needs some rethinking. You have a dropdown with href links in it and a form that submits information (which it shouldn't if you want ajax results).
And why is your getresults.php doing a database query and then returning the GET variable back. That makes no sense, because the database query is now pointless as its results are not used for anything.
What I think you want is onClick event listeners on the dropdown, and then have an Ajax request fire on each change, the getresults.php file then does a MySQL search and returns the results of the search (not $_GET['loc'] as index.php already knows this value).
Also, use mysqli* or PDO for your database queries, the mysql* set of functions are now deprecated and prone to sql injection.

How to POST data from a field with Javascript

Hi I am trying to make a page which will use the $.post method in Javascript to post the data from a live text field through to another script when the space bar is pressed. I want the data from a the page known as index.php to be posted through another file called save.php. I want to the value of txt_a textfield to to be the value of the post varible text. How would I do this? Below is my code so far...
<html>
<head>
<script type="text/javascript">
function event_a() {
if (event.keyCode == 13) {
$(document).ready(function(){
txt=$document.getElementsByName('txt_a')[0].value;
$.post("save.php",{text:txt});
};
};
}
</script>
</head>
<body>
<form method="POST" name="" action="">
<input name="txt_a" type="text" id="txt_a" onkeypress="event_a()"/>
</form>
</body>
</html>
Thanks
This should get you started:
$(function(){
$('#txt_a').keyup(function(e){
if(e.which === 13) {
$.post('save.php',{text: $(this).val()}, function(data){
//do something with the response
});
}
});
});
And in save.php:
$text = isset($_POST['text']) ? $_POST['text'] : null;
Your javascript function should look more like this:
function event_a(event) { // event needs to be defined as arg to use.
if (event.keyCode == 13) { // ready is used to trigger code when the page is ready, not needed here
var txt=$('txt_a').val(); // assuming you are using jQuery, you can access the value like this
$.post("save.php",{text:txt});
}
}
Why are you passing variable from one file to the another? Use $_SESSION to save and retrieve the set data/variable in multiple pages .

Change value of PHP variable with AJAX

The PHP:
<?php
$mainView = "views/dashboardView.php";
?>
The HTML:
<div class="mainContent">
<?php include($mainView); ?>
</div>
I would like the click event of a button to change what view .mainContent shows and I believe AJAX can accomplish this but as yet have not been able to get it to work.
Any advice?
You would have to modify your PHP script to allow for this.
For example:
PHP:
if (isset($_POST['change']))
{
$mainView = $_POST['change'];
echo $mainView;
}
HTML & jQuery:
<button id="change">Change the var</button>
<script>
$("#change").click(function() {
$.post("file.php", {change: $(this).val()},
function (data)
{
$("#mainContent").html(data);
});
});
</script>
<script type="text/javascript>
function changePage(pageDest){
var xmlobject = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xmlobject.onreadystatechange = function (){
if(xmlobject.readyState == 4 && xmlobject.status == 200){
document.getElementById("mainContent").innerHTML = xmlobject.responseText;
}
else{
document.getElementById("mainContent").innerHTML = 'Loading...';
}
}
xmlobject.open("GET",pageDest,true);
xmlobject.send();
}
</script>
<div class="mainContent" id="mainContent">
Change this HTML
</div>
<div onmouseup="changePage('views/dashboardView.php')">Get dashboard view</div>
The parameter in the changePage function is the location of the page that you would like to place in your mainContent <div>
Does this help?
You cannot change the value of a PHP variable, as PHP is Server Side (done first), and JS is Client Side (done after Server Side).
Typically AJAX is used to repopulate an area of a web page, but that would suit your purpose. In the example below, ajax/test.php is the new file you want to include. Obviously change the path/name as you wish, and create that file.
I will add though, if you are repopulating a large chunk of your page, it will probably be just as quick to fully reload it.
$(function(){
$('.your-button-class').on('click', function(){
$.post('ajax/test.php', function(data) {
$('.mainContent').html(data);
});
});
});
Storing the View in the session, will keep the site displaying this view until the user closes the browser and ends the session, the session expires or they change the view again.
The include that sets mainView
<?php
session_start();
$mainView = "views/dashboardView.php"; // default
if(isset($_SESSION['mainView']))
{
$mainView =$_SESSION['mainView'];
}
?>
// the ajax script that sets the mainView
<?php
session_start();
$_SESSION['mainView']='views/'.$_GET['mainView'].'.php';
?>
the javascript link for ajax
ajaxURL='ajax.php?mainView=otherDasboard';
you may also want to check for empty session variable and that the file exists before setting it

How to send javascript variable to php using ajax?

The scenario is , below is the html file through which i want to display the content of a text file at div id="myDiv".
The file will be read by php . The php content is given below.
I am unable to get the content from the text file . Please tell me what should be added in the ajax part to correct the program.
<html>
<head>
<script type="text/javascript">
function ajaxRequest(tb) {
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=statechange()
{
if (xmlhttp.readyState==4 && XMLHttpRequestObject.status == 200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://localhost/TBR/getdata.php?tb="+tb,true);
xmlhttp.send();
}</script>
</head>
<body>
<div >
<div id="myDiv">Text from file should come here.</div>
<button type="button" onclick="ajaxRequest(myfile.txt)">Change Content</button>
</div>
</body>
</html>
Below is the PHP file
<?php
$tbName = $_GET['tb'];
$file = "/home/$tbName";
$f = fopen("$file", "r");
echo "<ul>";
while(!feof($f)) {
$a= fgets($f);
echo "<li>$a</li><hr/>";
}
echo "</ul>";
?>
Fix quotes
onclick="ajaxRequest('myfile.txt')"
make sure you use encodeURIComponent() on tb
xmlhttp.open("GET","http://localhost/TBR/getdata.php?tb="+encodeURIComponent(tb),true);
Test your php page in the browser: does http://localhost/TBR/getdata.php?tb=myfile.txt provide the data you want?
If so test the function gets called. (Place an alert or debug the code and place a breakpoint within the function, or use console.debug if your browser supports it)
If the function gets called then your event handler is working correctly, if not try to rewrite it or attach it differently like onclick="ajaxRequest('myfile.txt');" though I suspect the missing semicolon isn't the problem.
If that is called you can try to see if the ajax call is carried out my inspecting the network traffic. Any decent browser will let you do that (hit f12 and look for the network tab). You should be able to see the request and response if the ajax request is being issued and responded to.
Supposing that is all working fine, ensure that your event ajax event handler is getting called. I suspect there is an issue here because you are not setting the event handler to a function...
xmlhttp.onreadystatechange = function statechange()
{
if (xmlhttp.readyState==4 && XMLHttpRequestObject.status == 200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
And failing all of that your data insert code isn't working.
<button type="button" onclick="ajaxRequest('myfile.txt')">Change Content</button>
Remember to quote the string in the onclick.
Here's a fixed version:
<html>
<head>
<script type="text/javascript">
function ajaxRequest(tb) {
if (window.XMLHttpRequest){
var xmlhttp= new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status == 200){
document.getElementById("myDiv").innerHTML=xmlhttp.responseText; }
}
xmlhttp.open("GET","http://localhost/TBR/getdata.php?tb="+ encodeURIComponent(tb),true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<div id="myDiv">Text from file should come here.</div>
<button type="button" onclick="ajaxRequest('myfile.txt')">Change Content</button>
</body>
</html>
What was wrong:
the presence of XMLHttpRequest was tested, but the function was not wrapped in an if, making that useless.
The variable names were a little mismatched - double check that
EncodeURI Component, as mentioned below
The proper syntax for a callback function is window.onload = function(){ alert('func!'); } not window.onload = alert(){ alert('load!'); }
That should be it, unless there's a problem with the PHP Script, try testing that out by visiting the URL directly.

Categories