0

I've managed to encode Wordpress data as JSON for a storelocator page but the page is failing to parse the JSON returned. It gives a 404 Not Found error in the console even though the file is present and is actually returning JSON data as it should.

The storelocator JS (essential code):

var settings = $.extend( {
  'mapDiv': 'map',
  'listDiv': 'loc-list',
  'formContainerDiv': 'form-container',
  'formID': 'user-location',
  'inputID': 'address',
  'dataType': 'json',
  'dataLocation': 'http://localhost/website/wp-content/themes/custom/locations.php',
  'jsonpCallback': null
}, options);

My PHP:

<?php

global $table_prefix, $wpdb, $output_array;

require_once('../../../wp-blog-header.php');
require_once('../../../wp-admin/includes/upgrade.php');

$output_array = array();

query_posts('category_name=business&showposts=-1');
//query_posts('name='.$post_name.'&showposts=-1');
while (have_posts()) : the_post();


    $name = get_the_title();
    $summary = get_the_content();
    $lat = get_field( "lat", $post->ID );
    $lng = get_field( "lng", $post->ID );
    $address = get_field( "address", $post->ID );
    $phone = get_field( "phone", $post->ID );
    $web = get_field( "web", $post->ID );

    array_push($output_array, array("id"=>$post->ID,
                    "name"=>$name,
                    "summary"=>$summary,
                    "lat"=>$lat,
                    "lng"=>$lng,
                    "address"=>$address,
                    "phone"=>$phone,
                    "web"=>$web));



endwhile;
//print_r($output_array);
echo json_encode($output_array);

?>

Sample of the JSON returned:

[{"id":76,"name":"AFRICAN ELITE PROPERTIES","summary":"Property development and management","lat":"-33.915025","lng":"18.421118","address":"Somerset Road, Green Point","phone":"021 421 1090","web":"www.africaneliteproperties.com"}]

Note: When I copy the returned data into a JSON file and use that as the data location it works perfectly. I've checked file permissions and everything is fine.

Where could I be going wrong?

babusi
  • 520
  • 1
  • 8
  • 27
  • What happens if you just call the url without AJAX? You get a 404 error, which either means that the script itself sends a 404 header, which it doesn't, or no script is executed at all. In conclusion, I think your URL is wrong. – GolezTrol Sep 08 '14 at 11:56
  • 1
    @GolezTrol it works perfectly if I just visit the url in the browser, i.e. It returns well-formatted JSON – babusi Sep 08 '14 at 11:59
  • @pencilsandpixels Look at the network tab in your browser's developer tools. Does the request get a JSON response? What is the status code in there? – Dan Blows Sep 08 '14 at 12:04
  • We are only seeing some configuration being set, not he function that actually does something with it. Are you using a ready made jQuery Plugin or is the code written by yourself? – Kai Mattern Sep 08 '14 at 12:04
  • @Blowski it doesn't return anything else other than the 404 error. The initiator is jQuery – babusi Sep 08 '14 at 12:10
  • @pencilsandpixels in developer tools, you should see the actual URL being requested. Open that URL in your browser - what does it return? Is it exactly the same URL as you are expecting? Check the case, slashes, protocol, etc. – Dan Blows Sep 08 '14 at 12:11
  • 1
    @pencilsandpixels You might also need to consider [forcing the MIME type](http://stackoverflow.com/a/4064468/921836) (I didn't see this being performed already in your code). Also, if you're invoking a .php file directly while leveraging wp-blog-header.php, you might first want to define [wp_use_themes as false](http://wordpress.stackexchange.com/questions/12919/what-is-the-constant-wp-use-themes-for); otherwise, Wordpress might see that your request isn't a valid page request and give you the 404 you're seeing. – Justin Bell Sep 08 '14 at 13:39

1 Answers1

1

This is not the right way to use AJAX in wordpress, You have to send the request to admin-ajax.php with a action hook. Take a look on the example:

$.ajax({
    url: 'http://localhost/website/wp-admin/admin-ajax.php', 
    type: 'post', 
    data: {action: 'my_json_data_fetcher'}, 
    success: function(response){}
});

Now what you have to do, invoke the two hooks, wp_ajax_ and wp_ajax_nopriv_ like this, Go to the functions.php in your themes folder.

// should be in your functions.php
// not that my_json_data_fetcher with wp_ajax_ and wp_ajax_nopriv_ hooks
add_action('wp_ajax_my_json_data_fetcher', 'now_your_function_that_return_json');
add_action('wp_ajax_nopriv_my_json_data_fetcher', 'now_your_function_that_return_json');

function now_your_function_that_return_json() {
    global $table_prefix, $wpdb, $output_array;

    $output_array = array();

    query_posts('category_name=business&showposts=-1');

    while (have_posts()) : the_post();


       $name = get_the_title();
       $summary = get_the_content();
       $lat = get_field( "lat", $post->ID );
       $lng = get_field( "lng", $post->ID );
       $address = get_field( "address", $post->ID );
       $phone = get_field( "phone", $post->ID );
       $web = get_field( "web", $post->ID );

       array_push($output_array, array("id"=>$post->ID,
                "name"=>$name,
                "summary"=>$summary,
                "lat"=>$lat,
                "lng"=>$lng,
                "address"=>$address,
                "phone"=>$phone,
                "web"=>$web));



    endwhile;

    echo json_encode($output_array);
    die(0);
}
jogesh_pi
  • 9,762
  • 4
  • 37
  • 65
  • 1
    It is indeed possible to invoke WP functionality without using admin-ajax.php, but if we're talking about best practices then it is advisable to use admin-ajax.php. The `wp_ajax[_nopriv]_{action}` approach allows for a tighter integration with Wordpress's security model, and provides a more future-proof implementation. – Justin Bell Sep 08 '14 at 13:31