Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Need a button 1

Status
Not open for further replies.

MikeM2468

IS-IT--Management
Apr 5, 2011
100
US
I need to create a button within a PHP script that, when clicked, takes some information from the script and runs another PHP script to perform a MySQL query and display the result in a popup window. I believe AJAX is the way to do it but I don't know where to start. I need guidance on the AJAX part.
 
Using Firebug, the response is getting back to the main script, but the alert box isn't coming up.
 
Something else I noticed. When I include the session script, firebug doesn't show a json tab. When I don't include it, the json tab is there.
 
if firebug does not show a json tab it means that it is not receiving json type data back from your server.

so there is an error somewhere that is interrupting the flow. this should be displayed in the firebug response, providing that you have properly turned on error display and output.

try navigating directly to the ajaxserver and see what output you get.
 
I get nothing when I hit ajaxserver.php directly.
 
then probably you have not got the error display and reporting set properly. triple check that. force an error in your code and make sure that something is spat out.
 
I'm definitely getting errors in the phperrors.log, just not related to this. When I enable the following I get the same errors just displayed in the output.

Code:
ini_set('display_errors', true);
error_reporting(E_ALL);
 
There is no error. None. Everything is happy as far as the log goes. I get errors for unrelated things, so I know the logs are working.
 
I see.

Can you then post the scripts verbatim (delete the passwords).

Another thing to try is to force output with some echo footprinting. It will break the json but help the debug.
 
Here they are:

formpage.php
Code:
<!DOCTYPE HTML>
<?php 
include("dbconnect.php");
require($_SERVER['DOCUMENT_ROOT'].'/user_header.php');
if (! @mysql_select_db("$database") ) {
  echo( "<P>Unable to locate the " .
        "database at this time.</P>" );
  exit();
}
?>
<html>
<head>
<meta charset="utf-8"/>
<script type="text/javascript" src="jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    /* attach event listeners to the buttons */
    $('.myButton').on('click', function(e){
        e.preventDefault();
        var id=$(this).attr('actionid');
        /* make ajax call */
        $.ajax(
                {
                    async:      false,
                    url:        'ajaxserver.php',
                    type:       'POST',
                    dataType:   'json',
                    data:       {id:id},
                    success:    function(data){
                        if(data.result == 'ok'){
                            alert(data.data);
                        }else{
                            alert('You are not authorized to view this information.');
                        }
                    }
                });
    });
});
</script>
</head>
<body>
<?php
if (isset ($_GET['id'])) {
	$voodooid 	= $_GET['id'];
}
doList($voodooid);
?></body>
</html>
<?php
function doList($id){
	$buttonFormat = '<button class="myButton" actionid="%s">Show Voodoo</button>';
    $button = sprintf($buttonFormat, $id);
    echo $button;
}
?>

ajaxserver.php
Code:
<?php 
include("dbconnect.php");
require($_SERVER['DOCUMENT_ROOT'].'/user_header.php');
if (! @mysql_select_db("$database") ) {
  echo( "<P>Unable to locate the " .
        "database at this time.</P>" );
  exit();
}
if(!isset($_POST['id'])) die('');
$id = $_POST['id'];
$allowedusers = array("bill", "john");
if (in_array($user, $allowedusers)) {
	$result 			= mysql_query("SELECT secretvoodoo from voodoo_list WHERE id = $id");
	$row 				= mysql_fetch_array($result);
	$secretvoodoo		= $row['secretvoodoo'];
	if($secretvoodoo):
		echo json_encode(array('result'=>'ok', 'data'=>$secretvoodoo));
		die;
	else:
		echo json_encode(array('result'=>'error', 'errorMessage'=>mysql_error()));
		die;
	endif;
} else {
	echo json_encode(array('result'=>'error', 'errorMessage'=>"unauthorized"));
	die;
}
?>

user_header.php
Code:
<?php
if(session_id() == '') session_start();  
// set timeout period in seconds
$inactive = 900;
// check to see if $_SESSION['timeout'] is set
if(isset($_SESSION['timeout']) ) {
	$session_life = time() - $_SESSION['timeout'];
	if($session_life > $inactive) { 
		session_destroy();
		header("Location: /login.php"); 
	}
}
$_SESSION['timeout'] = time();
if (!isset($_SESSION['user'])) {
	echo ("Unauthorized Access");
	echo ("<br />");
	echo "<META HTTP-EQUIV='Refresh' Content='0; URL=../login.php'>";
	exit();
}
$user = $_SESSION['user'];
?>

