Jump to content

Recommended Posts

I need to assign people to jobs in projects.  There are 3 tables involved:  names of people, list of jobs, and the projects they will be on. What I want to be able to do is

1) enter the first and last name of the person
2) search for the person by name
3) return the ID of that person
4) select the job they will be doing and get that ID (I have the dropdown for that already)
5) enter the jobID and personID into the project table.

Can this be done in one action or do I need to use 2 different forms?
 

Edited by singingsands
typo
Link to comment
https://forums.phpfreaks.com/topic/326030-can-a-submit-button-trigger-2-actions/
Share on other sites

Here's an example. As you enter more letters of the name it narrows down the resulting list.

image.png.c304e788e1385b3813e777836907bb2f.pngimage.png.5453efefc164369b30a450e5d8951e5f.png

(first and last names are searched)

<?php
#
# HANDLE AJAX REQUESTS
#
    if (isset($_GET['ajax'])) {
        if ($_GET['ajax'] == 'names')  {
            $res = $pdo->prepare("SELECT id
                                     , concat(fname, ' ', lname) as name
                                  FROM person
                                  WHERE fname LIKE ? OR lname LIKE ?
                                  ORDER BY fname, lname     
                                 ");
            $res->execute([ $_GET['search'], $_GET['search'] ]);
            $results = $res->fetchAll();
            exit(json_encode($results));
        }
    }
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example</title>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<style type='text/css'>
</style>
<script type='text/javascript'>
    $(function() {
        
        $("#search").on("input",function() {
            let srch = $(this).val() + "%"
            $.get(
                "",
                {"ajax":"names", "search":srch},
                function(resp)  {
                    $("#person").html("")
                    $.each(resp, function(k,v) {
                        let opt = $("<option>", {"value":v.id, "text":v.name});
                        $("#person").append(opt);
                    })
                },
                "JSON"
            )
        })
    })
</script>
</head>
<body>
    <form>
        Enter first part of name: 
        <input type='text' id='search' >
        <br><br>
        <select name='person_id' id='person' size='20'>
             <!-- names returned from search go here -->
        </select>

    </form>

 

  • Great Answer 1

I'm having trouble with the code above.  I changed the names of the database table and fields where appropriate, spent 2 days troubleshooting, finally copied my table to give it and the fields the same name as in the code.  All I'm getting is this: 

search.jpg.b0b93f285779783cdb062b8e5fee8cb9.jpgNothing comes up at all.

I know the php part is correct but I'm a total noob with ajax so I'm out of my depth here.

If you have added the connection code, check your browser tools network tab to see if something is throwing an error. Just a couple weeks ago I spent several hours debugging a script that was barfing and come to find out I had typed 'context' instead of 'content' in a column name.

Yes I have the connection code as an include. I added a simple query to the same form to check I'm getting the info 

<select name="person" class="form-control col-sm-10">  
                      <?php   
                        $query = "SELECT id,
                                  concat(fname, ' ', lname) as name
                                  FROM person
                                  ORDER BY fname, lname  ";
                        if ($result = $conn->query($query)) {  
                        while ($row = $result->fetch_assoc()) {
                        echo "<option value=".$row["id"].">".$row["name"]."</option>";
                         } 
                        }
                      ?>
       </select>  

And I do get a drop down list with the first and last name in alphabetical order.  But when I check the network tab I get an error:

Unchecked runtime.lastError: Could not establish connection.  Receiving end does not exist.

That makes no sense to me.

Edited by singingsands

This is the code as I copied it from the post.  I changed the names of my table and relevant field names to correspond with this code.

<?php 
require 'includes/db-inc.php';
#
# HANDLE AJAX REQUESTS
#
    if (isset($_GET['ajax'])) {
        if ($_GET['ajax'] == 'names')  {
            $res = $pdo->prepare("SELECT id,
            concat(fname, ' ', lname) as name
             FROM person
             WHERE fname LIKE ? OR lname LIKE ?
             ORDER BY fname, lname     
            ");   
            
            $res->execute([ $_GET['search'], $_GET['search'] ]);
            $results = $res->fetchAll();
            exit(json_encode($results));
        }
    }
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example</title>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<style type='text/css'>
</style>
<script type='text/javascript'>
    $(function() {
        
        $("#search").on("input",function() {
            let srch = $(this).val() + "%"
            $.get(
                "",
                {"ajax":"names", "search":srch},
                function(resp)  {
                    $("#person").html("")
                    $.each(resp, function(k,v) {
                        let opt = $("<option>", {"value":v.id, "text":v.name});
                        $("#person").append(opt);
                    })
                },
                "JSON"
            )
        })
    })
</script>
</head>
<body>
    <form>
        Enter first part of name: 
        <input type='text' id='search' >
        <br><br>
        <select name='person_id' id='person' size='20'>
             <!-- names returned from search go here --> 

        </select>

    </form> 

 

the OP's 'working' database code is using the mysqli extension. the provided autosuggest example is using the PDO extension, along with a connection variable name, $pdo, hinting at what database extension it is using.

i recommend that you convert your existing database specific code to use the much simpler and better designed PDO extension.

MySql (with whatever variations in capitalization you like) is the database server type. mysqli and PDO are php's extensions that allow your php code to  communicate with the database server. if you understand what your mysqli based code is doing, you should be able to convert the code. all it's doing is -

  1. building an sql query statement. which should be in a php variable, in order to separate the sql as much as possible from the php, and allow you to separate the common php code used or in this case change the database extension being used. there's no difference between the sql query statement for the mysqli or PDO extensions, when using positional ? prepared query place-holders.
  2. prepare the sql query. there's no difference in the php syntax for the the mysqli or PDO extensions, except that the connection variable must be (and is usually named) for the extension being used.
  3. bind input data/execute the prepared query. If you are using php8.1 or higher, the php syntax for the execute statement is exactly the same.
  4. you can then use msyqli's get_result() and fetch_all() methods to fetch all the data from the result set.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.