1

I'm pulling my data from the database and then I want to load the pulled data with ajax but I am not able to do so.

Following is my code.

jQuery code:

jQuery(document).ready(function () {
    jQuery('#il').change(function () {
        let il_id = jQuery(this).val();
        jQuery.ajax({
            type: "POST",
            url: "../wp-content/themes/fancy-lab/ajax.php",
            data: {il: il_id},
            success: function (e) {
                jQuery('#ilce').show();
                jQuery('#ilce').html(e);
            }
        });
    });
});

ajax.php code:

global $wpdb;

$listele=$wpdb->get_results("Select * From wp_ilce where il_id={$_POST['il']}");

foreach ($listele as $val){
    echo "<option value='$val->id'>".$val->ilce."</option>";
}

But I keep getting an error like this get_results returns null. So where is the problem?

<span>Province*</span>
 <select name="il" id="il" class="form-control">
  <option value="" hidden>Select a city.</option>
    <?php global $wpdb;
      $listele = $wpdb->get_results("Select * From wp_il");
         foreach ($listele as $value) {?>

<option value="<?php echo $value->id ?>"><?php echo $value->il ?></option>

           <?php } ?>
</select>
                
 <span>District*</span>
   <select name="ilce" id="ilce" class="form-control" disabled="disabled">
     <option value="" hidden>Please select county</option> </select>
               

Currently there are 4 sciences, I pull them from the database. Thanks to you, I can sort the districts according to those provinces, but no matter which province I choose, my districts always overlap, so after choosing another province, the districts have to be reset and come back. I hope I was able to explain

1 Answer 1

0

I would start with checking what's sql query you have

print_r("Select * From wp_ilce where il_id={$_POST['il']}");

Next copy it to the sql tab in your phpmyadmin and see if it returns the currect data, could be the the wp_ prefix is incorrect, mabe $_POST['il'] contains an incorrect value.

But aside from all that WP has a way for working with ajax requests.

This will be a bit long but it will give you a starting point with working with ajax requests.

WP has two actions for working with ajax requests, one is public and one is for logged in users. WP also has a unique url for all ajax requests.

http://example.com/wp-admin/admin-ajax.php

Every ajax request you have should use this url, unless you want to use WP RestAPI, but that's a different topic.

Now going by your JS code you could update it to this, I took the liberty to use a bit of ES6.

($ => {
    $('#il').on('change', e => {
        const ilId = $(e.currentTarget).val();

        $.ajax({
            type: 'POST',
            url: 'http://your-site/wp-admin/admin-ajax.php', // wp ajax url
            data: {
                action: 'bt_get_db_il_data', // the action name we will hook into
                il: ilId
            },
            success: e => {
                // Now on success you can check in the browser console the response
                console.log(e);

                $('#ilce').show();
                $('#ilce').html(e);
            }
        });
    });
})(jQuery);

Notice a few changes

  1. url: is now the WP url for working with ajax requests
  2. data: {} now contains action, this is the action name, in PHP, we will hook into and run our code
  3. success: {} now also has console.log(e);, this is for debugging purposes only, to see if the returned data is what we expect. You can remove/comment it after everything works

Ok, JS side is good, now lets move to the PHP logic.

In functions.php you will need to add the following code.

// the $action is the action property that was passed the the data of our ajax request
// for logged in users, structure: do_action('wp_ajax_{$action}')
add_action('wp_ajax_bt_get_db_il_data', 'bt_get_db_il_data');

// for logged out users, structure: do_action('wp_ajax_nopriv_{$action}')
add_action('wp_ajax_nopriv_bt_get_db_il_data', 'bt_get_db_il_data');

function bt_get_db_il_data () {
    global $wpdb;

    // I assume that $_POST['il'] is supposed to be an integer
    // PHP has a function for retrieving request data
    // for POST requests it like this
    $il = filter_input(INPUT_POST, 'il', FILTER_SANITIZE_NUMBER_INT);

    // now $il will only contain digits, minimising wrong data being passed into your sql query

    // in order to prevent SQL injection and other attacks we will use the prepare method
    // the first argumnet is the sql query, notice the %d,
    // this tell the prepare that the value that supposed to be there is a integer
    // the second and on arguments are the values we want to insert into our sql query
    // in our case we only have one, so our first %d (and only in this case), would be replaced with the value of $il
    $listele = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}ilce WHERE ID = %d", $il));

    // this is only for testing to see if we get the expected value/s
    //print_r($listele);

    // this will store our options html structure
    $options_html = '';

    foreach ($listele as $val){
        $options_html .= '<option value="' . $val->id . '">' . $val->ilce . '</option>';
    }

    echo $options_html; // this line "returns" the data back to our ajax

    // this line will stop any other code in our functions.php from runing
    // always add this line
    die;
}

I added comments that should cover most of the logic of the code but ill add a few other notes.

  1. When working with sql query, always escape data that you did not manual typed, in this case $_POST. To do that you use WP prepare.
  2. When getting request data, use PHP filter_input. This function helps you with validating/sanitizing data, so you get the expected data.
  3. Use print_r, var_dump or var_export before building the html sturcture you need, to see that the data is what you expect. This will also help you understand what available properties you can use and how to call them.

I think that should cover the basics, ill add a few other resources for you to read about that can help you understand and teach a few other things.

9
  • Thank you very much for the nice information you provided, the code is working, but I have one last question. I choose the province and district. When I choose the first province, the districts come without any problems, but when I choose the second province, this time it overlaps the other districts, what can I do?
    – Ferhat
    Commented Aug 13, 2021 at 10:12
  • @Ferhat I have no idea what is province and district in your code, could you maybe add it to your question? Commented Aug 13, 2021 at 10:13
  • I added it now you can check it
    – Ferhat
    Commented Aug 13, 2021 at 10:25
  • @Ferhat From what I see you first need to select a province, after you selected a province the ajax runs and returns the options for district, is this correct? Commented Aug 13, 2021 at 10:54
  • yes it is true but if i choose another province the other districts are still standing and all the districts are overlapping
    – Ferhat
    Commented Aug 13, 2021 at 10:58

Your Answer

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

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