1

EDIT: This question is rather complicated and most people who come here for an example of (see title) are probably disappointed.

THEREFORE, the OP created a special answer that contains a simple example of using jQuery to do (see title).

To save you time, that is now the selected answer (the previous selected answer was OP's own solution to original problem, so no harm done).

If this sounds like what you're looking for, why are you still reading this drivel? Go look at that answer.


PART I --

I think this has to be done through Ajax/JQuery, but I need help. Here is a very simplified example of what I must do.

A MySQL DB contains a table named USERS, with these fields:
first_name
last_name
email
admin_level

The below form will allow changing the above information for the specified user. The users are listed in an HTML dropdown. The dropdown is populated via PHP script retrieving values from MySQL, but in this example has been hard-coded to simplify the example.

To begin, the operator selects a user's name in the dropdown. An onchange event should then fire a jQuery(?) script that will poll the database and grab the above information for the selected user, and then populate the below form fields.

<div id="whiteboard"></div><br />
<br />
<form action="" method="POST" id="myform">
    <ul>
    <li>
        Choose Account:<br />
        <select name='staff_pick' style='width:200px;' onchange=get();>
            <option value = '1'>John Smith</option>
            <option value = '2'>Jane Doe</option>
            <option value = '3'>Bob Barker</option>
        </select>
    </li>
    <li>
        First Name:<br />
        <input type="text" name="first_name" id="first_name">
    </li>
    <li>
        Last Name:<br />
        <input type="text" name="last_name">
    </li>
    <li>
        Email:<br />
        <input type="text" name="email">
    </li>
    <li>
        Admin Level:<br />
        <input type="text" name="admin_level" value="3">
    </li>
    <li>
        <input type="submit" value="Update">
    </li>
    </ul>
</form>

Else, if anyone could point me to a comprehensive tutorial that closely matches this scenario, I would appreciate it.

4 Answers 4

1

You came to this question because of the title, and you hope it will show you how to use jQuery to detect a change to an html <select> dropdown and then use AJAX to get values from a MySQL database and return the answer.

Here is a working, tested example that should help you get started.

First, you need three things:

1) A MySQL database, containing:
    1a - a table named users
    1b - each row needs fields user_id, first_name, last_name
    1c - a bunch of data, with two or three users whose first name is Chris
    1d - Note that capitalization MATTERS in above steps (user_id not User_ID)
    1e - In step 1b, you can make user_id an auto-increment field, type = int

2) A php file called 'example.php' containing:

<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script type="text/javascript">
            $(function() {
//alert('Document is ready');

                $('#stSelect').change(function() {
                    var sel_stud = $(this).val();
//alert('You picked: ' + sel_stud);

                    $.ajax({
                        type: "POST",
                        url: "example_ajax.php",
                        data: 'theOption=' + sel_stud,
                        success: function(whatigot) {
//alert('Server-side response: ' + whatigot);
                            $('#LaDIV').html(whatigot);
                            $('#theButton').click(function() {
                                alert('You clicked the button');
                            });
                        } //END success fn
                    }); //END $.ajax
                }); //END dropdown change event
            }); //END document.ready
        </script>
    </head>
<body>

    <select name="students" id="stSelect">
        <option value="">Please Select</option>
        <option value="John">John Doe</option>
        <option value="Mike">Mike Williams</option>
        <option value="Chris">Chris Edwards</option>
    </select>

    <!-- **** The AJAX success fn will place found results into this DIV **** -->
    <div id="LaDIV"></div>

</body>

3) A php file called example_ajax.php containing:

<?php

//Login to database (usually this is stored in a separate php file and included in each file where required)
    $server = 'localhost'; //localhost is the usual name of the server if apache/Linux.
    $login = 'abcd1234';
    $pword = 'verySecret';
    $dbname = 'abcd1234_mydb';
    mysql_connect($server,$login,$pword) or die($connect_error); //or die(mysql_error());
    mysql_select_db($dbname) or die($connect_error);

//Get value posted in by ajax
    $selStudent = $_POST['theOption'];
    //die('You sent: ' . $selStudent);

//Run DB query
    $query = "SELECT `user_id`, `first_name`, `last_name` FROM `users` WHERE `first_name` = '$selStudent' AND `user_type` = 'staff'";
    $result = mysql_query($query) or die('Fn test86.php ERROR: ' . mysql_error());
    $num_rows_returned = mysql_num_rows($result);
    //die('Query returned ' . $num_rows_returned . ' rows.');

//Prepare response html markup
    $r = '  
            <h1>Found in Database:</h1>
            <ul style="list-style-type:disc;">
    ';

