How to save a value to an sql databse using an onfocus() function via ajax

前端 未结 1 1248
隐瞒了意图╮
隐瞒了意图╮ 2021-01-26 14:18

Basically what I am trying to do is save one value from a form into a sql database when a user focus\'s on another input. I guess the best way to do this is using ajax. (hope th

相关标签:
1条回答
  • 2021-01-26 14:46

    I was able to get the functionality you were looking for. My example and explanation below:

    Assume two tables:

    1) states -> id varchar(2) (AL, MN, FL, etc..) and state varchar(32) (alabama, minnesota, florida, etc...)

    2) cities -> id int(5) autoinc, city varchar(64) (Mobile, Stillwater, Miami), and state_id varchar(2) (AL, MN, FL)

    Tables linked by: cities.state_id = states.id

    Let's take a look at the form now.

    // autocomplete.php

    Call what you need for JQuery in the head:

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
    
    <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" />
    

    Set up your form in the body. The state input will call a javascript function when focus moves away from the field at which point it will retrieve the cities associated with that state.

    <form action="#">
        <label for="state">State: </label>
        <input type="text" name="state" id="state" onBlur="getCities();"/>
    
        <label for="city">City: </label>
        <input type="text" id="city" name="city"/>
    </form>
    

    Below the form in the body, work the Jquery magic. I figure if you're going to use autocomplete, set it up to work before the user has input any location data, in this case "state". We do this by encapsulating the code into functions.

    Keep in mind that what is happening is that autocomplete is calling a php file via GET, which returns an array of values that autocomplete uses to fill the list as you type.

    We want to get all the cities at first THEN once the user has input information in the state field get all the cities associated with that state. Essentially we'll be setting up autocomplete twice.

    Here you go - function to handle autocomplete:

    // set autocomplete
        function setAutocomplete(data) {
            $('#city').autocomplete({
                source: data,
                minLength: 1
            });
        }
    

    Now set up autocomplete, displaying all cities.

    // autocomplete default
        setAutocomplete('getautocomplete.php');
    

    At this point if you start typing in the cities input field you'll see all the cities, regardless of state.

    Now we'll handle what happens when the user enters a state in the state input:

    // get cities based on state input    
        function getCities() {
            var state_name = $('#state').val();
            setAutocomplete('getautocomplete.php?state='+state_name);
        }
    

    And that's it! When you enter state's name and lose focus on that field, it will alter autocomplete on the state input field, calling getautocomplete.php again but filtering by state name this time.

    Let's take a look at the PHP file now.

    // getautocomplete.php

    From the top -> Set up your database connection:

    $mysqli = new mysqli('localhost', 'root', '', 'php_autocomplete');
    
    /* check connection */
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }
    

    Then set the parameters we'll need for the SQL Query.

    // get parameters
    $term    = isset($_GET['term']) ? $_GET['term'] : NULL;
    $state   = isset($_GET['state']) ? $_GET['state'] : NULL;
    

    Now we check if the state parameter has been set, as this determines which SQL SELECT string we use.

    // set query dependant on if state available
    if ( $state == NULL ) {
        // get all cities
        $query = 'SELECT city 
                  FROM cities 
                  WHERE city LIKE "%'.$term.'%" 
                  ORDER BY city';
    } else {
        // filter by state
        $query = 'SELECT city 
                  FROM cities 
                  INNER JOIN states ON cities.state_id=states.id 
                  WHERE (state="'.$state.'" AND city LIKE "%'.$term.'%") 
                  ORDER BY city';
    }
    

    And finally we return and print out the results (essentially an array) which is what JQuery autocomplete will use to populate the autocomplete list:

    // get results
    $results = $mysqli->query($query);
    $json    = array();
    
    while ( $city = $results->fetch_array() ) {
        $json[] = array( 'value' => $city['city'], 'label' => $city['city'] );
    }
    
    echo json_encode($json);
    

    You don't need to use AJAX. Autocomplete is essentially doing AJAX on getautocomplete.php already. We just give it an additional parameter by adding ?state=state_name, and then in the PHP we account for that parameter and craft an SQL SELECT statement as required.

    Here's the complete code for both files so you can see it in context without any of my comments. I hope this helps you solve your problem. You should be able to make this work with your tables and form.

    //// autocomplete.php

    <!doctype html>
    <html>
    <head>
       <meta charset="utf-8">
       <title>Autocomplete</title>
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
       <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
       <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
       <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" />
    </head>
    <body>
       <form action="#">
          <label for="state">State: </label>
          <input type="text" name="state" id="state" onBlur="getCities();"/>
          <label for="city">City: </label>
          <input type="text" id="city" name="city"/>
       </form>
       <script type="text/javascript">
          // set autocomplete
          function setAutocomplete(data) {
              $('#city').autocomplete({
                source: data,
                minLength: 1
              });
          }
    
          // autocomplete default
          setAutocomplete('getautocomplete.php');
    
          // get cities based on state input    
          function getCities() {
            var state_name = $('#state').val();
            setAutocomplete('getautocomplete.php?state='+state_name);
          }
      </script>
    </body>
    </html>
    

    ///// getautocomplete.php

    <?php
    
    $mysqli = new mysqli('localhost', 'root', '', 'php_autocomplete');
    
    /* check connection */
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }
    
    // get parameters
    $term    = isset($_GET['term']) ? $_GET['term'] : NULL;
    $state   = isset($_GET['state']) ? $_GET['state'] : NULL;
    
    // set query dependant on if state available
    if ( $state == NULL ) {
        // get all cities
        $query = 'SELECT city 
                  FROM cities 
                  WHERE city LIKE "%'.$term.'%" 
                  ORDER BY city';
    } else {
        // filter by state
        $query = 'SELECT city 
                  FROM cities 
                  INNER JOIN states ON cities.state_id=states.id 
                  WHERE (state="'.$state.'" AND city LIKE "%'.$term.'%") 
                  ORDER BY city';
    }
    
    // get results
    $results = $mysqli->query($query);
    $json    = array();
    
    while ( $city = $results->fetch_array() ) {
        $json[] = array( 'value' => $city['city'], 'label' => $city['city'] );
    }
    
    echo json_encode($json);
    
    ?>
    
    0 讨论(0)
提交回复
热议问题