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?