简体   繁体   中英

How do I use Ajax in a Wordpress plugin?

I have a Wordpress site with 2 dropdown boxes. When I select an option in the first dropdown box I want the 2nd one to be refreshed with data from a PHP function. For that I need ajax. But I'm struggling with binding ajax into Wordpress.

The HTML looks like this:

<form method="get" action="http://siradjov.anex.at/playground/">
    <div class="form-inner">   
       <div class="listing-search-main">
            <input type="text" class="listing-search-text text" name="s" title="Coach House, Golf Course, Water View, etc" value="unique">
            <input type="submit" class="listing-search-submit btn btn-large btn-primary" name="search-submit" value="Search">
            </div><!-- .listing-search-main -->

       <div class="listing-search-details">
           <div class="listing-search-field listing-search-field-select listing-search-field-status">
           <select class="listing-search-status select" name="status">
              <option value="">Status</option>
              <option value="sale">Sales</option>
              <option value="rent">Rentals</option>
              <option value="foreclosure">Foreclosure</option>
           </select>

      <div class="listing-search-advanced " style="display: block;">
          <div class="listing-search-field listing-search-field-select listing-search-field-min">
           <select class="listing-search-min select" name="min">
              <option value="">Price (min)</option>
              <option value="100000">100.000</option>
              <option value="200000">200.000</option>
              <option value="300000">300.000</option>
              <option value="400000">400.000</option>
           </select>

Now when for example the user selects "Sales" I want the second select tag to be reloaded with the matching prices from a PHP array.

The PHP function looks like this:

 <?php

$selectedStatus = $_POST['status'];


if($selectedStatus == "sale")
{

    // Set price (min) to select

    $fields['min']['type'] = 'select';

    // Set price (min) select options
    $fields['min']['data'] = array(
        '100000' => '120,000',
        '120000' => '200.000',
        '130000' => '300.000',
    );

    // Set price (max) to select

    $fields['max']['type'] = 'select';

    // Set price (max) select options

    $fields['max']['data'] = array(
        '100000' => '120,000',
        '120000' => '200.000',
        '130000' => '300.000',
    );


}
else if($selectedStatus == "rent")
    {

        // Set price (min) to select

        $fields['min']['type'] = 'select';

        // Set price (min) select options
        $fields['min']['data'] = array(
            '200' => '200',
        );

        // Set price (max) to select

        $fields['max']['type'] = 'select';

        // Set price (max) select options

        $fields['max']['data'] = array(
            '200' => '200',
        );

    }

echo $fields;

I've save my jQuery Ajax call in a separate .js file. The code is the following:

 jQuery(document).ready(function() {
jQuery(".listing-search-status.select[name='status']").change(function() {

        if (this.value == "sale")
        {
            jQuery.ajax({
                type: "POST",
                url: "http://siradjov.anex.at/playground/wp-content/plugins/wpcasa-extended-search-status-price-chain-select/wpcasa_custom_prices.php",
                    data: { status : "sale" },
                    success: function(data) 
                    {
                      alert('Sale' + data['min']['data'][0]);
                    }
                     });
        }
        else
        {
            if (this.value == "rent")
            {
                jQuery.ajax({
                    type: "POST",
                    url: "http://siradjov.anex.at/playground/wp-content/plugins/wpcasa-extended-search-status-price-chain-select/wpcasa_custom_prices.php",
                    data: { status : "rent" },
                                            success: function(data) 
                        {
                       alert('Rent' + data['min']['data'][0]);
                        }
                                     });
            }
        }

  });
 });

But the alert Boxes don't show up. Neither do I get any error messages on Google Chrome's Console. Can anyone help me?

Use the native methods that Wordpress provides to you to leverage ajax requests.

In your plugin file, we need to add a couple actions so that we can send ajax requests through and have them parsed by the admin-ajax.php file.

add_action('wp_ajax_nopriv_ajax_request', 'ajax_controller');
add_action('wp_ajax_ajax_request', 'ajax_controller');

Now we build out an ajax controller in our plugin file. The purpose of this is to act as a controller that will switch it's output based on the FN parameter supplied by the ajax request (more on this later)

function ajax_controller(){
    $ret = ''; //our return variable
    switch($_REQUEST['fn']):
        case 'status' :
            $ret = update_status($_REQUEST['status']);
            break;
    endswitch;
    echo $ret;
    die(); //this makes sure you don't get a "1" or "0" appended to the end of your request.
}

Please note that the update_status() function was created to encapsulate your above php code.

Now we have the actions bound, and a controller that we can use endlessly to retrieve data. We just need to make a couple modifications to the ajax call. First, we can use ternary assignment for the 'rent/sale' switch, as opposed to 2 ajax calls, which will clean things up. Second, we need to change the url address to the /wp-admin/admin-ajax.php file.

var $status = (this.value == "sale") ? this.value : 'rent';
jQuery.ajax({
    type: "POST",
    url: "/wp-admin/admin-ajax.php",
    data: { 
       action: 'ajax_request', 
       fn : 'status', //this is the $_REQUEST['fn'] from above
       status : $status },
    success: function(data){
        alert('Sale' + data['min']['data'][0]);
    }
});

The action parameter is required, the fn is a result of my coding principles. The action attribute must directly match what comes after add_action('wp_ajax_nopriv_ and add_action('wp_ajax_ .

This should resolve it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM