Embedding JavaScript into an AJAX partial response - javascript

Is it considered bad practice to embed javascript into partials returned via AJAX?
Let's say that on http://mysite.com, I have a button that gets a form via AJAX.
Now let's say that I want to add some javascript event handlers to this form using jQuery (for validation and such).
The current ways to do this seem to be:
In the AJAX callback that returns form, I can setup event handlers
for the tag.
I don't like this approach because it puts code that controls my form in two places: in the partial being rendered, and in the global javascript file(s) being included.
Instead of returning a form from the server side, do everything client side. When a response from the server is required (for example, to validate the form), return JSON from the server, and create the resulting HTML elements (things like error messages) in JavaScript.
Now this approach makes me feel as though, I'm using JavaScript to create HTML elements instead of using more powerful server side tools (template languages) to do it.
I feel like the solution involves embedding JavaScript code into the HTML returned by the AJAX partial, so that it's an independently functional component of my application, and all the code is in one place.
Is there a cleaner way of doing what I'm trying to do here?

I'm not sure the argument can be made today that javascript is somehow inferior in terms of "power" when compared to other back-end languages... I think maybe because today javascript is a valid back-end language?
I think the second option makes sense because you're containing client/interface code, and segregating server-side logic for data manipulation and presentation.
There are plenty of javascript template libraries that work very well in my opinion, that is if you don't want to go the full javascript MVC route.

Related

Best (or correct) way to use JavaScript with C#/Razor?

What is the best and maybe correct way of mising JavaScript code with Razor?
At the moment i put my JavaScript code in an external JavaScript file "external.js" but there i have the problem that i can not access the C# variables of my model directly (i can do it, but it makes the whole thing a little bit complicated). This only works with Razor-Syntax #Model.Variable when i embed my JavaScript Code inside the view in the -Section/Tags.
So i thought about this situation and don't find an answer. I read and thought it would be the best to put all JavaScript code in one file, so that the browser loads the whole stuff only one time and then read out of the cache (Performance). But could it be better to write the JavaScript code inside each View instead of putting into one huge file?
Putting your Javascript directly into your view isn't going to affect the load of your page in any significant manner (unless your Javascript really is a behemoth).
It will be transported (and subsequently cached) when the view is requested.
If you're wanting to use your razor variables directly in Javascript, then having it in the view is your most sensible option
That is, of course, the view is intended to be used as a partial - in which case you probably want to rethink the design

Django saving models by JS rather than form submissions?

I have a contract job for editing a Django application, and Django is not my main framework to use, so I have a question regarding models in it.
The application I am editing has a form that each user can submit, and every single model in the application is edited directly through the form.
From this perspective, it seems every model is directly a form object, I do not see any model fields that I could use for custom variables. Meaning instead of a "string" that I could edit with JS, I only see a TextField where the only way it could be edited is by including it on a form directly.
If I wanted to have some models that were custom variables, meaning I controlled them entirely through JS rather than form submissions, how would I do that in Django?
I know I could, for example, have some "hidden" form objects that I manipulated with JS. But this solution sounds kind of hacky. Is there an intended way that I could go about this?
Thanks!
(Edit: It seems most responses do not know what I am referring to. Basically I want to allow the client to perform some special sorting functions etc, in which case I will need a few additional lists of data. But I do not want these to be visible to the user, and they will be altered exclusively by js.
Regarding the response of SColvin, I understand that the models are a representation of the database, but from how the application I am working on is designed, it looks as if the only way the models are being used is strictly through forms.
For example, every "string" is a "TextField", and lets say we made a string called "myField", the exclusive use of this field would be to use it in templates with the syntax {{ form.myField|attr:"rows:4" }}.
There are absolutely no use of this model outside of the forms. Every place you see it in the application, there is a form object. This is why I was under the impression that is the primary way to edit the data found in the models.
I did the Django tutorial prior to accepting this project but do not remember seeing any way to submit changes to models outside of the forms.
So more specifically what I would like to do in this case: Let's say I wanted to add a string to my models file, and this string will NOT be included/edited on the form. It will be invisible to the user. It will be modified browser-side by some .js functions, and I would like it to be saved along when submitting the rest of the form. What would be the intended method for going about doing this?
If anyone could please guide me to documentation or examples on how to do this, it would be greatly appreciated! )
(Edit2: No responses ever since the first edit? Not sure if this post is not appearing for anyone else. Still looking for an answer!)
There is some terminology confusion here, as SColvin points out; it's really not clear what you mean by "custom variables", and how those relates to models.
However your main confusion seems to be around forms. There is absolutely no requirement to use them: they are just one method of updating models. It is always possible to edit the models directly in code, and the data from that can of course come from Javascript if you want. The tutorial has good coverage of how to update a model from code without using a form.
If you're doing a lot of work via JS though, you probably want to look into the Django Rest Framework, which simplifies the process of converting Django model data to and from JSON to use in your client-side code. Again though DRF isn't doing anything you couldn't do manually in your own code, all without the use of forms.

How can I prevent someone from altering or avoiding my JavaScript logic when adding buttons to jQuery UI dialog?

