How to retrieve header value from XMLHttpRequest - javascript

My post is making it to the server and returning correctly; however, I cannot seem to retrieve the var addressId = xhr.getResponseHeader('X-NEW-ADDRESS-ID'); from the XMLHttpRequest header.
Can someone point out to me how to retrieve the header value from the response?
[HttpPost]
public HttpResponseMessage AddressNew(EnterpriseAddressViewModel a)
{
HttpResponseMessage r = null;
if (ModelState.IsValid)
{
AFCCIncProsNonProsCommonDL.DataTransfer.Tables.utbAddress address = new AFCCIncProsNonProsCommonDL.DataTransfer.Tables.utbAddress();
address.AddressFlags |= (byte)Math.Pow(2, 0);
address.AddressIsVisible = true;
address.AddressLine = a.Street;
address.AddressTypeID = a.AddressTypeID;
address.ZipCode = a.Zipcode;
int newAddressID = 0;
if (Roles.IsUserInRole(_nonProRoleName))
{
AFCCIncNonProsBL.Address.Addresses_Insert(_cnn, new Guid(Membership.GetUser().ProviderUserKey.ToString()), address, out newAddressID);
}
else
{
AFCCIncProsBL.Address.InsertAddress(_cnn, new Guid(Membership.GetUser().ProviderUserKey.ToString()), address, out newAddressID);
}
r = new HttpResponseMessage(System.Net.HttpStatusCode.Accepted);
r.Headers.Add("X-NEW-ADDRESS-ID", newAddressID.ToString());
}
else
{
r = new HttpResponseMessage(System.Net.HttpStatusCode.NotAcceptable);
r.Content = new StringContent("Error adding address");
}
return r;
}
---JavaScript-------
var btnSubmitNew = function () {
var newForm = new FormData(document.forms[0]),
xhr = new XMLHttpRequest(),
that = this;
xhr.onload = function () { };
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
var addressId = xhr.getResponseHeader('X-NEW-ADDRESS-ID');
};
};
xhr.open('POST', '/EnterpriseManager/' + currPartial + 'New', true);
xhr.send(newForm);
return false;
};

Related

How to acces data from variable in begin function

