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
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.
You can define a Javascript variable in your view and then use it inside your script:
View:
Script: