"Refresh" a JavaScript file on change - javascript

On my JSP project I've got a .jsp file which contains the following script:
<script type="text/javascript">
$(window).load(function() {
...
options.items = items;
...
});
</script>
The variable items is included in another JavaScript script that is also included in the same .jsp file:
<script type="text/javascript" src="<c:url value="/js/items.js"/>"></script>
items.js has the following structure:
var items = [{...}, {...}, {...}];
Now, the Servlet that implements doGet for this .jsp gathers some data from a database (and this data can be different every time) and uses it to write in the disk the file items.js mentioned above.
The problem is that the server (tomcat7) doesn't see that items.js has changed until it is restarted, but I need to generate that file every time because the data to gather is not always the same. So I'd like to know how to properly provide the first JavaScript function I mentioned with the data on items without having to restart the server. Of course, I want to avoid using scriptlets if possible.
Please note that I can't just delete that piece of JavaScript included in the beginning of this message because that piece of code is using a JavaScript library which I need to use to visualize my data.
Thanks in advance for your help.

Adding a bit modification to your own solution, if you want to avoid scriptlet you can write your above line like this:
instead of
options.items = <%= request.getAttribute("items") %>;
write
options.items = ${requestScope.items}; or options.items = ${items};

I'm replying to my own question to explain how I solved this problem.
I didn't do exactly what Sacho and Christopher Schultz suggested but what they said gave me an idea.
Firstly, on my servlet, I built a StringBuffer containing the data I want. Initially I wanted to use a JSONArray but that would mean using several transformations so that my js script could read (it'd be doable but it wouldn't simply consist of using the standard parser but something a little bit more complex). Then, I added this StringBuffer to the request parameter. This is how it all looks like:
protected void doGet(HttpServletRequest request,
HttpServletResponse response) {
StringBuffer sb = new StringBuffer();
// Fill the StringBuffer
request.setAttribute("items", sb);
request.getRequestDispatcher("/WEB-INF/myjsp.jsp").forward(
request, response);
}
Finally, I accessed this attribute from my jsp file as it follows:
options.items = <%= request.getAttribute("items") %>;
I wanted to avoid scriptlets but I think this piece of code is okay plus it's quite simple to implement.
Thanks for your help!

Related

How to access returned object from groovy controller in JS file

I am trying to access the returned object from grrovy controller into my javascript code.
Here's the code.
Groovy Controller:
def result = [
data : 'data',
status : 'success',
]
[result: result]
GSP file:
<g:hiddenField name="result" value="${result}" />
JS file:
var jsresult = $("#result").val();
console.log(jsresult);
console.log(jsresult.data);
Here's the console output:
{data=data, status=success}
undefined
Looks like some issue with formatting but not able to find out the root cause. Tried converting it into JSON but still not able to access the properties (jsresult.data).
Please let me know how I can resolve this and let me know if any alternate way of passing data from groovy controller to JS code.
Thanks.
First, make sure your result is being encoded a proper JSON:
<g:hiddenField name="result" value=${result as JSON}" />
Then parse it in javascript:
var jsresult = JSON.parse($("#result").val());
You'll get an object back that you can interact with as you expect.
As far as other ways to do this: there are quite a few, but for simple and arbitrary data transfer to a static page, this is probably the simplest. If you're using ajax requests you can avoid having to place the JSON-encoded data on your page at all, but from what you included here that does not appear to be the case.

Using arrays in JavaScript

I am trying to write a program in javascript in which there is a list of products in an array, and they are sorted in alphabetical order. However, when I enter the code into notepad, and load it up in the website format, it just displays the code I have entered, with no formatting
var products = ["Printer","Tablet","Router","Speakers","Mouse"];
Arrays.sort(products);
System.out.println(Arrays.toString(products));
This is the code exactly as it is in notepad, and in the website bit, it is displayed as one long line of all the programming
You have to surround your code with a script tag:
<script type="text/javascript">Your_code_here</script>
Furthermore System.out.println and Arrays.toString are Java functions. It seems like you have Java confused with JavaScript. I think what you are trying to do is:
<!DOCTYPE html>
<html>
<body>
<script>
var products = ["Printer", "Tablet", "Router", "Speakers", "Mouse"];
products.sort();
var productsString = products.join(" ");
document.write(productsString);
</script>
</body>
</html>
If you point a browser at a URL which returns JavaScript source code, then it will display the JavaScript source code (generally not as a single line those, that suggests a further error in which you are serving it to the browser with a Content-Type: text/html header instead of Content-Type: application/javascript).
If you want to execute client side JavaScript then you need to write an HTML document and import the JavaScript using a <script> element.
Your code will then fail because Arrays and System will be undefined.
Javascript not like java ..to use helper functions in javascript as ..sort,filter,reserve....you can use underscore.js library

Codeigniter - sending json to script file

