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 });
}
"Raw Ajax", in simple words, is the use XMLHTTPREQUEST to communicate to the database server. Using the XMLHTTPREQUEST object, we can communicate to the database server without posting the full page, this really improves the performance of the application.
The ajax() method can send all type of http requests. The following example sends http POST request to the server. Example: Send POST Request. $.ajax('/jquery/submitData', { type: 'POST', // http method data: { myData: 'This is my data.'
The url parameter is a string containing the URL you want to reach with the Ajax call, while settings is an object literal containing the configuration for the Ajax request. In its first form, this function performs an Ajax request using the url parameter and the options specified in settings .
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With