Welcome Guest, Not a member yet? Register   Sign In
javascript and codeigniter
#1

[eluser]hudar[/eluser]
Hi, good day..

I just wonder if anyone have some idea regarding this case :

I have javascript code like below :

Code:
$.post(
      '<?=site_url('shipper/shipment/inbound_by_date')?>',{
               date:date
      }
      ........
      // there are many lines here, but removed to make it sort and simple
};

I wrote that javascript on view which is php file. I wonder if this javascript could be made separated as .js file, so we just need to import that .js file in every page when needed, instead of copy paste all the javascript on every page (very paintfull Sad )
Since my php page on view, contain a lot of javascript code.
The javascript use php code which is <?=site_url()?>, does this code will work if separated as .js file? I don't think so.

Any suggestion would be very appreciated.
#2

[eluser]rogierb[/eluser]
Why not put the javascript in another view file and load that whenever you need it?
#3

[eluser]hudar[/eluser]
Hi Rogierb,

Did you mean put the javascript as another php file, then include that php file?

Never tried it, but will consider this. But if there is any other options, I would like to hear that.
#4

[eluser]Jameson.[/eluser]
Well, you could make Apache treat those .js files as php scripts by adding a handler similar to this:
Code:
AddHandler application/x-httpd-php .js
But that's not really the right thing to do. I suppose that large .js file is some sort of library with all sorts of functions that are static and need not be changed often. So let's allow our client's browser to cache that .js file and only output dynamic variables in view.

We'll have to refactor js code a bit:
Code:
function startup(url, date)
{
$.post(
      url + 'shipper/shipment/inbound_by_date', {
               'date': date
      }
}
and in view you would write somthing like this:

Code:
< script type='text/javascript'>

  $(document).ready(function(){
     startup('<?=$this->config->item("base_url")?>', '<?=$item['date_or_smth']?>');
  })

< /script>

On a side note: personally I prefer to put all my static client-side resources in one folder, say "static", and then just refer it via relative path from domain root (don't know how to call it correctly in English), like this:
Code:
&lt; script type='text/javascript' src='/static/js/common.js'&gt;&lt; /script>

This way I don't have to manually change references to files when using on another project and don't need to provide URL in program.
#5

[eluser]slowgary[/eluser]
Hudar, you can link to a PHP file instead of JS, like so:
Code:
&lt; script type='text/javascript' src='ajaxscript.php' &gt;&lt;/ script >

Then in ajaxscript.php just send the header:
Code:
Header("content-type: application/x-javascript");

And then echo your javascript. Just make sure it echo's valid JS, otherwise just like any JS file, you'll get errors.




Theme © iAndrew 2016 - Forum software by © MyBB