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 Mike Lewis 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.
 
there is an error in your ldap file. a semicolon is missing from the end of line 1.
 
Doh! Sorry.

After login, I get:
Code:
Current session data: Array
(
    [timeout] => 1389628547
    [user] => bill
    [access] => 1
)

Finished parsing user_header.php

When I hit formpage I get the same. When I add the ?id=, I get the same but the button shows up. When I click the button I get nothing.
 
ok. so we seem to be at a point where the user_header is working ok and the session is populating.

on formpage the buttons will show up when the id is populated as a query string. so that is working as you wanted.

so the issue now is what happens when you click the button.
_something_ must happen. firebug (on firefox) should report that there is an XHR request and give details of what that request looked like and what the results of that request was. it should also provide the response.

at the moment the response will be in html form (not ajax) because the debug switch is set. but there will still be some output if the script is being addressed at all.

if there is NO output, then there will also be NO successful XHR request (firebug will inform you) or NO XHR request at all. In which case the issue is in the javascript.

if there is an XHR request but not one that is successful, then usually this is because the address is not accurate. replace the current url with an absolutely qualified url.

if the issue is in the javascript please post the source code of the html rendered page (i.e not the php but the resulting output from the php page)
 
Firebug shows only one thing:
Code:
ReferenceError: $ is not defined
formpage.php?id=1001()formpa...id=1001 (line 13)
$(document).ready(function(){

Here is the source for the HTML.
Code:
<!DOCTYPE HTML>
<html>
<pre>Current session data: Array
(
    [timeout] => 1389629321
    [user] => bill
    [access] => 1
)
</pre><pre>Finished parsing user_header.php</pre> <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>
<button class="myButton" actionid="111">Show Voodoo</button></body>
</html>
 
ah.

then you are not loading jQuery. which means that the jQuery script (jquery-1.10.1.min.js) is not available on your site.

most people reference jQuery on a CDN. replace the src attribute as follows
Code:
<script src="[URL unfurl="true"]http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>[/URL]

or if you want to host locally, save that file to your web root and reference it properly.
 
I broke that when I moved things for testing. I still don't see anything for XHR.

I get:
Code:
connected to db
done sessions
selected database
user is allowed
secretvoodoo query done
{"result":"ok","data":"1234"}
 
That is working then.
Turn off the debug switch in the JavaScript. And try again.
 
That seems to work. Is that it? Should be good? I'll have to go back and check that these new scripts don't break other stuff that uses them. Thanks.
 
should be all that is necessary. do make sure that you completely switch off the debug functionality.

Code:
$.ajax(
                {
                    async:      false,
                    url:        'ajaxserver.php?[COLOR=#EF2929][s]debug=1[/s][/color]',
                    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);
                        }
                });
 
I had a mistake in my final testing. I had $user = 'bill'; specified and the user_header was commented out in the ajaxserver. If I switch it, I get everything but the alert box.
 
please post what firebug reports as the response to the XHR request.
 
see this screenshot of a typical firebug (on firefox) installation

Screenshot%202014-01-14%2014.02.38.png


xhr is clearly marked as a button to the right of javascript in the Net tab.
 
I didn't look at the net pulldown. I was on Console.

This is on the response tab with XHR selected:
Code:
<pre>Current session data: Array
(
    [user] => bill
    [access] => 1
    [timeout] => 1389704898
)
</pre><pre>Finished parsing user_header.php</pre> {"result":"ok","data":"1234"}
 
you did not go back to the non-debug version of user_header.php

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 '<meta http-equiv="refresh" content="5; url=login.php">';
    exit();
}
//echo '<pre>Finished parsing user_header.php</pre>';
$user = $_SESSION['user'];
?>
 
I've narrowed down the problem.
if:
1. A TITLE tag is placed in the user_header.php and
2. Sessions are used to get the user for ajaxserver.php
The alert box doesn't work.

if:
1. A TITLE tag is placed in the user_header.php and
2. $user is defined directly without enabling the session in ajaxserver.php
The alert box works.
 
oh dear.

we seem to have gone back a number of steps.

before, everything was working fine. you were just getting the session data displayed which was breaking the json encoding. stopping the output of session data would make everything work.

you are now saying (and I assume here that you have done NOTHING other than change the code as I posted) that a whole bunch of new symptoms are being exhibited simply by stopping the session data from being output.

If this is the case then either (i) you have introduced errors in following my suggestions; or (ii) you have the most oddly corrupted version of php that I have ever come across.

user_header.php, as posted by you, contains nothing that should be output in an interaction with the server by a user that is already logged in. The only time that there is _ever_ output of any sort is when either the no user is set in the session store (no login) or there is a timeout. In the first instance, output is sent to the user with a meta redirect. In the second instance, the browser is redirected at the http response level back to the login. both of those are scenarios where login must be redone and thus not part of the current process.

there is nothing in the above script (as posted) that can possibly give any output other than as stated. and certainly nothing that contains a <title> tag.

so we will have to wait to hear from you which of (i) and (ii) above you think it is.

Alternatively, provide a link to your site and a login and we can test from here.
 
The problem is that I neglected to show an included script that set the title for everything using the user_header.php. I thought, incorrectly, that it was insignificant. I've been using it all along and thus the problem. Here is the included script:
Code:
<?php
echo "<TITLE>VooDoo (DEVELOPMENT)</TITLE>";
echo "<body bgcolor='#F6CECE'>";
?>

I think the problem is that the occurrence of this <TITLE> tag breaks the <head> tag for the script. (you've now seen every script that this touches).
 
yes - it is definitely a good thing, when asking for help, to be completely transparent as to what all of your scripts (and includes) look like. Otherwise debug efforts are rather difficult.

the user_header script deals with authentication. I would say it is not a great idea to use it for outputting content.

two solutions:

1. move the authentication layer to another include, and in ajaxserver point to the new include rather than user_header
2. change the ajaxserver script to discard the extraneous output

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

[COLOR=#EF2929]ob_start();[/color]

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

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

[COLOR=#EF2929]if(!isDebug()) ob_end_clean();[/color]

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;
?>

the better is the first solution.
 
I've managed to fix it. What are all those footprint lines you added? I can't find any reference to that anywhere.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top