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 Chris Miller 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.
 
I'm sorry, I can't resist it: "Button, Button, who's got the button?" [spin2]
Seriously, let me make sure I have this straight: You want to put a button on the Client page that passes data to and executes a script on the server?
 
here is a trivial example (this is not necessarily a good approach. it is included to show you how it might be done).

Code:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8"/>
<script type="text/javascript" src="[URL unfurl="true"]http://code.jquery.com/jquery-1.10.1.min.js"></script>[/URL]
<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(data.error);
                        }
                    }
                });
    });
});
</script>
</head>
<body>
<?php
doList();
?></body>
</html>
<?php 

include_once 'dbconnect.php';
function doList(){
    $query = "Select * from users where deleted != 1";
    $result = mysql_query($query) or die(mysql_error());
    $first = true;
    $cellFormat = "<td>%s</td>";
    $rowFormat = "<tr>%s</td>";
    $headingCellFormat = "<th>%s</th>";
    $headingFormat = "<thead>%</thead>";
    $buttonFormat = '<button class="myButton" actionid="%s">Lookup</button>';
    if(mysql_num_rows() > 0) echo '<table>';
    while($row = mysql_fetch_assoc($result)):
        if($first):
            $count = count($row);
            $headings = array_keys($row);
            $output = '';
            foreach($headings as $heading):
                $output .= sprintf($headingCellFormat, htmlspecialchars($heading));
            endforeach;
            $output .= sprintf($headingCellFormat, 'Action');
            $output = sprintf($headingFormat, sprintf($rowFormat, $output));
            echo $output;
            $first = false;
        endif;
        $output = '';
        foreach($row as $item):
            $output .= sprintf($cellFormat, htmlspecialchars($item));
        endforeach;
        $button = sprintf($buttonFormat, $row['id']);
        $output .= sprintf($cellFormat, $button);
        $output = sprintf($rowFormat, $output);
        echo $output;
    endwhile;
    if(!$first) echo '</table>';
    
}
?>

Code:
<?php 
if(!isset($_POST['id'])) die('');
include_once 'dbConnect.php';
$query = 'Select * from users where id="%s"';
$query = sprintf($query, mysql_real_escape_string($_POST['id']));
$result = mysql_query($query);
if($result):
	$row = mysql_fetch_assoc($result);
	echo json_encode(array('result'=>'ok', 'data'=>$row));
	die;
else:
	echo json_encode(array('result'=>'error', 'errorMessage'=>mysql_error()));
	die;
endif;
?>
 
Jpadie: thanks, I'll go through this to see if I can follow it

Prattaratt: Yes. The initial script does a mysql query and presents some information. One bit of the information is excluded (actually not part of the query) and a button is put in its place. On clicking that button, another script runs, validates that the user has access to the information, runs another query, then displays the output in a popup.
 
the above does not provide for a popup. it just splashes a js alert box. if you want a pop-up, you don't actually really need ajax at all. just spawn a child window and provide a url that has the id of the record populated.

e.g.

Code:
onclick='window.open("windowServer.php?id=3", "some title");'

Code:
$('.myButton').on('click',function(){
 var childWindow = window.open("windowServer.php?id=" . $(this).attr('actionid'), "some title");
});

I prefer the jQuery approach for readability.
you could also add a native event listener.
 
In the code above, I need to change this:

Code:
include_once 'dbconnect.php';
function doList(){

to this:

Code:
function doList(){
include_once 'dbconnect.php';

for it to work. Is that normal? A good idea?
 
it depends on the contents of your dbconnect.php file. typically if it just has this
Code:
mysql_connect($host, $user, $pwd);
mysql_select_db($dbName);
then the connection can be in the global scope and thus automatically will be available in every functional scope too.

If you are using mysqli or PDO then something like this would be more normal

Code:
$pdo = new PDO("mysql:host=$host;dbName=$dbName", $user, $pwd);
Code:
include_once 'dbConnect.php';

function doList(){
 global $pdo;
 ...
}

if you have to put the include in to the functional scope it is because the mysql resource handle is being stored in a variable rather than 'floating' as part of the library. so you have to make the variable ($conn, sometimes) available to the function. using the global keyword does this. Or, as you have done, you can put the include into the function. In which case do not use include_once, but include. Note that this is less good overall from a performance and memory handling perspective.
 
I'm making progress, but how can I get a variable from PHP into the function without using globals?
 
typically by passing the argument

Code:
doList($something);

function doList($myVar){

}
 
Here is what I have. What am I missing?

Code:
<body>
<?php
doList();
?></body>
</html>
<?php
$test = '1234';
function doList($test){
    $buttonFormat = '<button class="myButton" actionid="%s">Lookup</button>';
    $button = sprintf($buttonFormat, $test);
    echo $button;
}
?>
 
php is linear. like most languages.

so try this


Code:
<body>
<?php
$test = 1234;

doList( $test );
?></body>
</html>
<?php
function doList($id){
    $buttonFormat = '<button class="myButton" actionid="%s">Lookup</button>';
    $button = sprintf($buttonFormat, $id);
    echo $button;
}
?>

the value of $test is passed to doList and is available within the function as $id. note that this creates a _copy_ of the variable and is not a pointer to the variable. This can sometimes have material benefits, and equally sometimes is not what you want. In either case if you are coming from a C or C# or C++ etc background, knowing the difference is important.
 
That works. Now I have a problem when I try to implement sessions with this. The problem is with the second script (ajaxServer.php above).

Here is the example trying to use sessions. $user is set by the session creation script. The $user is validated correctly, but it dies at the json_encode line.
Code:
<?php 
$allowedusers = array("john", "bob", "bill", "jane");
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;
}
?>

If I define $user specifically in the script as below and omit the session script, it works ok.
Code:
<?php 
$user = "john";
$allowedusers = array("john", "bob", "bill", "jane");
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;
}
?>

