Basic "Raw" Ajax Call - javascript

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 });
}

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);

jQuery post will do the job:
$.post('foo.html', {'varname' : 'bar'}, function(data) {
recvFoo(data);
});
Very well laid out question, thanks.

Related

Javascript processes 200 response before server sends the 200

I have a timing problem with an ASP.NET core 5 system I'm working on. My page shows a DataTable with id='outsideDataTable', and when an item is selected a modal bootstrap dialog is shown. The submit button invokes method submitModal() which does this:
$.ajax({
type: 'POST',
url: '/api/Submit',
dataType: 'json',
statusCode: {
200: SubmitDone()
},
error: 'SubmitError',
data: $('#ModalForm').serialize()
});
The /api/Submit function calls the server's Submit function which does an update to the database. None of the C# code uses async coding. The database interface is NPoco. At the end of the update the function calls Ok() which I believe returns the status 200 to the ajax call.
[HttpPost("api/[action]")]
public IActionResult Submit(
int recordId,
... other formdata ...)
{
if (recordId == 0)
{
var sr = new Record() { ... fill with form data ... };
db.Insert(sr);
}
else
{
var sr = db.Single("select * from Records where recordId=#0", recordId);
if (sr == null)
return BadRequest($"Couldn't find record with ID={recordId}");
... update sr with form data ...
db.Update(sr);
}
return Ok();
}
The OK() function returns status of 200 back to the client, which should now execute the js SubmitDone() function.
function SubmitDone() {
$('#ModalDlg').modal('hide');
$('#outsideDataTable').DataTable().draw();
}
The problem is that when the outsideDataTable is redrawn from within the SubmitDone function, it will retrieve the data, which does not yet include the changes put into the database by the submit action routine. Why is that? In my opinion the database should have done its thing by the time the status 200 is returned to the ajax call, ergo when the redraw happens the database should have the new data.
As a matter of fact, in fiddler I see that the list load from the redraw happens before the ajax to the submit function.
I have not isolated this into working code I can share, but can do so if needed - unless someone knows what I'm doing wrong.
When you assign the SubmitDone function to the statusCode.200 callback you shouldn't use parentheses because this is making the function execute immediately. Instead, it should be like this:
$.ajax({
type: 'POST',
url: '/api/Submit',
dataType: 'json',
statusCode: {
200: SubmitDone
},
error: 'SubmitError',
data: $('#ModalForm').serialize()
});

XMLHttpRequest error on send

i'm doing my baby steps in web-development.
I have a Html+JS(jQuery) Frontend and a C# Backend.
For now i just want a ping-pong request/response.
The JS looks like this :
$(document).ready(function() {
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", "http://testhttp/", false ); // false for synchronous request
xmlHttp.send();
console.log(xmlHttp.responseText);
});
The C# looks like this
if (!HttpListener.IsSupported)
{
...
}
string[] prefixes = {"http://testhttp/"};
// Create a listener.
HttpListener listener = new HttpListener();
// Add the prefixes.
foreach (string s in prefixes)
{
listener.Prefixes.Add(s);
}
listener.Start();
Console.WriteLine("Listening...");
// Note: The GetContext method blocks while waiting for a request.
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
// Obtain a response object.
HttpListenerResponse response = context.Response;
// Construct a response.
string responseString = "<p> Hello world!</p>";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
// Get a response stream and write the response to it.
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer,0,buffer.Length);
// You must close the output stream.
output.Close();
listener.Stop();
The Backend receives the request. However the response will not be transmitted correctly or permission is denied (on Firefox and Chrome).
jquery-3.2.0.min.js:2 Uncaught DOMException: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'http://testhttp/'.
I read that it might has something to do with the origin of the response and i need to set Access-Control-Allow-Origin. But those attempts failed.
Can someone pls guide me here?
Edit
Based on comments the js looks like this
$(document).ready(function() {
$.ajax({
url: "http://testhttp/",
type: "GET",
crossDomain: true,
dataType: "json",
success: function (response) {
$('#Test').html(response);
},
error: function (xhr, status) {
alert("error");
}
});
});
and in C# backend i added
response.Headers["Access-Control-Allow-Origin"] = "*";
Getting
GET http://testhttp/ net::ERR_CONNECTION_RESET

How to send an HTTP request with a header parameter?