Could someone help me out on this function structure what I try to do is seperate the functions like this:
function getNewResources (currentUrl, nextUrl)
{
let resourcesCurrentUrl = getResourceByUrl(currentUrl);
let resourcesNextUrl = getResourceByUrl(nextUrl);
// Diff resources
ACCESS DATA FROM ABOVE VARIABLES HERE!
// Return new resources
}
function getResourceByUrl (url)
{
let xmlhttp = new XMLHttpRequest();
let xmlResponse;
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4) {
// when succesfull
var resources = extractResourcesFromXMLResponse(this.response);
return resources;
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function extractResourcesFromXMLResponse (xmlResponse)
{
let resources = [];
// Add images
imagePaths = extractImages(xmlResponse);
resources.push(imagePaths);
return resources;
}
function extractImages(xmlDoc)
{
let match,
extractedImages = [],
newArr = [],
rex = /<img.*?src="([^">]*\/([^">]*?))".*?>/g;
while ( match = rex.exec( xmlDoc ) ) {
extractedImages.push( match[1] );
}
return extractedImages;
}
How do I acces the returned resource variable in the getNewResource() function

HTML form send data to google sheet with time stamp

i have success send data to my google sheet from HTML
function submit_form() {
var complete = true;
var error_color = '#FFD9D9';
var fields = ['name','phonenum','monthlysalary','totalamount','types'];
var row = '';
var i;
for(i=0; i < fields.length; ++i) {
var field = fields[i];
$('#'+field).css('backgroundColor', 'inherit');
var value = $('#'+field).val();
if(!value) {
if(field != 'message') {
$('#'+field).css('backgroundColor', error_color);
var complete = false;
}
} else {
row += '"'+value+'",';
}
}
if(complete) {
row = row.slice(0, -1);
var gs_sid = 'xxx';
var gs_clid = 'xxx';
var gs_clis = 'xxx';
var gs_rtok = 'xxx';
var gs_atok = false;
var gs_url = 'https://sheets.googleapis.com/v4/spreadsheets/'+gs_sid+'/values/Google!A1:append?includeValuesInResponse=false&insertDataOption=INSERT_ROWS&responseDateTimeRenderOption=SERIAL_NUMBER&responseValueRenderOption=FORMATTED_VALUE&valueInputOption=USER_ENTERED';
var gs_body = '{"majorDimension":"ROWS", "values":[['+row+']]}';
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://www.googleapis.com/oauth2/v4/token?client_id='+gs_clid+'&client_secret='+gs_clis+'&refresh_token='+gs_rtok+'&grant_type=refresh_token');
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
var response = JSON.parse(xhr.responseText);
var gs_atok = response.access_token;
if(gs_atok) {
var xxhr = new XMLHttpRequest();
xxhr.open('POST', gs_url);
xxhr.setRequestHeader('Content-type', 'application/json');
xxhr.setRequestHeader('Authorization', 'OAuth ' + gs_atok );
xxhr.send(gs_body);
}
};
xhr.send();
}
}
Now i having a problem, i would like to make the google sheets will auto adding timestamp when i send the data into google form. Its anyway to do it?
Thank you

XMLHttpRequest with multiple queries

I have an interface that need user to input zip code, then I will query the longitude and latitude from a remote site based on the inputted zip, then query some population information based on previous queried longitude and latitude. I need 3 XMLhttpRequest() to query three different sites. Each query will based on previous queried data. I think there may have some callback issues in my code, I don't know how to fix it.
<input type="submit" value="Get City" onclick="getInfo()">
<script>
function getInfo(getGeoCode) {
var zipCode = document.getElementById("inputtext").value
var xmlReq = new XMLHttpRequest();
xmlReq.open("GET", "http://api.zippopotam.us/us/" + zipCode, true);
xmlReq.onreadystatechange = function () {
if (xmlReq.readyState == 4) {
var temp = JSON.parse(xmlReq.responseText);
var lat = temp.places[[0]].latitude ;
var logt = temp.places[[0]].longitude;
getGeoCode(lat, logt);
};
};
xmlReq.send();
}
function getGeoCode(lat,logt,getpop) {
var nereq = new XMLHttpRequest();
nereq.open("GET", "https://data.fcc.gov/api/block/find?&latitude=" + lat + "&longitude=" + logt + "&showall=false&format=json", true);
nereq.onreadystatechange = function () {
if (nereq.readyState == 4) {
var temp2 = JSON.parse(nereq.responseText);
var stateCode = temp2.State.FIPS;
var contyCode = temp2.County.FIPS;
getpop(stateCode, contyCode);
};
};
nereq.send();
}
function getpop(stateCode, contyCode) {
var nereq2 = new XMLHttpRequest();
nereq2.open("GET", "http://api.census.gov/data/2010/sf1?get=P0010001&for=county:" + contyCode + "&in=state:" + stateCode, true);
nereq2.onreadystatechange = function () {
if (nereq2.readyState == 4) {
var temp3 = JSON.parse(nereq.responseText);
document.getElementById("fs").innerHTML = temp3;
};
};
nereq2.send();
}
</script>
Your functions have arguments which conflict with the function names you call, so they are not accessible anymore.
For example, getGeoCode has an argument called getpop. When getpop is called, it does not call the function of that name, but tries to call the reference that the getpop argument references. Especially as you aren't passing anything in this paarmeter, it is most likely erroring.
The solution is to just remove the getGeoCode parameter from getInfo() and the getpop parameter from getGeoCode():
<input type="submit" value="Get City" onclick="getInfo()">
<script>
function getInfo() {
var zipCode = document.getElementById("inputtext").value
var xmlReq = new XMLHttpRequest();
xmlReq.open("GET", "http://api.zippopotam.us/us/" + zipCode, true);
xmlReq.onreadystatechange = function () {
if (xmlReq.readyState == 4) {
var temp = JSON.parse(xmlReq.responseText);
var lat = temp.places[[0]].latitude ;
var logt = temp.places[[0]].longitude;
getGeoCode(lat, logt);
};
};
xmlReq.send();
}
function getGeoCode(lat,logt) {
var nereq = new XMLHttpRequest();
nereq.open("GET", "https://data.fcc.gov/api/block/find?&latitude=" + lat + "&longitude=" + logt + "&showall=false&format=json", true);
nereq.onreadystatechange = function () {
if (nereq.readyState == 4) {
var temp2 = JSON.parse(nereq.responseText);
var stateCode = temp2.State.FIPS;
var contyCode = temp2.County.FIPS;
getpop(stateCode, contyCode);
};
};
nereq.send();
}
function getpop(stateCode, contyCode) {
var nereq2 = new XMLHttpRequest();
nereq2.open("GET", "http://api.census.gov/data/2010/sf1?get=P0010001&for=county:" + contyCode + "&in=state:" + stateCode, true);
nereq2.onreadystatechange = function () {
if (nereq2.readyState == 4) {
var temp3 = JSON.parse(nereq.responseText);
document.getElementById("fs").innerHTML = temp3;
};
};
nereq2.send();
}
</script>

Read-Only Button for List Item in Sharepoint

I've got the following Sharepoint problem: I've created a Ribbon Button, which says "Read Only". When I am on a list, and check some items, I want to set those items to read only.
The ribbon button works great and when I am doing an alert or something, I get an answer. So this cannot be the problem. I did the following:
var listitem;
var roleAssgn;
var Assgn;
var selectedItems;
function readonly() {
selectedItems = SP.ListOperation.Selection.getSelectedItems();
var currentListGuid = SP.ListOperation.Selection.getSelectedList();
var context = SP.ClientContext.get_current();
var currentWeb = context.get_web();
var currentList = currentWeb.get_lists().getById(currentListGuid);
for (k in selectedItems) {
listitem = currentList.getItemById(selectedItems[k].id);
context.load(listitem, 'RoleAssignments');
context.executeQueryAsync(Function.createDelegate(this, this.readonlyPerItem), Function.createDelegate(this, this.failed));
}
}
function readonlyPerItem(sender, args) {
var k;
var Assgn;
var r;
context = SP.ClientContext.get_current();
roleAssgn = listitem.get_roleAssignments();
for(r in roleAssgn){
Assgn = roleAssgn[r];
alert("1");
context.load(Assgn, 'RoleDefinitionBindings');
alert("2");
context.executeQueryAsync(Function.createDelegate(this, this.readonlyPerRoleA), Function.createDelegate(this, this.failed));
}
}
function readonlyPerRoleA(sender, args) {
var bindings = Assgn.get_roleDefinitionBindings();
var member = Assgn.get_member();
}
function failed(sender, args) {
alert("FAIL");
}
This works great until it gets to the alerts. Alert-1 is working, but not Alert-2. The Debugger says: The object does not support the property "get_$h".
And that happens in the sp_runtime.js with:
SP.DataRetrievalWithExpressionString.$1Q_0(a.get_$h(),d)
I dont really see a problem. Is this a bug or is it just not possible?
Ok, I used another way to do this and wanted to let you know, how it worked for me. I used a JS in the Ribbon Menu to call another website, which is just an empty site. I added the parameters (listguid, siteurl and the itemid's comma-seperated).
Then that site just prints an "True" or "False". This response will be caught by my Ribbon JS and show some message if it worked or not. This is my Ribbon JS:
<CustomAction
Id="ReadOnlyButton"
RegistrationId="101"
RegistrationType="List"
Location="CommandUI.Ribbon"
Sequence="15"
Rights="ManageLists"
Title="Set Readonly">
<CommandUIExtension>
<CommandUIDefinitions>
<CommandUIDefinition
Location="Ribbon.Documents.Manage.Controls._children">
<Button
Id="Ribbon.Documents.ReadOnly"
Command="ReadOnly"
Sequence="15"
Image16by16="/_layouts/1031/images/formatmap16x16.png"
Image16by16Left="-80"
Image16by16Top="-128"
Image32by32="/_layouts/1031/images/formatmap32x32.png"
Image32by32Left="-160"
Image32by32Top="-256"
Description="Read Only"
LabelText="Read Only"
TemplateAlias="o1"/>
</CommandUIDefinition>
</CommandUIDefinitions>
<CommandUIHandlers>
<CommandUIHandler
Command="ReadOnly"
CommandAction="javascript:
var nid;
function getItemIds()
{
var itemIds = '';
var items = SP.ListOperation.Selection.getSelectedItems();
var item;
for(var i in items)
{
item = items[i];
if(itemIds != '')
{
itemIds = itemIds + ',';
}
itemIds = itemIds + item.id;
}
return itemIds;
}
function handleReadyStateChange()
{
if (client.readyState == 4)
{
if (client.status == 200)
{
SP.UI.Notify.removeNotification(nid);
if(client.responseText == 'True') {
nid = SP.UI.Status.addStatus('The Rights has been set successfully', '', true);
SP.UI.Status.setStatusPriColor(nid, 'green');
} else {
nid = SP.UI.Status.addStatus('Error while setting Rights', '', true);
SP.UI.Status.setStatusPriColor(nid, 'red');
}
window.setTimeout('SP.UI.Status.removeStatus(\'' + nid + '\')', 5000);
}
}
}
function invokeReadOnly()
{
var itemLength = 0;
var params = 'itemids=' + getItemIds();
for (var i=0;i<params.length;i++) { if (',' == params.substr(i,1)) { itemLength++; } }
if(itemLength > 0) {
nid = SP.UI.Notify.addNotification('Rights set for ' + (itemLength +1) + ' elements...', true);
} else {
nid = SP.UI.Notify.addNotification('Set Rights...', true);
}
var site='{SiteUrl}';
var url = site + '/_layouts/ReadOnly.aspx?listId={ListId}';
client = null;
client = new XMLHttpRequest();
client.onreadystatechange = handleReadyStateChange;
client.open('POST', url, true);
client.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
client.setRequestHeader('Content-length', params.length);
client.send(params);
}
invokeReadOnly();"
EnabledScript="javascript:
function enableReadOnly()
{
var items = SP.ListOperation.Selection.getSelectedItems();
return (items.length > 0);
}
enableReadOnly();"/>
</CommandUIHandlers>
</CommandUIExtension>
</CustomAction>
And this is my site behind it (ReadOnly.aspx):
protected void Page_Load(object sender, EventArgs e)
{
string itemidsAll = Page.Request["itemids"];
string listId = Page.Request["listId"];
bool set = true;
if (!String.IsNullOrEmpty(itemidsAll))
{
string[] itemIds = itemidsAll.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
int item = 0;
SPSite _site = null;
SPListItem spitem = null;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
_site = new SPSite(SPContext.Current.Site.ID);
});
using (SPWeb web = _site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPList doclib = SPContext.Current.Web.Lists.GetList(new Guid(listId), false);
foreach (string itemId in itemIds)
{
if (Int32.TryParse(itemId, out item))
{
spitem = doclib.GetItemById(item);
set &= SetItem(spitem, SPContext.Current, ref _site);
}
}
web.AllowUnsafeUpdates = false;
}
_site.Dispose();
}
Response.Clear();
Response.Write(set.ToString());
Response.End();
}
The SetItem-Method is for setting the Rights. You can use your own stuff there :)