//Parse mysql results and create response string. Response can be an html table, a full page, or just a few characters
    if ($num_rows_returned > 0) {
        while ($row = mysql_fetch_assoc($result)) {
            $r = $r . '<li> ' . $row['first_name'] . ' ' . $row['last_name'] . ' -- UserID [' .$row['user_id']. ']</li>';
        }
    } else {
        $r = '<p>No student by that name on staff</p>';
    }

//Add this extra button for fun
    $r = $r . '</ul><button id="theButton">Click Me</button>';

//The response echoed below will be inserted into the 
    echo $r;

NOTES:

a) I included the javascript in the <head> of the main file. Usually, we save the javascript in a separate file (eg. mycode.js) and only reference it in the main file, thus:

<script type="text/javascript" src="mycode.js"></script>

b) This line is very important. Without it the jQuery won't and neither will the ajax.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

0

PART II -

I temporarily created a div ("whiteboard") above the form to display what I'm getting back from the DB. The below PHP script (data3.php) is successfully polling the database and retrieving the desired data:

include 'connect_to_db.php';
$id = mysql_real_escape_string($_POST['sent_id']);
$query = "SELECT `fname`, `lname`, `eml`,`priv` FROM `users` WHERE `id`='$id'";
$next_user = mysql_query($query);

echo mysql_fetch_assoc($next_user);

So the data is coming back, but I'm having trouble breaking the data out of the array in jQuery.

In the head of the above HTML document, the following jQuery/javascript:

function get() {
   $.post('data3.php', {sent_id: myform.staff_pick.value },
      function(bounced) {
         var val0 = bounced[0];
         var val1 = bounced[1];
         var val2 = bounced[2];
         var val3 = bounced[3];
         var val4 = bounced[4];
      $('#whiteboard').html(val0+" "+val1+" "+val2+" "+val3+" "+val4).show();
   });
}

HOWEVER... the output is not correct. The word "A r r a y" is output into the whiteboard div. How can I get the fn (first name), ln, eml, etc values instead?

AND THEN... how would I put each broken-out returned value into the corresponding input field in the myform form?

0

PART III - Partial Solution

There must be a better (jQuery) way to break up the mysql_fetch_assoc array inside the jQuery code block, so if anyone can help I would appreciate it.

However, writing this kludge into the DATA3.PHP file is working for now and I now have the individual values broken out in jQuery:

DATA3.PHP IS NOW:

//DATA3.PHP
include 'connect_to_db.php';
$id = mysql_real_escape_string($_POST['sent_id']);
$query = "SELECT `fname`, `lname`, `eml`,`priv` FROM `users` WHERE `id`='$id'";
$next_user = mysql_query($query);

$row = mysql_fetch_assoc($next_user);
echo $row['fname']."|".$row['lname']."|".$row['eml']."|".$row['priv'];

The jQuery script in the main index.php file is now:

function get() {
    $.post('data3.php', {sent_id: myform.staff_pick.value },
        function(bounced) {
            var valNew = bounced.split("|");
            $('#first_name').value = valNew[0] ;
            $('#last_name').value = valNew[1] ;
            $('#email').value = valNew[2] ;
            $('#admin_level').value = valNew[3] ;
            $('#whiteboard').html(valNew[1]).show();
        });
}

My final problem to solve is that the input boxes (in the form) still do not contain the updated values, per the selected user. However, the whiteboard div consistently contains the correct information, and is correctly updated for each newly selected user. (I moved that command to the bottom of the stack just to make sure it still runs, and it does.) So, I'm mystified.

0

FINAL SOLUTION:

Syntax error... what a way to go.

The jQuery script in the main index.php file is now:

function get() {
    $.post('data3.php', {sent_id: myform.staff_pick.value },
        function(bounced) {
            var valNew = bounced.split("|");
            $('#first_name').val(valNew[0]) ;
            $('#last_name').val(valNew[1]) ;
            $('#email').val(valNew[2]) ;
            $('#admin_level').val(valNew[3]) ;
            $('#whiteboard').html(valNew[1]).show();
        });
}

You will note that the incorrect syntax was:

$('#first_name').value = valNew[0] ;

And the corrected syntax is:

$('#first_name').val(valNew[0]) ;

I will leave the question open for a couple of days and if anyone has a better way of doing any of this, please respond. In particular, I would like to understand how I could have returned

echo mysql_fetch_assoc($next_user);

in the initial DATA3.PHP file (see "Part III Partial Solution") and handled that correctly in jQuery on the main INDEX.PHP page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.