Execute Javascript coming from dojo.xhrGet in symfony - javascript

I am new to dojo and somewhat new to symfony as well and am having a wee problem here: I want to reload a part of my page using Ajax but it includes a Javascript which needs to be executed. This isn't reallly a problem in prototype or Jquery but I just can't figure it out in dojo. (I need to use dojo because it's a part of symfony and already in heavy use on the page I'm supposed to modify. I also know this is probably improped technique but it's just a little mod I need to do and this would be the easiest way ...)
Can you help??
Thanks,
thomas

You can do it by using dojo's require tool
For more information regarding this, take a look at the documentation
dojo.require("my.path.to.file", false, true);
Call this when you want to load the javascript file, mostly after the ajax request is complete. So that if this javascript is to alter/perform some operations on the ajax loaded content placed into DOM, you won't get NOT_FOUND dom exception.

Related

Prevent re-init in ajax

I have lots of page ajax request on my site. I am using jquery hashchange plugin to integrate them.
Now, as I have observed, after I do $(window).hashchange I always have to re-init some other plugins (e.g. fullcalendar, tooltip, and etc.).
I've been trying to google - on how to prevent re-init during ajax request. I've tried it using live and it works but the problem is there are certain plugins that wont need to use .live function especially when it's content-based (e.g. fullcalendar, tooltip (page load), etc.). I've been trying to solve this issue by using:
$(window).on("hashchange")
I can test if the elements exist and RE-INIT THE PLUGINS (which is so dirty for me), and the problem: the plugins wont work/read.
What would be the best approach in initializing plugins once everytime you do it in ajax? Is that even possible?
P.S. still beginning to learn and explore more on ajax.
From what I understand, you want to initialize plugins loaded via AJAX calls on your page. If that's right, you can put in your plugin initialization code in the "success" callback of your AJAX call.
You only need to add the code for the plugins that need explicit initialization.

How to use javascript in Silverstripe CMS?

I'm using SilverStripe 3.0 CMS, and I need to include a Google Map into the CMS.
I'm following this steps, and besides it's a little bit old, the official documentation uses the same methods in the current version of SilverStripe (At least it seems to be the current version documentation).
The issue is in this part of the code:
Behaviour.register({
"#Form_EditForm" : {
initialize : function() {
this.observeMethod("PageLoaded", this.adminPageHandler);
this.adminPageHandler();
},
adminPageHandler : function() {
initialize();
}
}
});
First of all, Behaviour was not defined. I needed to include manually the behaviour.js file that comes within the framework. But now, I get a Type Error:
this.observeMethod is not a function
Can someone give me a hint of what can I do in order to call a javascript function when a page editor is opened in the SilverStripe CMS?
the 'Behaviour.register' call you mention is definitly deprecated and no longer available in the core code, so the docs need an update here.
unfortunately, i couldn't find a documented way to replace this behaviour, but for now the following should work for you, based on the approach in the forum post you mentioned first hand:
find the 'initGoogleMaps.js' script added here:
function getCMSFields() {
Requirements::javascript('mysite/javascript/initGoogleMaps.js');
...
inside this script, remove the Behaviour.register... block, and move the initialize function outside document.ready (or simply remove the document.ready part), so initialize is globally available (you might consider renaming it).
then, add the following inside getCMSFields:
$fields->addFieldToTab('Root.Content', new LiteralField('js', '<script>initialize();</script>'));
this will ensure the initialize function is called every time a page's 'edit view' is rendered inside the cms.
hth
As mentioned by ben,
LeftAndMain::require_javascript('mysite/javascript/initGoogleMaps.js')
is more reliable than 'include-it when needed'. Why?
Because Silverstripe uses Ajax, it is better to load any javascript or css on the first load, so that they are ready when you go to different model admin areas within the CMS in ajax-powered environment. Not loading at the start causes inconsistency and your js, css files will not be loaded when you don't hard-load that admin area.
From documentation: http://doc.silverstripe.org/framework/en/reference/requirements and http://api.silverstripe.org/3.0/class-LeftAndMain.html
The whole "include it when you need it" thing shows some weaknesses in
areas such as the CMS, where Ajax is used to load in large pieces of
the application, which potentially require more CSS and JavaScript to
be included. At this stage, the only workaround is to ensure that
everything you might need is included on the first page-load.
One idea is to mention the CSS and JavaScript which should be included
in the header of the Ajax response, so that the client can load up
those scripts and stylesheets upon completion of the Ajax request.
This could be coded quite cleanly, but for best results we'd want to
extend prototype.js with our own changes to their Ajax system, so that
every script had consistent support for this.
By the way, the ideal place for this line is _config.php in your custom module or in mysite, depending on your needs.
LeftAndMain::require_javascript('mysite/javascript/initGoogleMaps.js')
would work much better

Ajax integrating in Struts with jQuery

I am familier with jQuery,Ajax and JSP Servlets but new to Struts2.I want to know a complete reference of Ajax integration in Struts 2, preferred with jQuery. In stackoverflow also has more quesitons and answers, but still there are few things remaining to know.I need to know few things.
(1) Is there a complete reference how to use Ajax in Struts2 applications. struts2-jquery-plugin (and their showcase also) has many sample codes and demos. But I couldn't find how to handle it in Java classes.Their all samples found in itself are on client side- JSP samples only, no demo shows how the action classes work. No idea what the application returns(XML/JSON or what the server side returns) Their site demos only core functionalities. I want know how to how to handle both side; [in Struts framework] and [how to customize more struts ajax tags in JSP]. If there is any link or advice,it ll be highly appreciated.
(2)
I read Struts 2 In Action book. It has sample codes and demo.Its chapter 8 explains how to work with Ajax( used Actionsupport, another one extending Result class ... ). In Internet,few sample codes found, and they had used in some different way( directly PrintWriter print() the result). But in JSP side, normal javascript had been used. So, according to your best practises (may be more ways), what is your most preferred way to use Ajax? (that means,you use as jquery plugin shows or not depends on Struts ajax tags and just use javascript/jQuery in JSP pages, and the best practices to handle struts classes Write Result class or just use PrintWriter to print the result? Here you may say, it depends on the situation and the taste of the develoer, but what would be according to the industry standards?)
IF someone downvote. please leave a comment, WHY?
You should be using this jquery plugin instead; it is the closest thing the S2 project has to an official jQuery plugin. The one you link to isn't the same.
The most common way to return data to JavaScript (jQuery or not) is to use the JSON plugin or the REST plugin. There are very few reasons to ever write responses manually.

HTML that's both server-side and javascript generated - how to combine?

I'm usually a creative gal, but right now I just can't find any good solution. There's HTML (say form rows or table rows) that's both generated javascript-based and server-sided, it's exactly the same in both cases. It's generated server-sided when you open the page (and it has to stay server-sided for Google) and it's generated by AJAX, to show live updates or to extend the form by new, empty rows.
Problem is: The HTML generation routines are existing twice now, and you know DRY (don't repeat yourself), aye? Each time something's changed I have to edit 2 places and this just doesn't fit my idea of good software.
What's your best strategy to combine the javascript-based and server-sided HTML generation?
PS: Server-sided language is always different (PHP, RoR, C++).
PPS: Please don't give me an answer for Node.JS, I could figure that out on my own ;-)
Here's the Ruby on Rails solution:
Every model has its own partial. For example, if you have models Post and Comment, you would have _post.html.erb and _comment.html.erb
When you call "render #post" or "render #comment", RoR will look at the type of the object and decide which partial to use.
This means that you can redner out an object in the same way in many different views.
I.e. in a normal response or in an AJAX response you'd always just call "render #post"
Edit:
If you would like to render things in JS without connecting to the server (e.g. you get your data from a different server or whatever), you can make a JS template with the method I mentioned, send it to the client and then have the client render new objects using that template.
See this like for a JS templating plugin: http://api.jquery.com/category/plugins/templates/
Make a server handler to generate the HTML. Call that code from the server when you open the page, and when you need to do a live update, do an AJAX request to that handler so you don't have to repeat the code in the client.
What's your best strategy to combine the javascript-based and server-sided HTML generation?
If you want to stay DRY, don't try to combine them. Stick with generating the HTML only on the server (clearly the preferable option for SEO), or only on the client.
Make a page which generates the HTML on the server and returns it, e.g.:
http://example.com/serverstuff/generaterows?x=0&y=foo
If you need it on the server, access that link, or call the subroutine that accessing the link calls. If you need it on the client, access that link with AJAX, which will end up calling the same server code.
Or am I missing something? (I'm not sure what you mean by "generated by AJAX").
I don't see another solution if you have two different languages. Either you have a PHP/RoR/whatever to JavaScript compiler (so you have source written in one language and automatically generated in the others), or you have one generate output that the other reads in.
Load the page without any rows/data.
And then run your Ajax routines to fetch the data first time on page load
and then subsequently fetch updates/new records as and when required/as decided by your code.

Good practice method for loading JavaScript via ajax

Disclaimer: I'm fairly new to AJAX!
I've looked around, and I'm not sure which method to use to load javascript using ajax.
I'm using ajax to request pages that each require their own 6-10 short methods. In total there will be maybe 5-6 of these pages, so an approximate total of 35+ methods.
I would prefer to access necessary javascript as each page that requires it loads.
I've seen a few methods, and I'm not sure which one would best suit my needs:
Include an empty script element in the head, and manipulate the src attribute via. the DOM.
Create a new script element via. the DOM and append it to the document.body (this sounds the same as #1).
jQuery (which I'm already using) has an ajax getScript() method.
I haven't read anything about it, but can I just include a script element as part of the ajax response?
As I'm new to ajax and web development in general, I'm curious as to the ups and downs of each method as well as any methods I've missed.
Some concerns are:
-Will a cached copy be used or will the script download each time an ajax request is made. Note that the scripts will be static.
-Browser compatibility. I use Chrome, but this app will be used across versions of IE >= 7 as well as Firefox.
In a jQuery environment, I'd use getscript(). You're right to wonder about the cache -- getscript includes a cache-busting feature (designed primarily to defeat aggressive IE caching, although of course useful in other scenarios). You can perform the equivalent of a non-cache-busted getscript like this:
$.ajax({
cache: true,
dataType: "script",
url: "your_js_file.js",
success: yourFunction
});
As all the other answers here just say "use jquery" without any further info/explanation/justification, it's probably worth actually looking at the other options you mentioned.
Option#1
could be a little complicated as it requires you to wait until one script has download and run before fetching the next one (as you've only one script element).
Option#2
is better as you can append a second script element to DOM before the first one has finished downloading, without affecting the download/execution.
Option#3
recommended by everyone before me, is fine IF you're in a jQuery environment and already loading the (quite heavy) jQuery library for other uses - loading it for this alone is obviously superfluous. It's also worth noting that $.getScript() and $.ajax() both use eval() to execute the script. eval() is not "evil" in this context as it's a trusted source, but it can in my experience occasionally be slightly more difficult to debug eval()-ed code.
Option#4isn't possible afaik.
Option#5
recommended by Nick Craver in the first OP comment is what I'd go with tbh - if the scripts are static as you say, caching will be more efficient than multiple HTTP requests. You could also look into using a cache.manifest for aggressive caching if you're especially concerned about bandwidth: http://www.html5rocks.com/tutorials/appcache/beginner/
Go with getScript. It essentially does the same thing as the second method, but you don't have to worry about how to listen for load in various browsers (mainly IE).
AJAX response is simply text as far as the DOM is concerned. It has no effect unless you insert that into the DOM somehow.

Categories