Downloading binary data using XMLHttpRequest, without overrideMimeType

I am trying to retrieve the data of an image in Javascript using XMLHttpRequest.
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://www.celticfc.net/images/doc/celticcrest.png");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
var resp = xhr.responseText;
console.log(resp.charCodeAt(0) & 0xff);
}
};
xhr.send();
The first byte of this data should be 0x89, however any high-value bytes return as 0xfffd (0xfffd & 0xff being 0xfd).
Questions such as this one offer solutions using the overrideMimeType() function, however this is not supported on the platform I am using (Qt/QML).
How can I download the data correctly?
Google I/O 2011: HTML5 Showcase for Web Developers: The Wow and the How
Fetch binary file: new hotness
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.celticfc.net/images/doc/celticcrest.png', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
if (this.status == 200) {
var uInt8Array = new Uint8Array(this.response); // Note:not xhr.responseText
for (var i = 0, len = uInt8Array.length; i < len; ++i) {
uInt8Array[i] = this.response[i];
}
var byte3 = uInt8Array[4]; // byte at offset 4
}
}
xhr.send();
I'm not familiarized with Qt but i found this in their documentation
string Qt::btoa ( data )
Binary to ASCII - this function returns a base64 encoding of data.
So, if your image is a png you can try:
resp = "data:image/png;base64," + btoa(resp);
document.write("<img src=\""+resp+"\">");
Qt version 5.13.1(support native Promise in qml env), prue qml.
function fetch, like node-fetch
function hexdump, dump the data as hex, just use the linux command hexdump to check.
function createResponse(xhr) {
let res = {};
function headersParser() {
let headersRaw = {};
let lowerCaseHeaders = {};
let rawHeaderArray = xhr.getAllResponseHeaders().split("\n");
for(let i in rawHeaderArray) {
let rawHeader = rawHeaderArray[i];
let headerItem = rawHeader.split(":");
let name = headerItem[0].trim();
let value = headerItem[1].trim();
let lowerName = name.toLowerCase();
headersRaw[name] = value;
lowerCaseHeaders [lowerName] = value;
}
return {
"headersRaw": headersRaw,
"lowerCaseHeaders": lowerCaseHeaders
};
}
res.headers = {
__alreayParse : false,
raw: function() {
if (!res.headers.__alreayParse) {
let {headersRaw, lowerCaseHeaders} = headersParser();
res.headers.__alreayParse = true;
res.headers.__headersRaw = headersRaw;
res.headers.__lowerCaseHeaders = lowerCaseHeaders;
}
return res.headers.__headersRaw;
},
get: function(headerName) {
if (!res.headers.__alreayParse) {
let {headersRaw, lowerCaseHeaders} = headersParser();
res.headers.__alreayParse = true;
res.headers.__headersRaw = headersRaw;
res.headers.__lowerCaseHeaders = lowerCaseHeaders;
}
return res.headers.__lowerCaseHeaders[headerName.toLowerCase()];
}
};
res.json = function() {
if(res.__json) {
return res.__json;
}
return res.__json = JSON.parse(xhr.responseText);
}
res.text = function() {
if (res.__text) {
return res.__text;
}
return res.__text = xhr.responseText;
}
res.arrayBuffer = function() {
if (res.__arrayBuffer) {
return res.__arrayBuffer;
}
return res.__arrayBuffer = new Uint8Array(xhr.response);
}
res.ok = (xhr.status >= 200 && xhr.status < 300);
res.status = xhr.status;
res.statusText = xhr.statusText;
return res;
}
function fetch(url, options) {
return new Promise(function(resolve, reject) {
let requestUrl = "";
let method = "";
let headers = {};
let body;
let timeout;
if (typeof url === 'string') {
requestUrl = url;
method = "GET";
if (options) {
requestUrl = options['url'];
method = options['method'];
headers = options['headers'];
body = options['body'];
timeout = options['timeout'];
}
} else {
let optionsObj = url;
requestUrl = optionsObj['url'];
method = optionsObj['method'];
headers = optionsObj['headers'];
body = optionsObj['body'];
timeout = optionsObj['timeout'];
}
let xhr = new XMLHttpRequest;
if (timeout) {
xhr.timeout = timeout;
}
// must set responseType to arraybuffer, then the xhr.response type will be ArrayBuffer
// but responseType not effect the responseText
xhr.responseType = 'arraybuffer';
xhr.onreadystatechange = function() {
// readyState as follow: UNSENT, OPENED, HEADERS_RECEIVED, LOADING, DONE
if(xhr.readyState === XMLHttpRequest.DONE) {
resolve(createResponse(xhr));
}
};
xhr.open(method, requestUrl);
// todo check headers
for(var iter in headers) {
xhr.setRequestHeader(iter, headers[iter]);
}
if("GET" === method || "HEAD" === method) {
xhr.send();
} else {
xhr.send(body);
}
});
}
function hexdump(uint8array) {
let count = 0;
let line = "";
let lineCount = 0;
let content = "";
for(let i=0; i<uint8array.byteLength; i++) {
let c = uint8array[i];
let hex = c.toString(16).padStart (2, "0");
line += hex + " ";
count++;
if (count === 16) {
let lineCountHex = (lineCount).toString (16).padStart (7, "0") + "0";
content += lineCountHex + " " + line + "\n";
line = "";
count = 0;
lineCount++;
}
}
if(line) {
let lineCountHex = (lineCount).toString (16).padStart (7, "0") + "0";
content += lineCountHex + " " + line + "\n";
line = "";
// count = 0;
lineCount++;
}
content+= (lineCount).toString (16).padStart (7, "0") + count.toString(16) +"\n";
return content;
}
fetch("https://avatars2.githubusercontent.com/u/6630355")
.then((res)=>{
try {
let headers = res.headers.raw();
console.info(`headers:`, JSON.stringify(headers));
let uint8array = res.arrayBuffer();
let hex = hexdump(uint8array);
console.info(hex)
}catch(error) {
console.trace(error);
}
})
.catch((error)=>{
});

Categories

Resources