Ajax error when using wp_remote_get in wordpress plugin

I am having problems with wp_remote_get in my Wordpress plugin.

What I want to do is call the method inside my main public class using ajax. But the fact is that the call fails when it uses the wp_remote_get function. It is assumed that it makes an API call and returns data in jQuery. When I comment on wp_remote_get , the call is working fine and the response is returned. Any ideas how I can 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); } }); }); }); 

All Wordpress actions are logged well, because the call works when I do not use wp_remote_get

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

+5
source share
1 answer

You need to add errors to your code. This will help you understand 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(); } } 

You also use echo in the wp_remote_get results. As indicated in the documentation, wp_remote_get returns an instance of WP_Error or an array. Therefore, you should use something like this:

 echo $response['body']; 
+1
source

Source: https://habr.com/ru/post/1234347/


All Articles