Please focus on the technical aspect of this question, and not on the why. The why is obvious: YAML is the most human-readable data serialization format available to man. And therefore, the best.
How can I send YAML via an XMLHttpRequest from the client to the server, without first converting it to JSON, XML or another format?
I am using JavaScript for the client-side code, I can use jQuery if needed. My server-side language of choice is PHP.
According to Wikipedia, the send() method of XMLHttpRequest:
Accepts a single parameter containing the content to be sent with the request. The W3C draft states that this parameter may be any type available to the scripting language as long as it can be turned into a text string, with the exception of the DOM document object. [Emphasis my own]
YAML is a text string. Can it be sent and subsequently parsed correctly on the server-side without using another data serialization format like json, xml etc?
Just set an appropriate content type and send it.
// xhr is an instance of XMLHttpRequest which has been open()ed and had event handlers set on it already
xhr.setRequestHeader("Content-Type", "text/x-yaml");
xhr.send(string_of_yaml_formatted_data);
Note, that most server side languages won't parse it automatically, so you'll need to read the raw data from the POST request body and parse it yourself.
e.g. in PHP:
$raw_yaml = file_get_contents('php://input');
$data = yaml_parse($raw_yaml);
Note: yaml_parse() requires PECL yaml >= 0.4.0
Related
Sometimes when making an HTTP request to download a file (e.g. PDF, XLSX, etc.) from the own webserver, it is necessary to use the HTTP method POST, because it requires dynamic input data. I have been trying different ways to reduce that to one single HTTP request for best performance, but could not succeed.
As JavaScript with the XMLHttpRequest object (AJAX) can not "download" files, I guess it requires an HTML workaround. The only working solution I found for that case is generating a form element wrapping input elements containing the data. I could not find a way how to send boolean values via this, as AJAX is able to. That would mean: it is not suitable for a standardizable implementation.
My question is: How can I download a file via one POST request which can include boolean values (JavaScript)?
In case it is important: The backend system I use is Ruby on Rails
As #Pointy mentioned, boolean values are always translated to strings in HTTP communication. I was wrong about that in my question. That means, converting a JavaScript JSON string or a classic object to an HTML form (then submitting and deleting it) works!
Actually sending an AJAX request and then manually triggering a link click to the generated file has the advantage of being able to use a progressbar.
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 have a JSON object in server side:
String jsonText = JSONValue.toJSONString(users);
and i want to send it to client side to be used in a javascript function, how to do that ?
I am using JSF 2 with Pure JavaScript with no other libraries.
In HTTP, the server doesnt send anything to client-side. The client-side asks for some resource using a request, and the response contains the resource.
Make the JavaScript function send an AJAX request to the server, and make the server answer with this JSON string in the response (by writing the JSON String to the response writer).
See http://api.jquery.com/jQuery.getJSON/ to get a JSON String from JavaScript. The server code is as simple as
response.getWriter().print(jsonText);
The easiest way is to let JSF print the string representation of the JSON object as a JS variable in the same view:
<script>var users = #{bean.usersAsJson};</script>
The correct way, however, is to use a fullworthy JSON web service for this. JSF is a component based MVC framework, not a JSON web service. For that the Java EE stack offers the JAX-RS API. Long answer short: Servlet vs RESTful. Use this preferably in combination with jQuery or whatever JS framework which is able to send Ajax requests and manipulate the HTML DOM tree in basically an oneliner. You only need to take into account that when used in combination with JSF, this can be used for pure presentation only.
The browser must request it, ie that string must sit somewhere in a request handling chain; set the response to that string and the browser will receive it.
I think you wanted to say response the json string.
It can be done by jQuery function getJSON.
It will get the json string and parse it inti hash, then you have to process it for your needs.
API documentation
send your json object to response and get the response in the javascript.
use eval function to evaluate json object.
var jsonObject = eval('(' + request.responseText + ')');
I have an external URL for a JSON file which is hosted on another domain (not mine). Is it possible to parse this information with javascript only? Here is a sample of the JSON data. I only want to get "q" values.
[{"url":"http://website.com/?q=who+is+ip+search","q":"who is ip search"},{"url":"http://website.com/?q=eclipse+visual+editor","q":"eclipse visual editor"},{"url":"http://website.com/?q=partition+recovery","q":"partition recovery"},{"url":"http://www.website.com/?q=katzenfurz","q":"katzenfurz"},{"url":"http://website.com/?q=rtfm","q":"rtfm"},{"url":"http://website.com/?q=Google+ist+Dein+Freund","q":"Google ist Dein Freund"}]
Browsers have native parsing methods -> JSON.parse() and JSON.stringify()
There are also several libraries that add the ability to parse JSON ...
http://www.json.org/js.html
http://developer.yahoo.com/yui/json/
http://api.jquery.com/jQuery.parseJSON/
Eval is sometimes used directly within JavaScript - but there are often security concerns when using this method -> http://en.wikipedia.org/wiki/JSON#JavaScript_eval.28.29
Yes, there is a built-in JSON.parse() function. Just pass the string to the function.
var obj = JSON.parse( data );
Live demo: http://jsfiddle.net/h4XTP/
JSON you know is JavaScript object; yes you can parse it in JS. Though as you have remote server as data publisher, you have to configure that server for a callback function.
To make the remote request, you insert a new script tag into your page, which will allow you to specify a remote URL. The reponse back will load a JSON object as a parameter of the callback function you specified in the request.
Once read somewhere. Hope it helped.
I'm looking to write some Javascript which will make an Ajax PUT or POST request to an HTTP server. I'm assuming that the information which gets passed as the argument to request.send needs to be in XML format. Could somebody shoe me an example of how to create this XML and pass it to request.send([Entity-body]) as the entity-body.
Thanks!
The "xml" in XmlHttpRequest is entirely superfluous; there's never been a requirement that the request or the response is in xml format.
In fact, it's just as common to send JSON (JavaScript object notation) instead of xml.
So, don't use xml unless you want to. Just send any string you want.
You don't have to send xml, you can send any arbitrary string.
an example for http post would be
request.send("id=1&somattribute=value&etc=etcetc");
where you have name value pairs
name=value
separated by &