1

I have inherited some bad code in a Drupal 7.x site and it needs to be cleaned up. Several places in the code the URL is hard-coded and I want to change that. For example, in many of my javascript (.js) files I have something like this:

var url= 'http://dev3.ws.mysite.com/index.php/api/alerts_mix/x-api-key/blahhhhhhhhhzBkfqPTq4SWuCiLONePNfschNft';

In the PHP code I have the following:

     $url="http://dev3.ws.mysite.com/api/checkin/x-api-key/blahhhhhhhhhuRCMIWM0Nw0rM2cDK7tTJTPW?uid=11&lt="

First question...is it OK to have the entire URL for the API (including the key) hard-coded or should we be calling this some other way?

Second...for both the js and PHP, what can I use in place of the HTTP and domain (http://dev3.ws.mysite.com) so it is a variable and gets those values from the config files so I don't need to change this every time when making a new dev site?

2 Answers 2

0

I suggest you add it in your custom module in hook_init then it will exist everywhere,

function yourmodule_init(){
     $url="http://dev3.ws.mysite.com/api/checkin/x-api-key/blahhhhhhhhhuRCMIWM0Nw0rM2cDK7tTJTPW?uid=11&lt="
    drupal_add_js(array('yourmodule' => array('myurl' => $url)), array('type' => 'setting'));
    variable_set('myurl',$url);

}

Then in modules you can get it with

$url=variable_get('myurl');

and in JS files

var url=Drupal.settings.yourmodule.myurl;
3
  • I like this solution but am getting an error in js: Uncaught TypeError: Cannot read property of undefined. Were you able to get this solution working? Commented Nov 16, 2015 at 23:48
  • @Ryan sure, tell me where are you use it? come code here Commented Nov 17, 2015 at 5:14
  • Here is what I implemented in my custombootstrap.module file: function yourmodule_init(){ $apiurl="dev.ws.mysite.com/api" drupal_add_js(array('yourmodule' => array('myurl' => $apiurl)), array('type' => 'setting')); variable_set('myurl',$apiurl); } I am using it like this in a .js file: var apiurl = Drupal.settings.yourmodule.myurl+'l_users_gis/x-api-key/blahhhhhhhhhhhBkfqPTq4SWuCiLONePNfschNft'; Commented Nov 17, 2015 at 16:49
0

For configuration, like an API server URL, I'd suggest using Drupal variables. There are several ways to set the variable:

  1. In the settings.php:

$conf['api_server'] = 'http://example.com';

  1. With Drush:

drush vset api_server 'http://example.com'

  1. Build an admin screen where you can set the value. (Probably overkill in this case.)

In your code where you need the URL, use variable_get():

$url = variable_get('api_server');

To access the value in JavaScript see: How to pass PHP variables to Javascript/jQuery?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.