I have a serverside function:
string foo(string input_string);
for example:
foo("bar") returns "baz"
and have wrapped this function into a HTTP server such that:
POST /foo HTTP/1.1
...
bar
will return:
HTTP/1.1 200 OK
...
baz
ie a POST request with the input string as the HTTP Message Body will return the output string as the HTTP Message Body of the 200 OK.
Now in my javascript on the web page I have two functions:
function sendFoo(input_string)
{
??? // should asynchronously start process to POST input_string to server
}
function recvFoo(output_string)
{
...
}
When I call sendFoo I would like the POST to be made asynchronously to the server and later when the response is received I would like recvFoo called (perhaps in another thread or whatever) with the Message Body of the 200 OK.
How do I implement sendFoo above? I am currently using jQuery, but a solution in pure javascript is ok too. (I can also modify the server if need be?)
Solution:
function sendFoo(input_string)
{
$.ajax({ url: "/foo", type: "POST", data: input_string, success: recvFoo });
}
jQuery post will do the job:
$.post('foo.html', {'varname' : 'bar'}, function(data) {
recvFoo(data);
});
Very well laid out question, thanks.
XMLHttpRequest
object's open()
method allows you to specify the HTTP method while the send()
method allows to specify the message body, e.g.
var xhr = ... // obtain XMLHttpRequest object
xhr.open('POST', '/foo'); // HTTP method and requested URL.
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
recvFoo(xhr.responseText); // Will pass 'baz' to recvFoo().
}
};
xhr.send('bar'); // Message body with your function's argument.
No need to fallback to classic JavaScript
$.ajax({
url:"URL of foo...",
type: "POST",
data: "what ever",
success: recvFoo
});
Or the post
option:
$.post('The url of foo', {input_string : 'bar'}, recvFoo);