i want to create a button in html that runs a php script,
i have this script:
<?php
$user = JFactory::getUser();
$userToken = JSession::getFormToken();
if (!$user->guest) : ?>
Log out
and i want to use it in a html button
any help?
call a js function onclick of your button and send ajax request on your script file to run php script...
<input type="button" value="Run Script" onclick="run_script();"/>
<script>
function run_()
{
$.post("yourScripFile.php",function(data){
if(data != null)
{
alert(data);
}
});
}
</script>
And in your php script file
<?php
$user = JFactory::getUser();
$userToken = JSession::getFormToken();
if (!$user->guest)
{
echo 'Log out';
die;
}
else
{
echo "else code here"; die;
}
?>
You can use a $_POST or $_GET parameter and pass it with the click of the button. Just put the script in an if block in the same page if($_GET['act'] == "logout"){//run script} and add ?act=logout to your url when you want to trigger the script. Instead of $_GET you can use $_POST and a hidden input named act
Related
I've got a simple jQuery function and at a certain point (let's say on a button click) I'd like to start a PHP session.
$(document).ready(function() {
$(".loginPopupButton").click(function(){
//here I'd need a way to trigger the session.
});
});
I would assume starting a session from PHP can be done as easily as changing a PHP variable. For example - the PHP can be something like:
<?php
$testVar = null;
if(isset($testVar)){
session_start()
$_SESSION['sessionStarted'] = $testVar;
}
?>
Is there a way for such as session to be started?
<?php
session_start();
if(isset($_GET['login'])) {
if(isset($_SESSION['sessionStarted'])) {
echo 'session is already set';
} else {
$_SESSION['sessionStarted'] = $testVar;
}
}
?>
and client-side:
$(document).ready(function() {
$(".loginPopupButton").click(function(){
//code to redirect to index.php?login=true or make some ajax GET call, doesnt matter
});
});
then you can add like php checks, if session exists, do not echo loginPopupButton and so on :)
I have a php script, only for learning purposes. I would like to use on my web app ajax form. Never did it, this is testing php script. So I would like to send via ajax form name and password, in php script will be checked if its correct and it will return either success(when login and password correct) or error(when no match). My problem is how to send it and receive it correctly in js or jQuery. Anyone who could help me maybe with better idea and/or better secure function of doing this?
I found on stackoverflow and tryed this script:
//bind an event handler to the submit event for your login form
$('#login_form').live('submit', function (e) {
//cache the form element for use in this function
var $this = $(this);
//prevent the default submission of the form
e.preventDefault();
//run an AJAX post request to your server-side script, $this.serialize() is the data from your form being added to the request
$.post($this.attr('action'), $this.serialize(), function (responseData) {
//in here you can analyze the output from your server-side script (responseData) and validate the user's login without leaving the page
});
});
And I was wondering if in php script it could work like this?:
<?php
$username = $_GET["name"];
$password = $_GET["password"];
if($username="*****" && $password==********)
{
header('Location:http://*****************/jaz/imes/index.html?login="success"');
}else{
header('Location:http://*****************/jaz/imes/index.html?login="error"');
}
?>
And as I said this is just a test script just for learning more about it.
First of all, try to use on() method if you're using jQuery 1.8+
Another thing is that you should set the session for that user in the PHP script, then redirect the user using the js:
jQuery:
$('#login_form').on('submit', function(){
$.post($this.attr('action'), $this.serialize(), function (responseData) {
if(responseData == 'success'){
window.location = "userpanel.php"
}else{
alert('NO MATCHES');
}
});
});
PHP:
<?php
$username = $_POST['username'];
$password = $_POST['password'];
// VALIDATING HERE, in db maybe?
if($username == 'blah' && $password == 'blah'){
$_SESSION['username'] = $username;
echo "success";
}else{
echo "failed";
}
?>
And in your HTML form you need to have 2 inputs with IDs as "username" and "password" so the above code could work.
I have a session variable that is set when the user submits a form with a certain option selected. When the page refreshes I need to test this session variable and if it exists then make some of the form read only. This is my code so far, php:
<?php
require("header.php");
if(isset($_REQUEST['searching'])){ //check if form has been submitted
echo"<h2>Submitted</H2><p>";
connect('final');//connect to DB
$fName = $_POST['addFname'];
$lName = $_POST['addLname'];
$address = $_POST['address']
$dropdown = $_POST['field']; // yes or no option
$fName = htmlspecialchars($fName);
$fName = mysql_real_escape_string($fName);
$lName = htmlspecialchars($lName);
$lName = mysql_real_escape_string($lName);
$address = htmlspecialchars($line2); // stop HTML characters
$address = mysql_real_escape_string($line2); //stop SQL injection
if($dropdown== "no"){
$_SESSION['name'] = "$fName";
}
?>
'field' is the name of my dropdown with 2 options yes and no.
MY JS for getting the variable:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type = "text/javascript">
var session;
function multi(){
$.ajaxSetup({cache: false})
$.get('getSession.php', {requested: 'foo'}, function (data) {
session = data;
});
}
</script>
I use that to get the variable from the session, getSession.php has the following:
<?php
session_start();
if (isset($_GET['name'])) {
// return requested value
print $_SESSION[$_GET['name']];
} else {
print json_encode($_SESSION);
}
?>
finally I have this function to disable the text fields
<script language="JavaScript">
<!--
function enable_text2()
{
if (session !=""){
status = "true";
document.add.addFname.readonly=readonly;
document.add.addLname.readonly=readonly;
}
}
//-->
</script>
the rest of my html is just a form, this is all in one document with the php code at the top, and the javascript functions in the head tag.
I call a wrapper function in the body onload tag, which then calls both of those functions, I thought the first function would get the session variable if it existed from the php document and then the second function would test if it was not empty, if it wasn't then it would make the fields read only.
However when I select no in the drop down and submit the form, the page refreshes and nothing happens, the fields are not read only.
Why You are using javascript for it??
session_start();
if (isset($_GET['name'])) {
$disable=true;
} else {
$disable=false;
}
<input type="text" name="addFname" <?php if($disable) { ?> readonly="readonly" <?php } ?>
Here i have taken "addFname" .you can disable any element inside that php if condition
Assuming PHP is generating the page you've got this "must be disabled" form on, there's no need for an ajax call - PHP can output a JS variable when it builds the page, e.g.
<script type="text/javascsript">
var disableForm = <?php echo (($_SESSION['somevar'] == 'whatever' ? 'true' : 'false') ?>;
if (disableForm) {
...
}
</script>
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>';
}
//this is in php.
function msgbox($msg, $type)
{
if ($type == "alert")
{
// Simple alert window
?> <script language="JavaScript"> alert("<? echo $msg; ?>"); </script> <?
}
elseif ($type == "confirm")
{
// Enter Confirm Code Here and assign the $result variable for use
// Should include "OK" and "Cancel" buttons.
?>
<script language="JavaScript">
if (confirm("<? echo $msg; ?>"))
{
<? $result == "ok"; ?>
}
else
{
<? $result == "cancel"; ?>
}
</script>
<?
}
}
if ($page_title->exists())
{msgbox("page exists,do you want to delete", "confirm");
}
if ($result == "ok")
//code..
The problem is that $result is not reading the value from the confirm box i think because the if clause is not being executed and the program flow is going where it would go without the if clause.
You have to understand when is your PHP and JavaScript code executed. First the server runs your PHP code. This generates HTML output, that gets passed to your browser and the browser executes the JavaScript code. This means that when you run confirm() in JavaScript, your PHP code is already finished (and probably serving another request).
You will need to rethink the user interaction.
(Btw, JSP means Java Servlet Pages, not JavaScript)