Here is the session script for reference.
Code:
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'];
 
not convinced that your session script covers all the use cases. here is a slight reorganisation of your code

Code:
<?php
if(session_id() == '') session_start(); 
// set timeout period in seconds
$inactive = 900;
if(isset($_SESSION['user'])){
	$user = $_SESSION['user'];
	$timeout = isset($_SESSION['timeout']) ? $_SESSION['timeout'] : 1000;
	$session_life = time() - $timeout;
	if ($session_life > $inactive) {
		unset($_SESSION);
		session_destroy();
		session_write_close();
		header("Location: /login.php");
		die(); //always explicitly kill the script after a redirect
	} else {
		$_SESSION['timeout'] = time();
		session_write_close();
	}
} else {
	unset($_SESSION);
	session_destroy();
	echo <<<HTML
<!DOCTYPE HTML>
<html>
<head>
<title>Unauthorized Access</title>
<META HTTP-EQUIV="Refresh" Content='5; URL=../login.php'>
</head>
<body>
Unauthorized access
</body>
</html>
HTML;
}
exit;
?>

and please also try an alternative to the main script

Code:
<?php 
require_once 'session.php';
$allowedusers = array("john", "bob", "bill", "jane");
if (in_array($user, $allowedusers)) {
	$result 			= mysql_query("SELECT secretvoodoo from voodoo_list WHERE id = $id");
	if($result):
		$row 				= mysql_fetch_array($result);
		if($row):
			$secretvoodoo		= $row['secretvoodoo'];
			echo json_encode(array('result'=>'ok', 'data'=>$row['secretvoodoo']));
			die;
		else:
			echo json_encode(array('result'=>'error', 'errorMessage'=>'No records found'));
			die;
		endif;
	else:
		echo json_encode(array('result'=>'error', 'errorMessage'=>mysql_error()));
		die;
	endif;
} else {
	echo json_encode(array('result'=>'error', 'errorMessage'=>"unauthorized"));
	die;
}
?>
 
There's something in there that PHP doesn't like. On the second script, I get an error referring to an unexpected '}' at the } else {. Does mixing the : and { cause that?
 
just fyi - it works fine for me.

on the first script, make _sure_ that the HTML; is absolutely flush to the left hand side and that your code editor does not enforce any silly indenting (several code editors do). if you cannot guarantee this then change the heredoc for single quotes.

Code:
echo '
<!DOCTYPE HTML>
<html>
<head>
<title>Unauthorized Access</title>
<META HTTP-EQUIV="Refresh" Content='5; URL=../login.php'>
</head>
<body>
Unauthorized access
</body>
</html>
';
 
I fixed it by making all of the if statements consistent using {} instead of :. Now I need to map out all of my scripts a little more closely because it's still sticking. Might take a day.
 
Is there a way to debug the ajax? The second script gets up to the echo json_encode line, but I can't see if it's getting past it.
 
easiest way is in firebug on firefox. just take a look at what is returned in the xhr code.

make sure that error_reporting is set to E_ALL and error display turned in, in php. if you don't have access to php.ini (restart the server after each change) you can add this to the beginning of each script

Code:
ini_set('display_errors', true);
error_reporting(E_ALL);

if by any chance you don't have json_encode as a function on your server then you may need to install that. assuming you are on linux and have an apt based package manager you would run this command

Code:
sudo apt-get install php5-json

this is particularly relevant on recent versions of ubuntu.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top