0

I'm helping a family member out with a WordPress site and haven't coded in PHP in some time. I need to change the way they are handling http requests and have read the following documentation:

https://codex.wordpress.org/AJAX_in_Plugins

<?php
/**
 * Plugin Name: First Plugin
 * Plugin URI: localhost
 * Description: First Plugin
 * Version: 1.0
 * Author: Giltea
 * Author URI: webmeau.ca
 **/

    global $wpdb;
    $wpdb->show_errors();

    add_action( 'wp_enqueue_scripts', 'my_enqueue' );
    function my_enqueue() {
        wp_enqueue_script( 'ajax-script',plugins_url('firstJquery.js', __FILE__), array('jquery') );
        wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
   }

    add_action('wp_ajax_getListings', 'getListings');
    add_action('wp_ajax_nopriv_getListings', 'getListings');

    function getListings(){
    global $wpdb;
    $results = $wpdb->get_results( "SELECT * FROM  wp_wpbdp_listings", OBJECT );
    echo $results;
    wp_die();
    }
?>

I then have a small Jquery script in a separate file:

// firstJQuery.js

(function($) {

    $.ajax({
        url: my_ajax_object.ajax_url,
        type: 'GET',
        dataType: 'json', // added data type
        action: 'getListings',
        success: function(res) {
            console.log(res);
        }
    });

}(jQuery))

I am getting a 400 bad request when it's hitting the admin-ajax.php endpoint. I am getting no other errors in any of my logs (apache, php, or WordPress) and have turned on debugging in the wp-config.php file. Anyone have any suggestions?

1 Answer 1

1

The PHP part of your code looks more or less OK. (There are some security concerns and you shouldn’t echo an array of objects, but you’ll get it when you see it).

But your code doesn’t work because of an error in your JS.

You should send “action” as data and not as a setting... so it should look like this:

$.ajax({
    url: my_ajax_object.ajax_url,
    type: 'GET',
    dataType: 'json', // added data type
    data: {
        action: 'getListings',
    },
    success: function(res) {
        console.log(res);
    }
});
1
  • Good eye, I should have caught that. Unfortunately, I don't have enough rep to upvote! Commented Nov 19, 2019 at 8:11

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.