I query the db i my model like so
function graphRate($userid, $courseid){
$query = $this->db->get('tblGraph');
return $query->result();
}
My controller gets data back from my model and I json encode it like so
if($query = $this->rate_model->graphRate($userid, $courseid)){
$data['graph_json'] = json_encode($query);
}
$this->load->view('graph', $data);
And thats returns me a json object like so
[
{"id":"1","title":"myTitle","score":"16","date":"2013-08-02"},
{"id":"2","title":"myTitle2","score":"17","date":"2013-09-02"},
{"id":"3","title":"myTitle3","score":"18","date":"2013-10-02"}
]
In my view graph I'm loading an js file
<script type="text/javascript" src="script.js"></script>
Now I want to use $data that is being sent from my controller to my view, to my external script.js to use as labels and data to feed my chart. But How do I get that Json data to my external script.js so I can use it?
1 more thing about the json data, isn't it possible to get the output of the json data as
{
"obj1":{"id":"1","title":"myTitle","score":"16","date":"2013-08-02"},
"obj2":{"id":"2","title":"myTitle2","score":"17","date":"2013-09-02"},
"obj3":{"id":"3","title":"myTitle3","score":"18","date":"2013-10-02"}
}
The problem isn't a Codeigniter problem, it's a javascript scope/file inclusion/where-do-i-get-my-data-from problem.
I run into this all the time and have used these solutions:
naming my php files with .php extensions and loading them as if they're views.
Just putting the script that needs data from a view IN the view file where it's used
Using an ajax request in my included js file to hit a controller and get json data.
I use #2 most frequently (for things like datatables where I WANT the js code right there next to the table it's referencing.
I use #1 occasionally, but try NOT to do that because it means some .js files are in my webroot/js dir and some are in teh application/views directory, making it confusing for me or anyone else who wants to support this project.
#3 is sometimes necessary...but I like to avoid that approach to minimize the number of requests being made and to try to eliminate totally superfluous requests (which that is).
You need to print the result of the output json string to the html generated file.
But you need to parse the string with some script. I would recommend you: http://api.jquery.com/jQuery.parseJSON/
For the second question. It is possible by doing:
$returnValue = json_encode(
array (
"obj1" => array("id"=>"1","title"=>"myTitle","score"=>"16","date"=>"2013-08-02"),
"obj2" => array("id"=>"2","title"=>"myTitle2","score"=>"17","date"=>"2013-09-02"),
"obj3" => array("id"=>"3","title"=>"myTitle3","score"=>"18","date"=>"2013-10-02"),
)
);
Print the output using PHP like:
echo json_encode($query);
Then from the client-side (where JavaScript resides) load that JSON that you printed using PHP. This can be done easily using JQuery.
Like this:
$.get("test.php", function(data) {
alert("Data Loaded: " + data);
});
You can find more information about this here: http://api.jquery.com/jQuery.get/
Now you'll need to parse this data so that JavaScript can understand what you got as text from the server. For that you can use the JSON.parse method on the "data" object in the aforementioned example. Once parsed, you can use the object like any other object in JavaScript. You can find more information about JSON.parse here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
I hope that helps.

Build a Javascript Widget : can I call an aspx?

I'd like to create my own JS widget, which it must be dinamic.
I mean, for example, the html generated from the downloaded script :
<script src="www.mywebsite.it/widget/?ID=2&Category=4" type="text/javascript"></script>
must be different from :
<script src="www.mywebsite.it/widget/?ID=1&Category=5" type="text/javascript"></script>
and the Data into HTML should be taken from Database, on my server. So, I need to call an aspx page that create javascript that will create html? Or which could be the solution?
The better way is to use generic handler with .ashx, if you want retrieve data from server and send data in JSON or XML.
Next, the data will be inserted in page with javascript.
So, if I understand well, you do generate an .aspx that contains your template and a javascript that hold the code to navigate in Category as this if you use JQuery :
$.ajax({
url: 'data.ashx?ID=2&Category=5',
success: function(data) {
$('.result').html(data);
alert('Load was performed.');
}
});
Server behind (ashx) :
private readonly JavaScriptSerializer _js = new JavaScriptSerializer();
public void ProcessRequest(HttpContext context)
{
//Do logic and retrieve data here
Categorys c = GetFooById(context.Request["id"]);
context.Response.Write(_js.Serialize(c));
context.Response.ContentType = "application/json";
}
It seems that you'd want to use AJAX.
The script source shouldn't be dynamic (it can't be cached if it is), but the script itself could call whatever page you like to pull back data (say in JSON format) or raw markup to place in a pre-defined element.
Don't use the ASPX page to create javascript if you can help it.
Consider using a JavaScript library such as jQuery to help you.

ASP.NET generating Javascript object

I need to generate a JSON object from server containing data to be cached on client. I placed the following:
<script src='Path to js file on server" />
At the server, I generated my json data and placed them inside the JS file.
I can see the generated JSON object on the client-side something as:
var jsonData = [{}, {}];
However, when I try to access jsonData object, it says, undefined!
Is there another way to generate valid javascript from server side?
Thanks
This is the server-side code:
var items = List<myObj>();
string json = JsonConvert.SerializeObject(items, Formatting.Indented);
StringBuilder sb = new StringBuilder();
sb.AppendLine();
sb.AppendFormat(" var jsonData = {0};", json);
var fileName = Request.PhysicalApplicationPath + "Scripts/Data.js";
System.IO.File.WriteAllText(fileName, sb.ToString());
As for client side:
<script src='#Url.Content("~/Scripts/Data.js")' type="text/javascript"></script>
I tried to use this code on the client:
alert(jsonData[0].Id);
It says, jsonData is undefined!
Regards
ASP part is ok, the problem seemed to lie in javascript variable scoping plane. Possible problems:
You just don't include that js file.
You're trying to access variable before it is initialized;
Variable isn't visible in place, you're trying to access it.
You're not exact in your question and accessing not jsonData, but something like jsonData[0].property
etc.
UPD: Ok, first two options are excluded. Where are you trying to access this variable? Please, show us a portion of code.

Categories