Anil Namde Anil Namde - 4 months ago 10
Ajax Question

Script puzzle <script src="ajaxpage.php?emp_id=23" />?

Very simple Ajax request taking employee id and returning the user info as HTML dumb.

Request ajax("employee/info?emp_id=3543")

id = 3543
name = some name

This is just another simple JS trick to populate the UI.

However i do not understand how something like below is equally able to execute correctly and dump the HTML code.

<script type="text/javascript" src="employee/info?emp_id=3543" />

When page encounters following code it executes like the ajax request is executed and dumps code into page. Only difference is its no more asynchronous as in case of Ajax.

Questions :

Is this correct approach ? its +ves and -ves.

Which are the correct scenarious to user it?

Is this also means that any HTML tag taking "src" tag can be used like this?


I have used this kind of javascript loading for cross domain scripting. Where it is very useful. Here is an example to show what I mean.

[Keep in mind, that JS does not allow cross domain calls from javascript; due to inbuilt security restrictions]

On domain there lies a service that give me a list of users which can be accessed from It returns a json, with a wrapping method like following JSON:

{username:"user1", age:21} 

If I request this json wrapped in a method like as follows:

callMyMethod({username:"user1", age:21})

Then this is a wrapped json which if loads on my page; will try to invoke a method called callMyMethod. This would be allowed in a <script src="source"> kind of declaration but would not be allowed otherwise.

So what I can do is as follows

<script language="javascript" src=""></script>
<script language="javascript">
    function callMyMethod(data)
      //so something with the passed json as data variable.

This would allow me to stuff with JSON coming from other domain, which I wouldn't have been able to do otherwise. So; you see how I could achieve a cross domain scripting which would have been a tough nut to crack otherwise.

This is just one of the uses.

Other reasons why someone would do that is:

  • To version their JS files with releases.
  • To uncache the js files so that they are loaded on client as soon as some changes happen to js and params being passed to URL will try to fetch the latest JS. This would enable new changes getting reflected on client immediatly.
  • When you want to generate conditional JS.

The usage you have specified in example wouldn't probably serve much purpose; would probably just delay the loading of page if processing by server takes time and instead a async ajax call would be much preferred.