0

I'm a beginner coding with JQuery Select2 and Ajax. I'm trying to load dataset from DB into JQuery Select2 dropdown with search option.

This is the function for DB query and enqueue scripts in my functions.php :

function enqueue_select2()
    {
       wp_enqueue_style('select2-css',    'https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css');
      wp_enqueue_script('select2-js',      'https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js', array('jquery'), null, true);
    }
    add_action('wp_enqueue_scripts', 'enqueue_select2');


    function get_locations_for_select2(){
        $user = 'xxx'; 
        $password = 'yyy';
        $database = 'zzz'; 
        $servername = 'localhost';
        $mysqli = new mysqli($servername, $user, $password, $database);

        $sql_loc = "SELECT t.term_id,t.name as term_name,slug 
                 FROM wplw_terms t 
                 inner join wplw_term_taxonomy tax on tax.term_id=t.term_id 
                 where taxonomy='at_biz_dir-location' and slug like '%-state' and t.name LIKE '" .      $searchTerm . "%' order by t.name asc limit 20;";
        $results = $mysqli ->query($sql_loc);
    
        $data = [];
        if ($results->num_rows > 0) {
            while ($row = $results->fetch_assoc()) {
                $data[] = array("id" => $row['term_id'], "text" => $row['term_name']);
            }
        } else {
            echo "0 results" . "<br>";
        }
    
        echo json_encode($data);
    }

This is the html and script written in Elementor element for client side:

<select name="search_locations_list" id="search_locations_list" style="width:200px;">
      <option value="">Select location</option>
    </select> 

    <script>
    $('#search_locations_list').select2({
    ajax: { 
    url:"https://my-domain/functions.php",
    type: "post",
    dataType: 'json',
    delay: 250,
    data: function (params) {
    return {
    searchTerm: params.term // search term
     };
     },
     processResults: function (response) {
     return {
     results: response
     };
     },
     cache: true
     }  
     });
     </script>

I have 2 questions i'll be grateful to get help with:

  1. Is it possible to call specific function from functions.php file and put it in the ajax url line? If it's not possible, what is the right way? (because i'm new in JQuery and Ajax it will be helpful and appreaciated to get detailed solution).
  2. I don't know how to pass the $searchTerm text that the user type in the client side dropdown search field, to the server side.

Thank's in advance for any help.

I tried to write the DB query in separate php file and call it in Ajax url param, and the data was loading to Select2 dropdown, but I had a problem how to transfer the user search input chars to server side. That's why I thought to write the php code in functions.php file.

2
  • Are you struggling with the PHP part or the jQuery part? Also, be warned that your SELECT query is highly vulnerable for SQL injection. Have a look at prepared statements to avoid getting hacked
    – Nico Haase
    Commented Jul 8 at 6:54
  • 1
    No, targeting the functions.php with a request directly, is not the right way to do this. smashingmagazine.com/2011/10/how-to-use-ajax-in-wordpress
    – CBroe
    Commented Jul 8 at 7:31

0

Browse other questions tagged or ask your own question.