0

I've been doing some research on calling a PHP function within a file from jQuery and can't seem to find a proper way of doing this without it failing on me. I'm trying to create an intermediary (kind of) CMS with MVVM to create a single-page website with a WordPress base.

At the moment I'm stuck on a bit where I'm trying to access PHP functions in allocated files, I've seen examples here, here and here on how to do it with a function per file, but I'd like to be able to call a function in a file as it gives me a clearer overview.

I've checked the link and it's correct, the PHP file is called posts.php and its in the location defined by window.MODELS, however the function fetch_all doesn't get executed.

JavaScript

//call php function
var requestURL = window.MODELS + 'posts/fetch_all';

$.get(requestURL, function(data){
    console.log('checking data: ', data);
}, 'json')
    .done(function(passed){
        console.log('it worked!');
    })
    .fail(function(failed){
        console.log('it failed :( ');
    });

PHP

public function fetch_all(){
    return json_encode("this is fetch_all..."); //replace text to get all posts with get_posts()
}  

The console shows the JavaScript fail: "it failed :( ". How do I get 'fetch_all' to be executed and return data?

Community
  • 1
  • 1
rkeet
  • 3,406
  • 2
  • 23
  • 49

1 Answers1

3

The URL you're calling from jQuery must match the location of the .php file on your server, for instance the correct URL to call is:

var requestURL = window.MODELS + 'posts.php?action=fetch_all';

Then, inside your PHP file you have to select which function to call according to query parameters. You can add this code after your function declaration, in order to call the proper function depending on the 'action' query parameter:

if ($_REQUEST['action'] == 'fetch_all')
    echo fetch_all();
else
    echo json_encode( array( 'status' => 'error') );

Also remember that your output should be echoed in order to generate output and not simply returned.

Hope it helps, A.

santamanno
  • 626
  • 4
  • 12
  • Ok that did the trick! :) Very many thanks as this had me stumped for hours! Can't accept the answer yet (you were too quick ;) ) but will in a minute! Though shouldn't the `else` be `echo json_encode` as well? – rkeet Apr 16 '13 at 22:35