Beforehand I'm new to AJAX, but I think my code doesn't have problems, So I'm guessing is WordPress who's causing my setback. What I'm hoping to achieve is to receive a response from a page, here is my simplified setup.
I have a page of ID 999 with the template shout.php
like so:
<?php
/*Template Name: PHP - Shout*/
echo "shout1";
if(is_user_logged_in()) echo " - shout2";
?>
As expected if I go to http://.../Page999
it prints out shout1
and if I'm logged in shout1 - shout2
.
In my request page :
function button_post(){
var http = new XMLHttpRequest();
var url = '<?php echo get_permalink(999); ?>';
var params = ' ';
http.open('POST', url, true);
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
}
I have a copied version of shout.php
outside Wordpress and the button responds to it like expected, but when I use the page 999 (that uses the same file as template) It doesn't work. I don't know why wordpress 'blocks' somehow the response to my function.
It doesn't need to be the exact same setup but I need the file working inside wordpress so I can use functions like is_user_logged_in()
.
In my knowledge this is the only way to make Wordpress interpret an outside page: setting it as a template and using it on a page. I don't know if that's what's causing the issue tho.
Thank you kindly in advance :)