I'm very new to javascript and web programming in general and I need some help with this. I have an HTTP request that I need to send through javascript and get need to store the output in a variable. I tried using just the call url:
https://api.fantasydata.net/nfl/v2/JSON/PlayerSeasonStats/2015
But it returns an authentication error because I didn't send my API key and it doesn't show me how to do it just in the URL. The API key is listed as a header and not a paramater and I'm not sure what to do with that. I tried using the XMLHttpRequest() class but I'm not quite sure I understand exactly what it does nor could I get it to work.
The actual HTTP Request
GET https://api.fantasydata.net/nfl/v2/JSON/PlayerSeasonStats/2015 HTTP/1.1
Host: api.fantasydata.net
Ocp-Apim-Subscription-Key: ••••••••••••••••••••••••••••••••
I just need to figure out how to send that request along with the key and how to store the JSON doc it returns as a variable in javascript.
EDIT: This is what I have so far:
function testingAPI(){
var key = "8a1c6a354c884c658ff29a8636fd7c18";
httpGet("https://api.fantasydata.net/nfl/v2/JSON/PlayerSeasonStats/2015",key );
alert(xmlHttp.responseText);
var x = 0;
}
function httpGet(theUrl,key)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
xmlHttp.setRequestHeader("Ocp-Apim-Subscription-Key",key);
xmlHttp.send( null );
return xmlHttp.responseText;
}
Thank you!
If it says the API key is listed as a header, more than likely you need to set it in the headers option of your http request. Normally something like this :
headers: {'Authorization': '[your API key]'}
Here is an example from another Question
$http({method: 'GET', url: '[the-target-url]', headers: {
'Authorization': '[your-api-key]'}
});
Edit : Just saw you wanted to store the response in a variable. In this case I would probably just use AJAX. Something like this :
$.ajax({
type : "GET",
url : "[the-target-url]",
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', '[your-api-key]');},
success : function(result) {
//set your variable to the result
},
error : function(result) {
//handle the error
}
});
I got this from this question and I'm at work so I can't test it at the moment but looks solid
Edit 2: Pretty sure you should be able to use this line :
headers: {'Authorization': '[your API key]'},
instead of the beforeSend line in the first edit. This may be simpler for you
With your own Code and a Slight Change withou jQuery,
function testingAPI(){
var key = "8a1c6a354c884c658ff29a8636fd7c18";
var url = "https://api.fantasydata.net/nfl/v2/JSON/PlayerSeasonStats/2015";
console.log(httpGet(url,key));
}
function httpGet(url,key){
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", url, false );
xmlHttp.setRequestHeader("Ocp-Apim-Subscription-Key",key);
xmlHttp.send(null);
return xmlHttp.responseText;
}
Thank You
**`
U need to have a
send();
Statement.
That way you can send the request to the site server.
`**

jQuery's .ajaxSend: can't add data dynamically

I use $(document).ajaxSend(...) to dynamically add data (POST args) to some Ajax requests, when necessary.
Adding data works when some datas have been defined in an $.ajax(...) call. But if no data has been defined in the $.ajax setting, my $.ajaxSend can't add data to the settings.
Here is my $.ajaxSend interceptor:
$(document).ajaxSend(function(e, request, settings) {
if(settings.csrfIntention) {
var requestToken = {
intention: settings.csrfIntention,
hash: self.tokens[settings.csrfIntention]
}
if(!settings.data) {
settings.data = '_token=' + encodeURIComponent(JSON.stringify(requestToken));
}
else if(typeof(settings.data) == 'string') {
settings.data += '&_token=' + encodeURIComponent(JSON.stringify(requestToken));
}
else if(!settings.data._token) {
settings.data._token = requestToken;
}
}
});
And an example of $.ajax call that works:
$.ajax({
url: opts.close.url,
method: 'POST',
data: { foo:'bar' },
csrfIntention: 'ajax_close_ticket',
success: function(data) { ... }
});
The $.ajaxSend works and settings.data is set to:
foo=bar&_token=%7B%22intention%22%3A%22ajax_close_ticket%22%2C%22hash%22%3A%22uXV1AeZwm-bZL3KlYER-Dowzzd1QmCmaT6aJFjWLpLY%22%7D
Serverside, I can retrieve the two fields: foo and _token.
Now, if I remove the data object in the $.ajax call, the output of $.ajaxSend seems Ok, too:
_token=%7B%22intention%22%3A%22ajax_close_ticket%22%2C%22hash%22%3A%225cK2WIegwI6u8K_FrxywuauWOo79xvhIcASQrZ9QPZQ%22%7D
Yet, the server don't receive my _token field :(
Another interesting fact: when I have the two fields, the Chromium dev tools under the Network tab displays the two fields under a "Form Data" title. When _token is alone, "Form Data" is replaced by "Request Payload".
Edit: just understood why _token is not interpreted by the server. If no data has been previously set in $.ajax call, jQuery does not add the right Content-Type in HTTP headers, it set it to text/plain instead of application/x-www-form-urlencoded. How can I force jQuery to add this header?
Edit 2: Solution found. Will post an answer to help other people...
I apologize for my bad English
I believe that the solution to his case would be the use of the function "ajaxSetup"
var requestToken = {
intention: settings.csrfIntention,
hash: self.tokens[settings.csrfIntention]
};
$.ajaxSetup({
data : {
_token: requestToken
}
});
this way all your orders took the data as the desire
A simpler approach:
var requestToken = {
intention: settings.csrfIntention,
hash: self.tokens[settings.csrfIntention]
}
var myForm = {};
myForm['_token'] = encodeURIComponent(JSON.stringify(requestToken));
In your ajax call:
myForm['foo'] = 'bar';
$.ajax({
url: opts.close.url,
method: 'POST',
data: myForm,
csrfIntention: 'ajax_close_ticket',
success: function(data) { ... }
});
//This sends foo and _token
Finally I answer my question after only 10 minutes...
In HTTP, the form arguments are sent into the request body, under the headers. The header Content-Type should be present to declare the data type. When this header is set to application/x-www-form-urlencoded, the server will understand that you sent a form and will parse the request body as a GET URL (you know, the foo=bar&key=val format).
jQuery adds this header automatically when you set a data object into the $.ajax call. Then it passes the request to the $.ajaxSend callback, which adds its proper fields.
When no data has been provided in request settings, jQuery do not add an unnecessary Content-Type: x-www-form-urlencoded in the request headers. Then, when you append the request body into your $.ajaxSend callback, jQuery do not check the data again and declares the content as text/plain. The server has nothing to do with text/plain so it does not interpret the body data as form fields.
You can obviously force jQuery to change the header to application/x-www-form-urlencoded, let's take the code of my original post :
if(!settings.data) {
settings.data = '_token=' + encodeURIComponent(JSON.stringify(requestToken));
}
Now add the right header:
if(!settings.data) {
settings.data = '_token=' + encodeURIComponent(JSON.stringify(requestToken));
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}

