skip to Main Content

In my MVC site I have a js script with an ajax request to a controller (getSinger) like this:
xmlhttp.open("GET","http://localhost/project/home/getSinger/"+str,true);

Is there a way to get the path before the controller name? In the php side I have a constant (URL) with the complete path, so if I deploy the application I have not to change the path.
I tried so but it doesn’t work:

xmlhttp.open("GET","<?php echo URL ?>/home/getSinger/"+str,true);

2

Answers


  1. Javascript is client side. PHP is server side.

    If you generate the js with php before sending it to the browser, yes, you can do that. But if it’s a script loaded by an html file, no, you can’t use PHP functions.

    If the API and the js are on the same URL, you can use window.location to get the path. In the other case, you may have use a json conf file to avoid changing the js code directly.

    Login or Signup to reply.
  2. You can define a Javascript variable in your view and then use it inside your script:

    View:

    <script>const siteUrl = "<?php echo URL ?>";</script>
    <script src="yourajaxscript.js"></script>
    

    Script:

    xmlhttp.open("GET", siteUrl + "/home/getSinger/" + str, true);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search