Django AJAX Navigation - ajax

As a test i have have decided to see if i can get the hashchange navigation trick think working with my django app...
So far i have it at the stage where the hash change triggers and only needs to load the data in, this is where i have problems.
Now, I am new to django and django/ajax and i dont know where to start, did a few googles and had no luck. In a nutshell I need a way to load in the pages without the template using the extend syntax.. Would i just be able to parse an additional value to the url and exclude it from the template?? im not sure
Please give some code guidance or something

Your template creates the html that is sent to the browser, once it reaches the client your template can't make changes on that page, the page would need to be reloaded for the template to make any changes. So your options when the hash change is triggered is to either have the information you want load as part of the page but be hidden, which means you must know everything the user needs when the page loads, or use AJAX. With AJAX we can make changes without reloading the page when the user gives us new information by making a XMLHttpRequest using Javascript, which doesn't have to return XML it can be JSON or even just a singe text string. So when your hash change triggers you will be sending a request to the site, usually a GET or POST, and a script on the site will process the information sent from the client side and respond accordingly. Here is an example that would be inside the change trigger function
data = "somedata";
request = new XMLHttpRequest(); //create the request object
request.open("POST", "app/handler", false); // set its parameters
request.send("data="+data); // send it to the server
response = request.responseText; // get the response
responseHandler(response) // do something with the data the server sent back
On the server side this could be the sole purpose of the app. All the formatting can be done with the base template, javascript and css for the site. Just load the new information after each response. There are some AJAX libraries for Django, check out the wiki page or look into the django.core.serialization which will let you return your apps model as json, xml or yaml.
from django.core import serializers
def my_json_view(request):
data = serializers.serialize("json", MyModel.objects.all()[:5])
return HttpResponse(data, mimetype="application/javascript")

Related

How to load view containing data with ajax?

I have Restful controller that renders a view with data from database and I want to load this view with its data in another view via ajax. There is a problem "undefined variable". Is there any solution?
When you pass variables to your view they are only available on the server side while the view renders and then they are discarded. What this means is that the variables are only available to the php of your application and then they are gone by the time the view has been rendered and sent to the visitors web browser.
If you try to use the variables with JavaScript then you are running the JavaScript on the client side (as opposed to the server side). The variables that you pass to your view do not exist on the client side where your JavaScript runs.
From what it sounds like. You are defining a variable in your controller via laravel. Then you are passing the variable from the controller to the view. The view is then rendered as html and sent to the visitor's computer (the client) which the html is then loaded and that is when the JavaScript starts to load.
That's the problem, now possible solutions.
First you could send the variable (assuming it is simple data and not like an object) to the browser through laravel flash variables which are actually stored on one time cookies on the client side. Then you use JavaScript to access the cookie and get the data then storing it to a js variable and using it in your script.
Second you create an Api to respond to your http requests and then send an Ajax request from your JavaScript to the api to get the data. Then you would store it in JavaScript and use it. This allows complex data like objects because you would use the JSON format to send information to respond to the Ajax call. While cookies are restricted to (5kb I think) there is really no theoretical limit to JSON data.
I hope that helps and I hope I'm understanding your problem.
Would need to see your javascript before anything, but usually for me this means a misspelled element id or misspelled a reference file

Scala Play - calling controller method from view doesn't load a new page

I display information, gather some user's input, and call a controller method using ajax/java script call from the view. However, instead of displaying a new/different html page, the controller method returns back to the original html page that I called jscript from.
Is this because of ajax call? How do I make sure that controller method would display the html file it's supposed to, instead of staying on old html page?
It sounds to me like what you want to do is to open a different url than the one you are on. To do that you do not use ajax. Instead try using javascript to change window.location to tell the browser to go to the url (or 'call your controller'). It looks like this:
window.location.assign("/your/controller/url"); // or
window.location = "/your/controller/url";
There is more to read about it here: https://developer.mozilla.org/en-US/docs/Web/API/Window.location
You can think of ajax as a separate little browser that lets you call the web server but letting you handle what comes back with javascript rather than always showing it to the user. So if you want to do the call with ajax but get the response HTML into your page, you are responsible for taking that response and inserting it into the DOM.

Pre-populate Ember DS.Store via ajax