QUnit, Sinon.js - How do I ensure Post to Fake Server has correct request body?

I have a JavaScript function that does a Post to a remote API that I am looking at writing a unit test for. The method I want to test is this:
var functionToTest = function(callback, fail) {
$.ajax({
url: "/myapi/",
type: "POST",
data: { one: 'one', two: 'two' },
accept: "application/json",
contentType: "application/json"
}).done(function(x) {
log = generateLogMessage('Success');
callback(log);
}).fail(function(x, s, e) {
log = generateLogMessage('Fail');
fail(log);
});
}
I have a unit test (in QUnit leveraging Sinon.js) that tests that the callback is called correctly when the request succeeds:
QUnit.test('Test that the thing works', function () {
var server = this.sandbox.useFakeServer();
server.respondWith(
'POST',
'/myapi/',
[
200,
{'Content-Type': 'application/json'},
'{"Success":true}'
]
);
var callback = this.spy();
functionToTest(callback, callback);
server.respond();
QUnit.ok(callback.calledWith(generateLogMessage('Success')));
});
This test works, but it returns successfully regardless of what the request body. What I want to do is only have the Fake Server respond if the request body is { one: 'one', two: 'two' }
Almost two years later now, but still relevant:
This can be achieved by passing a function instead of an array as the third parameter to server.respondWith. The function takes one argument 'request', on which you can call request.respond(statusCode, headers, body);
You'll still have to extract the values from request.requestBody, but at least it's doable.
QUnit.test('Test that the thing works', function () {
var server = this.sandbox.useFakeServer();
server.respondWith(
'POST',
'/myapi/',
function (request) {
console.log(request.requestBody); // <- assert here :-)
request.respond(200, {'Content-Type': 'application/json'}, '{"Success":true}');
}
);
var callback = this.spy();
functionToTest(callback, callback);
server.respond();
QUnit.ok(callback.calledWith(generateLogMessage('Success')));
});
I was going to suggest that you use filtered requests. However this is not possible with the current implementation of sinon.
excerpt from documentation:
Add a filter that will decide whether or not to fake a request. The
filter will be called when xhr.open is called, with the exact same
arguments (method, url, async, username, password). If the filter
returns truthy, the request will not be faked.
You don't have ability to filter on the data.
EDIT: If I understand the problem correctly, you might be able to do something like this:
functionToTest(...);
var request = server.requests[0];
var data = JSON.parse(request.requestBody);
if (data.one == 'one' && data.two == 'two') {
request.respond(200, jsonHeaders, JSON.stringify(specialResponse));
}
else {
request.respond(200, jsonHeaders, JSON.stringify(otherResponse));
}
I know that code will get the correct result that you want, but there's not a way to programmatically accomplish that with sinon right now.

Categories