Home > Mobile >  ajax request to a php MVC controller
ajax request to a php MVC controller

Time:12-14

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);

CodePudding user response:

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.

CodePudding user response:

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);

CodePudding user response:

I think the php $_SERVER variable should give you what you need. You can find the path of your URL here.

Try to var_dump it.

https://www.php.net/manual/en/reserved.variables.server.php

Note that you're also working on localhost, your deployer probably doesn't know what localhost is.

  • Related