Reading the Ember guide about the data store it's not clear how you pre-populate the store with your data. I see you can set up the RESTadapter with the host name, and the 'store.find' method will trigger a 'get' request if the data is not cached, but how can I initialize a DS.Store with JSON data via ajax before ever doing a find?
Ember guide model HTTP
The context for this is, a single page app that on page load gets a blob of json, which is used to model out the rest of the site. The end result gives the illusion that the site contains multiple pages.
Sounds like you want this.store.pushPayload(..)
http://emberjs.com/api/data/classes/DS.Store.html#method_pushPayload
Note that you only have access to the store inside Routes and Controllers. Consider putting this inside the activate hook of App.ApplicationRoute
http://emberjs.com/guides/routing/defining-your-routes/#toc_initial-routes
http://emberjs.com/api/classes/Ember.Route.html#method_activate

AJAX POST does not always occur

I have tried to incorporate AJAX into an application that I built.
The basic function is:
-The user clickes a button, which triggers JS code that makes an AJAX call that does a POST to a Servlet(sending account data).
-The Servlet(which has an EJB injected into it), communicates with an EJB through it's local interface.
-The EJB(on init) initializes a DAO object, injects an EntityManager into it, and uses that DAO object to communicate with a database through JPA (Hibernate as the provider).
-The local interface methods of the EJB return Data Transfer Objects, which are parsed in the Servlets doPost() method, and the DTO's are used to build an HTML table(String) that the Servlet responds to the AJAX call with.
-On the client side, I use that HTML table(responseText) to update a div on the page.
I have 2 questions:
1) Is using a data-centric approach to the AJAX call (returning an HTML table instead of JSON Strings) a common choice in enterprise level applications that make use of AJAX?
2)I've noticed that sometimes the POST is not even called. It seems to be intermittent. I tried to add the Cache Control header, but that doesn't seem to work. This concerns me especially when I think about eventually deploying the application to production, that maybe AJAX is not the way to go, but when it works, the application works smoothly.
1) Using AJAX to submit data or update the web page is very common. Page at a time applications are the old way web applications used to be done where you would need to reload the entire page just to update a little bit of information - which would be inefficient and not to mention would create a bad user experience. These days, updating just "Part of a page" is very common and is mostly done using AJAX, and if not WebSockets.
Now you question regarding updating the page using the servers response which is HTML - to update the page, or just get a JSON String, and manipulate the DOM (ie adding tables etc). I have used a combination of these. For example if needed to add a row to a table, you could get the server to generate the HTML using a tempting engine (groovy or similar). In addition you you need a response code, so you can package the HTML and Response code in a JSON, and send it back to the client. Any combination of these works depending on your use case.
JsonObject json = new JsonObject();
json.addProperty("responseCode", responseCode);
json.addProperty("html", html);
2) You can write a simple script to send multiple requests to the AJAX url to see if it is the server that is not able to handle the amount of requests. If it works, then you can narrow down the problem to be client side. Make sure you are not using blocking techniques. You can also setup a callback function to see if there is any response if any. AJAX Post is similar to a normal POST request, just make sure you have some indicator for the user notifying them that the request is in progress/complete.

How do you convert a form with method="get" to a mod_rewrite url?

I have a PHP MVC Web App and Apache mod_rewrite rules already working fine, but when I create forms using method="get", the submitted URL looks like
contact/submit?a=b&c=d
I would like my form to submit to
contact/submit/a/b/c/d
Both posting and getting the form work fine on the server side, but when using post method, the back button always asks for reposting the form values and furthermore I want the strings in the URL for SEO. I think JQuery might let me intercept the form submit event and refresh to the url dynamically, but it it seems there must be an easier way to do it that I am missing.
You could use the POST->REDIRECT->GET pattern that Spring Web Flow utilizes. This would allow you to post as you wish and then redirect to contact/submit/a/b/c/d. It would also solve the problem with the back button asking you if you want to resubmit your form data. See this related article.
The GET method uses standard query string arguments to pass form data via an HTTP GET request.
The HTTP GET request is not intended to modify any data on the server. POST is designed for modifying data on the server.
GET may be cached. POST will not.
/a/b/c/d is not a standard format (as in RFC) for passing data. However, for requesting data or URLs to post to, that has become popular.
So, if you are updating server data, just use a POST -> REDIRECT -> /a/b/c/d.
If you are just reading data from the server, then you will need to use a bit of Javascript to read your form values and construct a query string, and then go to it with window.location = ...
Have fun!

Resources