How can we send/get the http headers information with AJAX? - ruby-on-rails

Is there any way to send/get the http headers (like, content-type... ) through AJAX?. Then, can please explain me, what will we archive by passing the http headers in AJAX and where will use this technique?.
Thanks

I'm no expert,
But you should look at the AJAX object XmlHttpHeader and the wikipedia article here.
EDIT: quoting the www.w3.org reference:
function test(data) {
// taking care of data
}
function handler() {
if(this.readyState == 4 && this.status == 200) {
// so far so good
if(this.responseXML != null && this.responseXML.getElementById('test').firstChild.data)
// success!
test(this.responseXML.getElementById('test').firstChild.data);
else
test(null);
} else if (this.readyState == 4 && this.status != 200) {
// fetched the wrong page or network error...
test(null);
}
}
var client = new XMLHttpRequest();
client.onreadystatechange = handler;
client.open("GET", "unicorn.xml");
client.send();
If you just want to log a message to the server:
function log(message) {
var client = new XMLHttpRequest();
client.open("POST", "/log");
client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
client.send(message);
}
Or if you want to check the status of a document on the server:
function fetchStatus(address) {
var client = new XMLHttpRequest();
client.onreadystatechange = function() {
// in case of network errors this might not give reliable results
if(this.readyState == 4)
returnStatus(this.status);
}
client.open("HEAD", address);
client.send();
}

Related

Hyperledger Composer with javascript

I am a beginner with hyperledger composer. I want to retrieve data from server such as AJAX that use it in javascript file of hyperledger composer.
How can I achieve it?
below, it is example from w3school that I use in script file of hyperledger composer.
/**
* Sample transaction processor function.
* #param {org.acme.sample.SampleTransaction} tx The sample transaction instance.
* #transaction
*/
function sampleTransaction(tx) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
you can use call-outs in Composer transaction functions. But remember with smart contract transactions, all peers executing the transaction logic must return a deterministic result - else your transaction will fail to be endorsed (you probably knew that, just saying)
See more details and examples here -> https://hyperledger.github.io/composer/latest/integrating/call-out
function handlePost(postTransaction) {
var url = 'https://composer-node-red.mybluemix.net/compute';
// call-out
return post( url, postTransaction)
.then(function (result) {
// alert(JSON.stringify(result));
postTransaction.asset.value = 'Count is ' + result.body.sum;
// now update an Asset Registry (Composer)
return getAssetRegistry('org.example.sample.SampleAsset')
.then(function (assetRegistry) {
return assetRegistry.update(postTransaction.asset);
});
});
}

How to send javascript object with POST XMLHttpRequest

I want to send the following data in POST XMLHttpRequest method.
Data to be sent:
var data = {xx:"value",user:{password:"pass",username:"xyz"}};
Code used:
var xmlhttp = new XMLHttpRequest();
var data = {xx:"value",user:{password:"pass",username:"xyz"}};
data = JSON.stringify(data);
xmlhttp.open("POST",Url,true);
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.send(data );
Result:
Getting "xx" is missing.
Kindly help me to resolve this issue.

How to send multipart HTTP requests from browser with Dart