I am using a jQuery UI dialog and I am adding buttons to the dialog in JavaScript based on some entitlements logic. (I pass in a boolean from my server-side AJAX call if I am entitled and then I show different buttons based on that flag.)
What concerned me is what is preventing someone from using developer tools like Firebug and putting a breakpoint on that line that does the check and either altering the flag or dragging to skip over that entitlements check.
So my question is specific to adding buttons onto a jQuery UI dialog (because its not like you can add the buttons from the server side since its a jQuery plugin), but I guess it highlights a more general point around any entitlements logic on the client side being "vulnerable". So if there are any general best practices around this point I would be interested (but still looking for an answer to my specific example).
NOTE: I am also doing a server-side entitlement check on POST as a backup, so I am still "protected" but I am still concerned about the point above.
Nothing prevents people from altering client-side code, it is inevitable.
You can, however, add buttons of the kind of "server-side", you just retrieve a string using the AJAX call, which happens to be a JavaScript function that adds buttons. And on the client side do eval() on that string which will execute the retrieved JS function and will add the buttons. Moreover, you can transmit your entire JavaScript code that way, so the client cannot skip anything since all is being executed in the eval().
A quick example:
Server-side function returns
string banana= "alert('test');";
return banana;
and client side does
eval(response.d);
Here is a theoretical example: FIDDLE
You cannot control what clients will do with your scripts, nor what requests they will make of your server. You must design your back-end API (not your JS client) to be the "gating mechanism" between the user and your system. It's best not to think of the JS as part of your system, but as a separate client that you ship as a reference implementation for your API.
But, if you wanted to at least make it difficult for users to mess with your code, you could minify and concatenate your JS scripts with something like Closure.
As the other person suggested, you cannot implement security on the client for exactly the reason you point out. You could use basic auth, or try setting up a token based approach.

need to call client side javascript from vb.net or vice versa or write to DOM from vb.net

I have a web application that utilizes javascript, jquery, and vb.net. I have a button that, when clicked, causes a jquery click function to be called. It sets a few variables (based on user inputs) and then calls a javascript function that calls a server side Pagemethod (which calls a DLL to do the calculations, etc.) The results come back and I use Tablesorter to display the results. This worked very well until the need arose for the drop down controls on the page to be bound to values in a table.
Of course, the drop downs are bound in the server side code in the Page_Init Sub. That also means, however, that I cannot access the selected items in those dropdowns from the client side javascript/jquery (or can I?).
I have the controls defined on the server side (Protected WithEvents) and am able to bind and refer to them on the server side...outside of the Pagemethod, that is. Since it has to be declared as Public Shared, it won't allow me to reference the page controls since they are not explicitly defined in that Pagemethod.
I thought I would just rewrite the jquery click event on the server side, but that presents me the problem of getting the results back to the client side to be rendered by Tablesorter.
If there was another (or better) way to call the server side code from javascript so I wouldn't have to use a Pagemethod, that would conceivably work also.
I also kicked around the idea of writing the table html from the server side code and then Tablesorter would be able to render it, but I haven't found a good way yet.
To potentially complicate the issue, I'm using master pages. The main master page contains the jquery and javascript code, the other master page applies to a subgroup of pages in my app (including the page I'm working with now) and is where the button in question actually resides.
I've tried the "<%= %>" method, but I cannot get the code to recognize the variable.
I can post code, if needed, but my question is more general in nature regarding methodology, rather than a specific syntax for my scenario.
Thanks in advance for any suggestions!
I managed to solve the issues I was having using Client Callbacks as described in this article. It was exactly what I needed, however, I did have to pass in a concatenated variable. I needed two variables to check for certain conditions and the Callback only accepts one.

How to use JavaScript MVVM/MVC with pre-loaded data

I want to load an HTML page with existing data (a list of comments or widgets or whatever), then use Javascript to render additional data in the same format as it is input by users interacting with the page.
I'd like to use a model stored in a JavaScript object that represents both existing data on the page as well as new data from user input, then observe to the model to update the DOM when it changes.
I'd like to render JS templates to display data entered by users quickly, without hitting the server again.
I would like to avoid writing server-side and JavaScript templates that render the same data.
To solve the first problem of building the initial model it seems like the options are, in order of preference:
Use JavaScript to pull the data rendered in HTML to build the initial model, or
Render JSON directly to the DOM and build the JS object from that, or
Hit the server again after the page is loaded as an ajax call to get the data as JSON
To avoid having server-side and client-side templates to display the same thing:
Use use something like Pure to build templates from the DOM, or
Only use JS templates and use one of the second options above to initially render the page (populate them from JSON rendered to the DOM or make an ajax call to get JSON to populate them).
Use a templating system that works on both the server and client.
I feel like none of these solutions are particularly elegant, and I'm curious as to what other patterns I may not have thought of or if there is a common solution.
My environment is Rails 3, but the problems are applicable to any server -> HTML/JS setup. I can see how some of this might be easier with something like Node.js but I'm principally interested in solutions that would apply to Rails.
There's so many ways to accomplish this. I have been struggling with this same issue. I think that once the complexity of your web app reaches a certain threshold you have to resort to javascript to keep the state correct. Jquery (among other dom manipulation frameworks) really help but at a certain point it can become spaghetti code.
I just touched this binding javascript library called Knockout. It's pretty elegant and simple to use it tries to follow the MVVM pattern by allowing you to create a ViewModel with observables that you can bind html elements so that their values and attributes change based on your ViewModel values.
If you're creating dynamic html you can always embed the initial values of the javascript ViewModel along with the html of the page so that you can avoid that initial ajax call.
Out of the box it is compatible with jquery templates which just makes dom manipulation a breeze. I've just started using it and I'm loving it so far.
Hope that helps.

Categories

Resources