Home > Enterprise >  JavaScript with Ajax call to the WordPress API
JavaScript with Ajax call to the WordPress API

Time:09-29

I'm making a Wordpress plugin named "customposttype" that makes a custom post type with 3 custom fields. The plugin also must do an Ajax call to the WordPress API and gets all the data from those posts in JSON format, to show them in a specific template called "shoplist.php".

My CPT is called "tienda", it has this url for the REST API: ...wp-json/wp/v2/tiendas.

I'm sure that I have several errors because it's my first time using an API and I'm very bad at Javascript.

I'm stuck just right here, I don't know how to continue developing it.

JS shows "Hello world!" at the console, but nothing else.

PHP

add_action("wp_ajax_nopriv_get_shop_data", "get_shop_data");
add_action("wp_ajax_get_shop_data", "get_shop_data");
    
function get_shop_data() {
 
    $api_url = "https://pezquefuma.es/wp-json/wp/v2/tiendas";
    $request = wp_remote_get($api_url);
    $body = wp_remote_retrieve_body($request);
    $output = json_encode($body, true);
    echo $output;

    die();
}
    
    function my_enqueue() {
    if ( get_page_template_slug() == 'shoplist.php' ) {
    
     wp_enqueue_script( 'ajax-script', plugins_url('customposttype/js/filename.js'), array('jquery') );
      wp_localize_script( 'ajax-script', 'my_ajax_object', array( 
          'ajax_url' => admin_url('admin-ajax.php'),
          'nonce' => wp_create_nonce('my-nonce')
          ) 
      );
    }
 }
     
 add_action( 'wp_enqueue_scripts', 'my_enqueue' );

JS

jQuery( document ).ready(function() {
console.log("Hello world!");

jQuery.ajax({
    type : "GET",
    dataType : "JSON",
    url : my_ajax_object.ajax_url,
    data : {
        action: "get_shop_data",
    },

    error: function(response, error) {
        console.log("wrong");
    },

    success : function(response) {
        if(response.type === "success") {
            console.log("Success");
        }
    }
});

});

CodePudding user response:

There are two ways to check response data. one is to use browser's network devtool and another is to use console.log

 success : function(response) {
        console.log(response);
  }
  • Related