I have to upload an image from browser to my RESTful web API, implemented using Python Eve. From documentation, It requires sending multipart/data-form request. (http://python-eve.org/features.html#file-storage). There is 'dart:http' library that could do. But, it requires 'dart:io', which is not available on browser. So, is there anyway I can send the request from browser?
Thank you for any help.
You can just use something like this:
FormData formData = new FormData();
formData.append('image', '...');
HttpRequest.request('url', method: 'post', sendData: formData).then((HttpRequest request) {
// ...
});
This should set the correct mimeType. If not you can set it with the mimeType parameter.
Regards,
Robert
Client side, the dart:html library should do the trick. Something like this (source):
import 'dart:html';
main() {
InputElement uploadInput = query('#upload');
uploadInput.on.change.add((e) {
// read file content as dataURL
final files = uploadInput.files;
if (files.length == 1) {
final file = files[0];
final reader = new FileReader();
reader.on.load.add((e) {
sendDatas(reader.result);
});
reader.readAsDataURL(file);
}
});
}
/// send data to server
sendDatas(dynamic data) {
final req = new HttpRequest();
req.on.readyStateChange.add((Event e) {
if (req.readyState == HttpRequest.DONE &&
(req.status == 200 || req.status == 0)) {
window.alert("upload complete");
}
});
req.open("POST", "http://127.0.0.1:8080/upload");
req.send(data);
}

In NServiceBus full duplex application Server could not send/reply/return message

I have created a ASP.Net Web API project and using this link. NServiceBus is integrated with web api. Here is my configuration at web api as a client.
Configure.Serialization.Xml();
Configure.Transactions.Enable();
Configure.With()
.DefineEndpointName(Constants.ClientName)
.DefaultBuilder()
.ForWebApi()
.Log4Net()
.UseTransport<Msmq>()
.PurgeOnStartup(false)
.UnicastBus()
.ImpersonateSender(false)
.CreateBus()
.Start();
This is how I'm sending message to Server
var response = await Bus.Send(Constants.ServerName, request)
.Register<ResponseModel>((NServiceBus.CompletionResult completionResult) =>
{
ResponseModel responseMessage = null;
if (completionResult != null && completionResult.Messages.Length > 0)
{
var status = completionResult.Messages[0] as RequestStatus?;
if (status == RequestStatus.Successful)
{
responseMessage = TransactionManager.TransactionDictionary[request.RequestId].ResponseModel;
}
}
return responseMessage;
});
This is how I'm sending response from Server. I have commented some lines to show what I have already tried.
public void Handle(RequestModel message)
{
ProcessRequest(message).RunSynchronously();
}
private async Task ProcessRequest(RequestModel message)
{
....
ResponseModel response = new ResponseModel();
response.RequestId = message.RequestId;
response.Result = await responseMessage.Content.ReadAsStringAsync();
//Bus.Send(Util.Constants.ClientName, response);
//Bus.Reply(response);
//Bus.Reply<ResponseModel>((ResponseModel response) =>
//{
// response = Bus.CreateInstance<ResponseModel>(r =>
// {
// r.RequestId = message.RequestId;
// r.Result = responseMessage.Content.ReadAsStringAsync().Result;
// });
//});
await Bus.Send(Util.Constants.ClientName, response).Register((NServiceBus.CompletionResult completionResult) =>
{
if (completionResult != null && completionResult.Messages.Length > 0)
{
var msg = completionResult.Messages[0];
if (msg != null)
{
var status = (RequestStatus)msg;
return status;
}
}
return RequestStatus.Error;
});
....
}
From any of the above response methods ultimately all messages end up in error queue.
Previously I was getting 'Could not enlist message' error. Now it is not throwing that error. But Server could not send message to Client.
I could not get what I'm doing wrong. Please also suggest if you see any scope for improvements.
I'm not sure if TransactionScope work correctly with async/await in C#. According to this question (Get TransactionScope to work with async / await) in .NET 4.5.1 there was introduced option for TransactionScope that enable mixing it with async/await. Unfortunately NServiceBus doesn't support .NET 4.5/4.5.1 so try just remove async/await.

XMPP strophe Connection attach process failed

I'm able to create a XMPP connection on page load. However whenever I move to another pages, I want to use the same connection to remove recurring notifications in client. I've used following code.
$(document).bind('connect', function (ev, data) {
var jid = $.jStorage.get('JID', null);
var sid = $.jStorage.get('SID', null);
var rid = $.jStorage.get('RID', null);
if ((jid != null) && (sid != null) && (rid != null)) {
var conn = new Strophe.Connection("http://localhost:5280/xmpp-httpbind");
conn.attach(jid, sid, rid, function () {
alert('Connection attach success.');
Gab.connection = conn;
});
}
else {
var conn = new Strophe.Connection("http://localhost:5280/xmpp-httpbind");
conn.connect(data.jid, data.password, function (status) {
if (status === Strophe.Status.CONNECTED) {
$(document).trigger('connected');
} else if (status === Strophe.Status.DISCONNECTED) {
$(document).trigger('disconnected');
}
});
Gab.connection = conn;
}
});
And in unload:
$(window).unload(function () {
if (Gab.connection != null) {
Gab.connection.pause();
$.jStorage.set('JID', Gab.connection.jid);
$.jStorage.set('SID', Gab.connection.sid);
$.jStorage.set('RID', Gab.connection.rid);
} else {
$.jStorage.flush();
}
// Gab.connection = null;
alert('paused/disconnected');
})
It attaches to connection, however as soon as it attaches, it says (POST http://localhost:5280/xmpp-httpbind 404 Not Found 36ms) in Firebug console. Any ideas?
Thanks in advance.
You should not trust unload. Instead store/update your RID on every cb from the xmpp server. Make sure your RID is getting incremented on each call as well.
Make sure to inspect the body of the message. Some XMPP servers return HTTP 404 on terminate.

Resources