ajax wordpress getting 404 error unable to retrieve json from external website and print it on my datatable

I having some issue when I try to access to external website via ajax.404 error will occur when I tried to access it thus unable to store the name parameter data and print on my datatable.
This is one of the error prompt

DataTables warning: table id=import – Ajax error.
For more information about this error. please see http://datatables.net/tn/7

Read More

Below is my code please help thanks.

<?php echo datatable_scripts(); ?>
<script>
$(document).ready(function() {
    $('#import').DataTable({
        ajax: {
            url: 'http://example.com/hello.php',
            type: 'GET',
            dataSrc: 'Data'
        },
        columns: [
            {data: 'name'}
        ]
    });
});
</script>

Below is my json output file from external website.

{“data”:[{“name”:”_testing_product_009″},{“name”:”_testing_product_010″},{“name”:”_testing_product_008″},{“name”:”_testing_product_007″},{“name”:”_testing_product_006″},{“name”:”_testing_product_005″},{“name”:”_testing_product_004″},{“name”:”_testing_product_003″},{“name”:”_testing_product_002″},{“name”:”testing
product lance”}]}

On my hello.php code

<?php
header("Access-Control-Allow-Origin: *");  //To enable cross-domain
include("../../../wp-blog-header.php");  //To enable wordpress core function


    $args = array( 
        'post_type'   => 'product', 
        'post_status' => 'publish',
        'nopaging'    => true
    );

    $query = new WP_Query( $args ); // $query is the WP_Query Object
    $posts = $query->get_posts();   // $posts contains the post objects

    $output = array();
    foreach( $posts as $post ) {  
        $output['data'][] = array( "name"=>$post->post_title );
    }

    echo json_encode($output); ?>

Related posts

1 comment

  1. Please try the following:

    $("#import").DataTable({
      "ajax": "http://example.com/hello.php",
       columns: [
         {data: "name"}
       ]
    });
    

    I’m not sure if you need all the other options based on the format of your JSON. dataSrc is only needed if you are loading JSON that is in an incompatible format for DataTables.

Comments are closed.