Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax call fails when using wp_remote_get in wordpress plugin

I am having issues with wp_remote_get in my Wordpress plugin.

What I want to do is call a method inside my main public class with ajax. But the thing is that the call fails when the wp_remote_get function is used in it. It is supposed to do an API call and return the data to the jQuery. When I comment out the wp_remote_get the call works fine and response is given back. Any ideas how can I make this work?

Method that processes the call:

    public function countryLookupApiCall() {
    if (isset($_POST['action']) && isset($_POST['country'])) {
        $country = $_POST['country'];
        $apiKey = $this->getApiKey();
        $url = $this->url . $country . '/callCharges?apiKey=' . $apiKey . '&response=JSON';
        $response = wp_remote_get($url);
        echo $response;
        die();
        }
    }

jQuery:

jQuery(document).ready(function() {
jQuery("#countryLookupForm").submit(function(e){
    var country = jQuery("#selectCountry").val();
    var action = 'countryLookupResponse';

    jQuery.ajax ({
        type: 'POST',
        url: countryLookup.ajaxurl,
        dataType: 'json',
        data: {action: action, country: country},

        success: function(data) {
            //do something with this data later on
            var result = jQuery.parseJSON(data);
            }
        });
    });
});

Wordpress actions are all registered well because the call works when I don't use the wp_remote_get

EDIT: The solution was more than simple, I just needed to add e.preventDefault();

like image 380
Danijelb Avatar asked Nov 09 '22 02:11

Danijelb


1 Answers

You need to add errors checking into your code. This can help you to figure out what is causing the problem.

    public function countryLookupApiCall() {
if (isset($_POST['action']) && isset($_POST['country'])) {
    $country = $_POST['country'];
    $apiKey = $this->getApiKey();
    $url = $this->url . $country . '/callCharges?apiKey=' . $apiKey . '&response=JSON';
    $response = wp_remote_get($url);
    if (is_wp_error($response)) {
        $error_code = $response->get_error_code();
        $error_message = $response->get_error_message();
        $error_data = $response->get_error_data($error_code);
        // Process the error here....
    }
    echo $response;
    die();
    }
}

Also you are using echo on wp_remote_get result. As defined in documentation wp_remote_get returs WP_Error or array instance. So you should use something like this:

echo $response['body'];
like image 76
alexeevdv Avatar answered Nov 14 '22 21:11

alexeevdv