login.php
Code:
<?php
include("dbconnect.php");
if (!$connect) {
  echo( "<P>Unable to connect to the " .
        "database server at this time.</P>" );
  exit();
}
if (! @mysql_select_db("$database") ) {
  echo( "<P>Unable to locate the " .
        "database at this time.</P>" );
  exit();
}
if(session_id() == '') session_start(); 
$client_ip = $_SERVER['REMOTE_ADDR'];
// authenticate.php contains the ldap authentication function
include("authenticate.php");
// check to see if user is logging out
if(isset($_GET['out'])) {
    // destroy session
    session_unset();
    $_SESSION = array();
    unset($_SESSION['user'],$_SESSION['access']);
    session_destroy();
}
// check to see if login form has been submitted
if(isset($_POST['userLogin'])){
    // run information through authenticator function at authenticate.php
	// the authenticate function returns true if the user is authenticated
    if(authenticate($_POST['userLogin'],$_POST['userPassword'])) {
        // authentication passed
		$error = 0;
		$user = $_POST['userLogin'];
        header("Location: /index.php");
        die();
    } else {
        // authentication failed
        $error = 1;
		$user = $_POST['userLogin'];
    }
}
// output error to user
if ($error == 1) {
    unset($_SESSION['user'],$_SESSION['access']);
    session_destroy();
	echo "Login failed: Incorrect user name, password, or permissions<br />";
}
// output logout success
if (isset($_GET['out'])) echo "Logout successful<br />";
?>
<TITLE>Login</TITLE>
<form method="post" action="login.php">
    User: <input type="text" name="userLogin" /><br />
    Password: <input type="password" name="userPassword" /><br />
    <input type="submit" name="submit" value="Submit" />
</form>
 
you have not included dbConnect.php or authenticate.php (so I cannot tell what happens with the session inside those files, nor if there are any errors). Are you _certain_ that there is nothing in those files that could cause an error, warning or notice to be thrown? If any html is output then the session can fail and the ajax will receive html rather than json.

the ajaxserver now has a debug function. this will break the json but will provide feedback that will be visible either by browsing direct to the ajaxserver.php file or by the console in firebug.

Code:
<?php
ini_set('display_errors', true);
error_reporting(E_ALL);
if(session_id() == '') session_start();  
// set timeout period in seconds
$inactive = 900;
// check to see if $_SESSION['timeout'] is set
if(isset($_SESSION['timeout']) ) {
    $session_life = time() - $_SESSION['timeout'];
    if($session_life > $inactive) { 
        session_destroy();
        session_write_close();
        header("Location: /login.php"); 
        exit; /* very important */
    }
}
$_SESSION['timeout'] = time();
if (!isset($_SESSION['user'])) {
    echo ("Unauthorized Access");
    echo ("<br />");
    echo "<META HTTP-EQUIV='Refresh' Content='0; URL=../login.php'>";
    exit();
}
$user = $_SESSION['user'];
?>

Code:
<?php 
function isDebug(){
    return isset($_POST['debug']) || isset($_GET['debug']);
}
function footprint($message = ''){
    if(empty($message)) return;
    if(isDebug()) echo $message . "\n";
}

require_once "dbconnect.php";
footprint("connected to db");

require_once $_SERVER['DOCUMENT_ROOT'].'/user_header.php';
footprint("done sessions");

if(!function_exists('json_encode')):
    footprint('json_encode function does not exist');
    die;
endif;

if (! @mysql_select_db($database) ):
    echo json_encode(array( 'result'=>'error',
                            'errorMessage'=>'Unable to locate the database at this time.'));
    die;
else:
    footprint('selected database');
endif;

/*  change back to POST when the scripts are working */
/*  useful to allow GET requests while debugging */
if(!isset($_REQUEST['id'])):
    echo json_encode(array( 'result'=>'error',
                            'errorMessage'=>'No ID provided.'));
    die;
endif;

$id = mysql_real_escape_string($_REQUEST['id']); //always escape and enquote all user input to avoid sql injection
$allowedusers = array("bill", "john");
if (in_array($user, $allowedusers)):

    footprint('user is allowed');

    $result = @mysql_query("SELECT secretvoodoo from voodoo_list WHERE id = '$id'");
    
    if($result):
        footprint('secretvoodoo query done');
        $row = @mysql_fetch_assoc($result);
        if(!$row):
            echo json_encode(array( 'result'=>'error', 
                                    'errorMessage'=>"Nothing found for that ID"
                            ));
            die;
        else:
            echo json_encode(array( 'result'=>'ok', 
                                    'data'=>$row['secretvoodoo']
                                ));
            die;
        endif;  
    else:
        echo json_encode(array(     'result'=>'error', 
                                    'errorMessage'=>mysql_error()
                                ));
        die;    
    endif;
