I've got a general question about AJAX. Is it okay to send JavaScript in an AJAX response and execute it? Or is the only elegant way to respond either with JSON or plain HTML?
My problem is that I am searching for the best way to handle AJAX requests which are leading to the insertion of HTML OR the execution of JavaScript, depending on user data.
Thanks a lot.
I would think that the JavaScript function that would be executed after the AJAX response would be standard for everyone aside from some variable. If that is the case, you should include the JavaScript function in your scripts file that gets loaded normally in the . Then have the AJAX response come back with the variable that you need, like the user ID. Then use that variable to call the JavaScript function normally instead of injecting a new function each time.
If HTML is returned you can insert it directly into the DOM on a successful AJAX request.
I think the way to go would be to always return JSON even if it's an HTML response. The JSON response could be something like:
{"responseType":"HTML", "varID":null, "payload":"<div>some html</div>"}
If the response were type JS then the varID could have that variable and the payload could be null. That's just an example but you could do something similar to standardize the response but handle both scenarios.
No it's ok to do so, in jQuery $.getScript do just that, it get the file via ajax and then evaluate it. Which is why no script tags are ever added when using getScript
Executing javascript received by an ajax call is a bad idea as this can lead to XSS style attacks (eval is evil and all that jazz).
An AJAX response is best served up in JSON format and then the client side scripting can act in accordance with the JSON it receives.
Related
First of all: sorry for my bad grammer. English isn't my native language, but i will try to exlpain my problem as simple as i can.
I'm working on a web-application, where user can enter a link. (Question 1) This link should be send to the server/servlet and will be progressed to other things. (Question 2) After the progression, the servlet will send a json-array (?) back to the javascript-part of my app.
I'm completly new to this kind of stuff, but its very important to me, to find out how this works or better, how i can make this work. Its actually very simple, but i used plenty of weeks and cant figure it out.
The application is using the SAP UI5-libs (Question 3), where i would also like to know, if there is any possible way, to parse JSON with the UI5 libs.
I hope, i could explain my problem good enough, so i can get some help. Thanks to all!
The 'sending' of the string to the server/servlet would happen via ajax in either POST or GET form. That is up to you.
I recommend you use a javascript plugin like jQuery (JQuery Ajax API) because the regular ajax code is a bit messy.
As for the servlet/server communicating back to the client is as simple as writing to the page. In a typical servlet context it would be something like
out.print("This is a message");
where Ajax automatically returns the content of the entire page upon callback.
So in conclusion:
Consider test.jsp your servlet. I wish to send "Hi" from the client (being the browser) via GET to the servlet and I want the servlet to say "Hello" back.
I would open an ajax request of type GET to the url "test.jsp?param=Hi". In the servlet I receive this page request and process it. The servlet discards the parameter because it is not used and outputs "Hello" to the page.
In the client the ajax will have returned "Hello" and I can use this to put it into a var or whatever and all of this happened while not refreshing and not navigating in the original document where I did the javascript.
Another way is using websockets where you basically use sockets in javascript to send and receive any kind of data.
Also please check out this possible duplicate question: How to send a string to a servlet from javascript using xmlhttprequest
in my js script tag I hv a var that store data of my ajax success callback. let say it's $result. How can I use it in php? I don't want to directly use for example $('#element').html($result) to manipulate the DOM.
You don't need to send the response to browser instead of that you can use the request and manipulate as you want it in server side that is in php. It is not necessary to send the response back to client.
You should manipulate/Filter the result before getting it from ajax and then use it to manipulate DOM/or for whatever purpose you like.. I guess this is the best option.... Else it'll raise the iteration time and page load time.
So just manipulate it before returning from the ajax file
and if you wish to use it in php which will load it again then why to use ajax.
What do I need to on the server side to allow someone to get data from that server using JSONP. And what do I need to do on the user side as well? I want to use JSONP as an alternative to an XMLHttpRequest.
It won't work out of my Firefox extension, because of the same-origin policy. So, people recommended JSON, but I am pretty lost after searching for tutorials and guides on the internet.
Thanks for the help!
Assuming your server is running PHP, you just need to add 'callback' GET request.
<?php header('content-type: application/json; charset=utf-8');
$data = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo $_GET['callback'] . '('.json_encode($data).')';
And on client side (using jQuery):
$.ajax({url: 'http://site.com/data.php', dataType:'jsonp'});
The PHP code above is just for demo, don't forget to sanitise $_GET['callback']
That said, if your issue just the same origin policy, you'll probably just need to allow cross-origin from the server side, and everything should work.
On the server side, all you have to set up is a web resource (e.g., page) that accepts a GET request and returns the data using the JSON-P convention, which is:
callback({"data": "here"});
...where the function name ("callback" in that example) is usually taken from one of the query string parameters (by convention, the parameter "callback"), and the data is JSON text (although technically it could be anything that's valid in a JavaScript object literaly, the convention with JSON-P is to restrict yourself to what's valid in JSON). So for instance, let's say that the request looked like this:
http://example.com/foo.php?callback=bar
That calls the page foo.php (doesn't have to be PHP, can be any dynamic server-side system), telling it that the function we want it to call is "bar". Our response would be:
bar({"data": "here"});
On the client side, you have to add a script element to the page dynamically, and also add the callback function that will get triggered by the JSON-P response. Usually you want to give that function some random name, and remove it when you're done.
Here's a complete example as an answer to another question here on Stack Overflow. You may have to adapt it slightly for use in a Firefox add-on, but the concepts are the same.
jsonp is json with a wrapper, so you can fake ajax requests to another server by dynamically inserting new <script> tags, with src's pointing at the other server. The wrapper essentially makes the jsonp return stuff be a valid javascript function call that can be executed to extract the standard json data within.
Generally, in an insecure 'just to demo' version, you'd have something like this:
function unwrap_jsonp(data) {
eval(data);
}
The remote server would return the following literal text:
unwrap_json("{'this':'is','sparta':'!'}");
Note that this is literal Javascript plaintext code, which is executed and "unwraps" the embedded JSON string back to a native javascript data structure.
Most JSONP services allow specifying an extra parameter via the query string to name the handler function you want to wrap the response in, e.g.
http://example.com/getjsonp.php?callback=unwrap_json
I'm looking for a straight forward list(with any notable information to match the point) of the separate processes involved from initiating the request object to the user seeing the end result in AJAX?
Thanks.
Okay, I'll give it a shot.
Initiate a request to the server from JavaScript. At some level this is XmlHttpRequest but you are better off using a library such as jQuery to help.
Get a response back from the server. Usually the response is JSON or HTML. Using XML is not recommended because parsing XML in JavaScript is not fun.
Update the HTML DOM to show the results from the server. This is very application-specific. But again using jQuery or some other library makes this easier.
How do I design a Django/Javascript application to provide for conditional Ajax responses to conventional HTTP requests?
On the server, I have a custom-built Form object. When the browser POSTS the form's data, the server checks the submitted data against existing data and rules (eg, if the form adds some entity to a database, does that entity already exist in the database?). If the data passes, the server saves, generates an ID number and adds it to the form's data, and passes the form and data back to the browser.
if request.method == 'POST':
formClass = form_code.getCustomForm()
thisForm = formClass(data=request.POST)
if thisForm.isvalid():
saveCheck = thisForm.saveData()
t = loader.get_template("CustomerForm.html")
c = Context({ 'expectedFormObj': thisForm })
(Note that my custom logic checking is in saveData() and is separate from the html validation done by isvalid().)
So far, standard Django (I hope). But if the data doesn't pass, I want to send a message to the browser. I suppose saveData() could put the message in an attribute of the form, and the template could check for that attribute, embed its data as javascript variable and include a javascript function to display the message. But passing all that form html back, just to add one message, seems inelegant (as does the standard Django form submission process, but never mind). In that case I'd like to just pass back the message.
Now I suppose I could tie a Javascript function to the html form's onsubmit event, and have that issue an XMLHttpRequest, and have the server respond to that based on the output of the saveData() call. But then the browser has two requests to the server outstanding (POST and XHR). Maybe a successful saveData() would rewrite the whole page and erase any potential for conflict. But I'd also have to get the server to sequence its response to the XHR to follow the response to the POST, and figure out how to communicate the saveData outcome to the response to the XHR. I suppose that is doable, even without the thread programming I don't know, but it seems messy.
I speculate that I might use javascript to make the browser's response conditional to something in the response to the POST request (either rewrite the whole page, or just display a message). But I suspect that the page's javascript hands control over the browser with the POST request, and that any response to the POST would just rewrite the page.
So can I design a process to pass back the whole form only if the server-side saveData() works, and a message that is displayed without rewriting the entire form if saveData() doesn't? If so, how?
Although you can arrange for your views to examine the request data to decide if the response should be an AJAXish or plain HTML, I don't really recommend it. Put AJAX request handlers in a separate URL structure, for instance all your regular html views have urls like /foo/bar and a corresponding api call for the same info would be /ajax/foo/bar.
Since most views will examine the request data, then do some processing, then create a python dictionary and pass that to the template engine, you can factor out the common parts to make this a little easier. the first few steps could be a generic sort of function that just returns the python dictionary, and then actual responses are composed by wrapping the handler functions in a template renderer or json encoder.
My usual workflow is to initially assume that the client has no javascript, (which is still a valid assumption; many mobile browsers have no JS) and implement the app as static GET and POST handlers. From there I start looking for the places where my app can benefit from a little client side scripting. For instance I'll usually redesign the forms to submit via AJAX type calls without reloading a page. These will not send their requests to the same URL/django view as the plain html form version would, since the response needs to be a simple success message in plain text or html fragment.
Similarly, getting data from the server is also redesigned to respond with a concise JSoN document to be processed into the page on the client. This also would be a separate URL/django view as the corresponding plain html for that resource.
When dealing with AJAX, I use this:
from django.utils import simplejson
...
status = simplejson.dumps({'status': "success"})
return HttpResponse(status, mimetype="application/json")
Then, AJAX (jQuery) can do what it wants based on the return value of 'status'.
I'm not sure exactly what you want with regards to forms. If you want an easier, and better form experience, I suggest checking out uni-form. Pinax has a good implementation of this in their voting app.
FYI, this isn't an answer...but it might help you think about it a different way
Here's the problem I'm running into...Google App Engine + jQuery Ajax = 405 Method Not Allowed.
So basically I get the thing to work using the outlined code, then I can't make the AJAX request :(.