Search code examples
cakephpcakephp-2.x

How to write url for XMLHttpRequest in Cakephp 2


how to write the url for my XMLHttpRequest so that I can send my data to my controller.

What I have now is this:

var data = `post=${post}`;
var xhr = new XMLHttpRequest;
xhr.open("POST" , "<?= Router::url(array('controller'=>'posts','action'=>'add')) ?>", true);
xhr.setRequestHeader("Content-type" , "application/x-www-form-urlencoded");
xhr.send(data);

I know I can just:

xhr.open("POST" , "/cakephp/posts/add/", true);

But what I want is to specify the exact controller and action, so that I will not change the code if ever I change my website name like:

xhr.open("POST" , "/mywebsitename/posts/add/", true);

Thanks!


Solution

  • Nevermind, I just found an alternative solution.

    I did:

    var hostname = window.location.origin;
    var data = `post=${post}`;
    var xhr = new XMLHttpRequest;
    xhr.open("POST" , hostname + "/posts/add", true);
    xhr.setRequestHeader("Content-type" , "application/x-www-form-urlencoded");
    xhr.send(data);
    

    so that it will automatically get the base URL of my website.