4

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?

Jimbo
  • 24,043
  • 14
  • 77
  • 118
  • You realize that AJAX requests are a plain regular HTTP request like any other? They just happen to be done in the background of a webpage by code, instead via direct human intervention. If some data format can be sent via HTTP by clicking/submitting a form, then it can go via AJAX, because they're essentially exactly the same process. – Marc B Jul 31 '14 at 15:42
  • 1
    **cv-pls**: http://stackoverflow.com/questions/25062649/how-can-i-send-yaml-over-ajax/ – Jimbo Aug 01 '14 at 11:04

1 Answers1

5

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

Community
  • 1
  • 1
Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205