Jump to content

[SOLVED] Using PHP to rewrite bits of a JavaScript file


KevinM1

Recommended Posts

Please bear with me as what I'm doing is a bit involved.

 

I currently have an e-commerce site that I'm rewriting.  One of the scripts within this site allows an administrator to configure the various kinds of e-mails that the site sends to registered members when certain things happen (like a welcome e-mail to a new member, for example).  It's a pretty straight forward script -- there's a select-element that allows the administrator to select the category of e-mail they want to configure (new member welcome, purchase request, etc).  Below that, there's a small form that allows the administrator to set the reply address, message subject, and the message itself.  Like I said, pretty easy.

 

The complexity comes in the form of a JavaScript file I've written.  This JS file does two things:

 

1. Toggles the display of the reply address/subject/message form.  The message field allows for some custom, predefined tags to be used.  These tags are str_replaced by member/statistical info that's in the database.  The toggle is to show/hide the tag instructions.

 

2. Puts default values within those three fields, based on what category has been selected.  For example, if the new member welcome category has been selected, then the form's subject field would automatically have "Welcome to blahblahblah" text in it.

 

Here's what I'd like to do: when an administrator updates the e-mail configuration, and that info is entered into the database, I'd also like to overwrite the correct values within my JavaScript file, so the default entries it outputs are the same as what's currently in the database.

 

I'm thinking that there's two ways to go about this:

 

1. Use PHP to find the right part of the JS file and overwrite the old values with the new when the update goes through.

2. Do some AJAX-y things, which is beyond my current ability.

 

Anyone have any ideas on how I might tackle this?  Is it time to dive into AJAX?

 

NOTE: I'm not doing object-oriented PHP here.  I understand the basics, but knowing when/how to combine the objects and structures I've learned of still eludes me.  So my script is procedural in nature.  With any luck, I'll have that OOP epiphany that others seem to get, and version 2 will be object-oriented.

Link to comment
Share on other sites

this osunds like it would be better implemented as 'config' values for the javascript.

 

you could use your php to echo out a series of javascript values inside a script tag in teh head section. ie.

 

<script type="text/javascript">

mailfrom = <?php echo $setting['mailfrom'];

....

</script>

 

alter your javascript file to use these settings that have been generated by php - that way you are only altering settings - no going into teh javascript file and having to find bits to alter.

Link to comment
Share on other sites

this osunds like it would be better implemented as 'config' values for the javascript.

 

you could use your php to echo out a series of javascript values inside a script tag in teh head section. ie.

 

<script type="text/javascript">

mailfrom = <?php echo $setting['mailfrom'];

....

</script>

 

alter your javascript file to use these settings that have been generated by php - that way you are only altering settings - no going into teh javascript file and having to find bits to alter.

 

Apologies for the late reply.

 

So, basically you're saying that my external file will be able to read the values I set via PHP in the document head (providing I link to the file after setting those values)?

 

I always get confused on whether or not an external JS file can access variables/values set separately inside a script-tag in HTML.

Link to comment
Share on other sites

Javascript can access any variables declared by other Javascript as long as they were declared before you try and access them and its within a scope you can see.  You don't need to modify the existing file or bother with an AJAX approach, you can just use JSON.

 

<?php
  $config = // read stuff from database
  $json = // convert config information into a JSON string
  echo <<<JS
    <script type="test/javascript">
      var gConfig = exec({$json}); // <-- convert your JSON string into an actual object
      alert(gConfig.someProperty); // <-- show that we can display a property of the object, i.e. that it worked
    </script>
JS;
?>

Link to comment
Share on other sites

Javascript can access any variables declared by other Javascript as long as they were declared before you try and access them and its within a scope you can see.  You don't need to modify the existing file or bother with an AJAX approach, you can just use JSON.

 

<?php
  $config = // read stuff from database
  $json = // convert config information into a JSON string
  echo <<<JS
    <script type="test/javascript">
      var gConfig = exec({$json}); // <-- convert your JSON string into an actual object
      alert(gConfig.someProperty); // <-- show that we can display a property of the object, i.e. that it worked
    </script>
JS;
?>

 

I haven't played with JSON yet.  From what I've seen, it's basically just property:value pairs, correct?

 

In any event, it's nice to learn that internal and external JavaScript can interact with each other.

Link to comment
Share on other sites

JSON stands for Javascript Object Notation.  You are correct in your understanding of it.

 

I'll give a short example anyways.

 

You start JSON with open curly bracket and close it with closing curly bracket.  In between are property-value pairs.  The property-value pairs are separated by commas.  You separate a property from it's value with a colon.

 

  // This object has a single property named 'msg' with the value 'Hello!'
  var tmp = { msg : "Hello!" };

  // This object has two properties (msg, action) with two values ('Hello!', 'Wave')
  var tmp = { msg : "Hello!",
                   action : "Wave"
  };

  // You can embed JSON in other JSON
  var tmp = {
    internalObj : {  msg : "Hello!"
    },
    msg : "Good bye!"
  };
  alert(tmp.msg);
  alert(tmp.internalObj.msg);

  // You can even declare methods (functions)
  var tmp = {
    msg : "A message!",
    action : function(){
      alert(this.msg);
    }

 

Here is a PHP function that takes a PHP array and converts it into a JSON string.  By no means is it comprehensive or fool-proof, but it works for my application.

<?php
  /**
   * Array2JSObj
   * Convert a PHP array to a Javascript Object literal
   */
  function Array2JSObj($arr){
    $js = "";
    if(is_array($arr) && ($num = count($arr))){
      $js = "{";
      $i = 0;
      foreach($arr as $key => $val){
        if(is_string($val)){
          $val = str_replace("\\", "\\\\", $val);
          $val = str_replace("\n", "\\n", $val);
          $val = str_replace("\"", "\\\"", $val);
          $val = str_replace("\r", "", $val);
          $val = "\"" . $val . "\"";
        }else if(is_bool($val)){
          $val = $val ? "true" : "false";
        }else if(is_null($val)){
          $val = "null";
        }
        $js .= $key . " : " . $val;
        if($i < $num - 1){
          $js .= ",";
        }
        $i++;
      }
      $js .= "}";
    }else{
      $js = "alert(\"Bad PHP Array\");";
    }
    return $js;
  }
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.