else:
    echo json_encode(array(         'result'=>'error', 
                                    'errorMessage'=>"unauthorized"
                                ));
    die;
endif;
?>

Code:
<!DOCTYPE HTML>
<html>
<?php 
function doList($id){
    if(empty($id))return;
    $buttonFormat = '<button class="myButton" actionid="%s">Show Voodoo</button>';
    printf($buttonFormat, $id);
}
require_once "dbconnect.php";
require_once $_SERVER['DOCUMENT_ROOT'].'/user_header.php';
if (! @mysql_select_db("$database") ) :
  echo( "<P>Unable to locate the " .
        "database at this time.</P>" );
  exit();
endif;
$voodooid = isset($_GET['id']) ? $_GET['id'] : '';
?>
<head>
<meta charset="utf-8"/>
<script type="text/javascript" src="jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    /* attach event listeners to the buttons */
    $('.myButton').on('click', function(e){
        e.preventDefault();
        var id=$(this).attr('actionid');
        /* make ajax call */
        $.ajax(
                {
                    async:      false,
                    url:        'ajaxserver.php?debug=1',
                    type:       'POST',
                    dataType:   'json',
                    data:       {id:id},
                    success:    function(data){
                        if(data.result == 'ok'){
                            alert(data.data);
                        }else{
                            alert(data.errorMessage);
                        }
                    },
                    complete:   function(data){
                        console.log(data);
                        }
                });
    });
});
</script>
</head>
<body>
<?php doList($voodooid); ?></body>
</html>

Code:
<?php
function showForm(){
    ?>
<!DOCTYPE HTML>
<html>
<meta charset="utf-8"/>
<head>
<TITLE>Login</TITLE>
</head>
<body>
<form method="post" action="login.php">
    User: <input type="text" name="userLogin" /><br />
    Password: <input type="password" name="userPassword" /><br />
    <input type="submit" name="submit" value="Submit" />
</form> 
</body>
</html>
<?php 
}

require_once "dbconnect.php";
if (!$connect) {
  echo( "<P>Unable to connect to the " .
        "database server at this time.</P>" );
  exit();
}
if (! @mysql_select_db("$database") ) {
  echo( "<P>Unable to locate the " .
        "database at this time.</P>" );
  exit();
}
if(session_id() == '') session_start(); 
$client_ip = $_SERVER['REMOTE_ADDR'];
// authenticate.php contains the ldap authentication function
require_once "authenticate.php";
// check to see if user is logging out
if(isset($_GET['out'])):
    // destroy session
    $_SESSION = array();
    session_destroy();
    session_write_close();
    echo "Logout successful<br />";
    showForm();
elseif(isset($_POST['userLogin'])):     // check to see if login form has been submitted
    // run information through authenticator function at authenticate.php
    // the authenticate function returns true if the user is authenticated
    if(authenticate($_POST['userLogin'],$_POST['userPassword'])):
        // authentication passed
        $error = 0;
        $user = $_POST['userLogin'];
        $_SESSION['user'] = $user;
        $_SESSION['timeout'] = time();
        session_write_close();
        header("Location: /index.php");
        die();
    else:
        // authentication failed
        $error = 1;
        $user = $_POST['userLogin'];
        unset($_SESSION['user'],$_SESSION['access']);
        session_destroy();
        session_write_close();
        echo "Login failed: Incorrect user name, password, or permissions<br />";
        showForm();
    endif;
endif;
?>
 
When I hit ajaxserver directly I get {"result":"error","errorMessage":"No ID provided."}. an expected result. Firebug shows nothing. The button on the formpage doesn't work, but is that expected? Firebug shows nothing.

Here are the other scripts.

dbconnect.php
Code:
<?php
$username="vduser";
$password="xxxxx";
$database="voodoo";
$server="localhost";
$connect = @mysql_connect("localhost", "vduser", "xxxxx");
?>

