Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm attempting to create an API through Wordpress exposing some of my back-end data. I've come to the conclusion that I cannot have a stand alone page (plugin) exposing this data because Wordpress is always attempting to call it and it had be be behind some sort of action hook.

My solution was to create an AJAX call w/o an event to trigger it but a URL. In the theme functions.php file I created two action hooks:

add_action('wp_ajax_nopriv_do_ajax', 'ajax_return_catalog_info');
add_action('wp_ajax_do_ajax', 'ajax_return_catalog_info');

With my method here:

function ajax_return_catalog_info() {     
    switch($_REQUEST['fn']) {
       case 'ajax_call_1':
          // do ajax method 1 here      
          echo json_encode($output);
          break;
       case 'ajax_call_2':
          // do ajax method 2 here
          echo json_encode($output);
          break;
    }
}

Now to call the AJAX through a web browser with the following URL:

http://mywebsite.com/wp-admin/admin-ajax.php?action=do_ajax&fn=get_brand&id=579

This seems to return JSON which is what I expect but my browser doesn't seem to know it is JSON because it is missing some header information usually returned from the JavaScript I've omitted.

My question to the community is if there is a better way to do this?
Am I going about this the wrong way?

Much Appreciated

share|improve this question
add comment

1 Answer

up vote 0 down vote accepted

You need a die(); before the closing } of the function and you might want to add the relevant php header to tell the browser it's content-type

I wouldn't worry about the browser returning the wrong content type.

As long as your code loading the data treats it as JSON

So for your function try this instead

function ajax_return_catalog_info() {
    header('Content-type: application/json');
    switch($_REQUEST['fn']) {
       case 'ajax_call_1':
          // do ajax method 1 here      
          echo json_encode($output);
          break;
       case 'ajax_call_2':
          // do ajax method 2 here
          echo json_encode($output);
          break;
    }
    die();
}

if you don't die you get a 0 stuck on the end as well, as it collapses back to the Ajax Call Function (which goes echo 0;die();

share|improve this answer
    
Thank you Barry, this was exactly what I needed. 1) die() and 2) adding header content-type –  cmeigs Aug 22 '12 at 14:29
    
Excellent glad I could help :-D –  Barry Carlyon Aug 22 '12 at 18:02
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.