authenticate.php
Code:
<?php
function authenticate($user, $password) {
	include("ldap.php");  
    $ldap_user_group = "Voodoo";
    $ldap = ldap_connect($LDAPHost) or die("Could not connect to LDAP");	
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3); 
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
    if($bind = @ldap_bind($ldap, $user . $LDAPUserDomain, $password)) {
        $filter = "(sAMAccountName=" . $user . ")";
        $attr = array("memberof");
        $result = ldap_search($ldap, $dn, $filter, $attr);
        $entries = ldap_get_entries($ldap, $result);
        ldap_unbind($ldap);
        foreach($entries[0]['memberof'] as $grps) {
            if (strpos($grps, $ldap_user_group)) $access = 1;
        }
        if ($access != 0) {
            $_SESSION['user'] = $user;
            $_SESSION['access'] = $access;
            return true;
        } else {
            return false;
        }
    } else {
		return false;
    }
}
?>



 
that's expected. yes.
now try adding an id. ajaxserver.php?id=someid

thanks for posting those two scripts. if you are comfortable that they are functional (and their includes, likewise) then all i would suggest is to comment out this line in my version of login.php (as it is already set within authenticate())

Code:
$_SESSION['user'] = $user;
 
Adding the id works as expected too. {"result":"ok","data":"1234"}

When I hit formpage with or without commenting that line, I get nothing if the user_header is included. Without it, I get the button but it doesn't work.
 
commenting the line won't affect functionality. it's just for cleanliness.

so as I understand it, the script is working at the moment if you point your browser directly at the ajax server. but not if BOTH these two things are true:

1. you load up the form and rely on ajax for server interaction
2. the form includes user_header

however the ajaxserver direct route works fine when user_header is included.

i'm not certain what this indicates as you have not posted any site where we can test this and examine the raw headers and responses. But i suspect that the most likely culprit is somehow related to the session management and/or timeout.

let's try to fix the button before attempting the ajax functionality.

please use this version of user_header.php to test with.

Code:
<?php
ini_set('display_errors', true);
error_reporting(E_ALL);
if(session_id() == '') session_start();  
echo '<pre>';
echo 'Current session data: ';
print_r($_SESSION);
echo '</pre>';
// set timeout period in seconds
$inactive = 900;
// check to see if $_SESSION['timeout'] is set
if(isset($_SESSION['timeout']) ) {
    $session_life = time() - $_SESSION['timeout'];
    if($session_life > $inactive) { 
        session_destroy();
        session_write_close();
        header("Location: /login.php"); 
        exit; /* very important */
    }
}
$_SESSION['timeout'] = time();
if (!isset($_SESSION['user'])) {
    echo "Unauthorized Access";
    echo "<br />";
    echo "REDIRECT SUSPENDED FOR DEBUGGING";
    exit();
}
echo '<pre>Finished parsing user_header.php</pre>';
$user = $_SESSION['user'];
?>

and then post back the verbatim output please.
 
Before I change anyting. I don't think your version of user_header is working at all. I get no prompt to login.
 
if you implement that file you will get some output. if only the content of $_SESSION. that is the first stage in debugging.

but please also comment out the header redirect line. the point is to force the page to remain in place and give you feedback.
 
The first time I hit formpage directly, with no id, I get
Code:
Current session data: Array
(
)
Unauthorized Access
REDIRECT SUSPENDED FOR DEBUGGING

The second time I hit it, I get
Code:
Current session data: Array
(
    [timeout] => 1389622536
)
Unauthorized Access
REDIRECT SUSPENDED FOR DEBUGGING
 
ok. so the problem is that the user variable is not being set within the session store.

browse to the login page manually and log in.
at the end of login.php before the last endif; insert a line and add this
Code:
else: 
 showform();
(this will cause the form to show when you browse there)
once you are logged in, browse back to the form page manually and post back the response.

 
After I login, it just goes to a blank page. I think there's a problem with the auth. I get a new error in the php log.
Code:
[13-Jan-2014 10:02:58] PHP Parse error:  syntax error, unexpected T_VARIABLE in C:\test\ldap.php on line 3

Here is the ldap.php that I forgot to post earlier.
Code:
<?php
$crypt = "xxxxxxxx"
$LDAPHost = "ldaps://ldap.domain.com";
$dn = "dc=domain,dc=com"; 
$LDAPUserDomain = "@domain.com"; 
$LDAPUser = "ldapuser";        
$LDAPUserPasswordHash = "yyyyyyyyyyy=";
$LDAPUserPassword = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($crypt), base64_decode($LDAPUserPasswordHash), MCRYPT_MODE_CBC, md5(md5($crypt))), "\0");
?>
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top