I am unable to print response for xmlHttpRequest - javascript

I am unable to print response for below :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<head>
<script>
jQuery.noConflict();
jQuery(document).ready(function() {
alert("Hello world, part 2!");
callOtherDomain();
});
function callOtherDomain() {
var invocation = new XMLHttpRequest();
var uName = "";
var pWord = "";
var project = '';
var domain = '';
var url = 'https://url';
invocation.open('GET', url, true, uName, pWord, project, domain);
invocation.onreadystatechange = function () {
if (4 != invocation.readyState) {
return;
}
if (200 != invocation.status) {
return;
}
console.log(this.responseText);
console.log(invocation.responseText);
console.log(invocation);
};
invocation.send();
}
I get value for console.log(invocation); as - [object XMLHttpRequest] and this.responseText prints - undefined.
When using the same credentials with chrome extension for REST API I can see the response.
I have tried printing - var xmlResponse = invocation.responseXML; - gives 'null'
var xmlResponse1 = invocation.responseText; also prints whitespace/blank
console.log(invocation.status); - print 200 (which means the call is made successfully)
I am also getting console.log(invocation.readyState); - as 4.
Here is the details shown on that network tab snag.gy/kdcwc.jpg, does is mean the response is received
var headers = invocation.getAllResponseHeaders();
alert(headers);
All the headers are also printing blank/whitespace.
anyone can help please ?

Related

Why isn't JavaScript throwing exceptions as the result of an asynchronous HTTP (AJAX) request?

I've written the following JavaScript function which is very simple, it takes an ID and which then is sent to a PHP page, which echoes out some JSON. It passes the ID into the PHP page via GET.
For example, if I was to make the following GET request: /processing/getAccountInfo.php?id=5, it would return this (got from a database): {"username":"carefulnow","profileImg":null}. This is correct, so I know my PHP is working fine.
My JavaScript code that originally called the AJAX now needs to process it, echo it out and check it for errors. If the PHP function encounters any errors, the returned JSON will contain an "errorMsg" which contains the name of the PHP exception that it encountered including a specific message (Exception::getMessage()). An example error result would be {"errorMsg":"PDOException: some error..."}.
function getAccountInfo(id) {
var loading = document.getElementById("loading");
var inner = document.getElementById("accInfInner");
var name = document.getElementById("accInfName");
var img = document.getElementById("accInfImg");
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
try {
var response = JSON.parse(this.responseText);
if (response.errorMsg === undefined) {
if (response.username === undefined || response.profileImg === undefined) {
throw new Error("Could not get the username and profile image. Try logging in then back out.");
}
name.innerHTML = response.username;
// The profile image is not required.
if (response.profileImg !== null) {
img.src = response.profileImg;
} else {
img.src = "/assets/img/defaultuser.jpg";
}
loading.style.display = "none";
inner.style.display = "block";
} else {
throw new Error(response.errorMsg);
}
} catch (exception) {
inner.innerHTML = "Error. Hover for details.";
inner.title = exception.message;
}
}
};
xmlhttp.open("GET", "/processing/getAccountInfo.php?id=" + id, true);
xmlhttp.send();
}
The problem, however, is that the throw statements aren't working. If an error is thrown from the PHP, nothing happens (no errors in the console)! My IDE (PHPStorm 2017.1) gives the following error: "'throw' of exception caught locally", which after a lot of searching, I cannot find anyone else having this same issue. Is it something to do with the GET request been asynchronous, or is it something a lot simpler I'm not seeing?

TFS Extension - How to read TaskAttachment content

I'm having trouble with reading the content of a "TaskAttachment" that I uploaded from one extension to another.
I'm using this code to get the "TaskAttachment", I'm getting it with the right name and URL, (Which I get have access to without nay authentication, e.g. from another clean browser)
var taskClient = DT_Client.getClient();
taskClient.getPlanAttachments(vsoContext.project.id, "build", build.orchestrationPlan.planId, "MyExtType").then((taskAttachments) => {
$.each(taskAttachments, (index, taskAttachment) => {
if (taskAttachment._links && taskAttachment._links.self && taskAttachment._links.self.href) {
var link = taskAttachment._links.self.href;
var attachmentName = taskAttachment.name;
var fileContent = readText(link);
...
And this javascript function to read the content
...
var readText = function readTextFile(file)
{
alert("file = " + file);
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
alert("rawFile.readyState = " + rawFile.readyState);
alert("rawFile.status = " + rawFile.status);
alert("rawFile.responseText = " + rawFile.responseText);
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
alert(allText);
return allText;
}
}
}
rawFile.send(null);
return "Failed to get data..";
}
The problem is that I'm getting 401 error message :
"IIS 7.5 Detailed Error - 401.2 - Unauthorized"
How can I read this file content? Is there a better way to transfer data from a "Build Step Extension" to a "UI Extension" that present the data in the build summary page (new tab)?
According to "IIS 7.5 Detailed Error - 401.2 - Unauthorized" It's most likely due to directory permissions set in the file system.
Make sure Anonymous access is enabled on IIS -> Authentication.
Right click on it, then click on Edit, and choose a domain\username and password.
I just managed to read the attachment data using the "getAttachmentContent" method:
I'm not sure why MS doesn't put any reference to this function in the tutorial, after long digging in the documentation \ Q&A I found it.
taskClient.getPlanAttachments(vsoContext.project.id, "build", build.orchestrationPlan.planId, "My_Attachment_Type").then((taskAttachments) => {
$.each(taskAttachments, (index, taskAttachment) => {
if (taskAttachment._links && taskAttachment._links.self && taskAttachment._links.self.href) {
var recId = taskAttachment.recordId;
var timelineId = taskAttachment.timelineId;
taskClient.getAttachmentContent(vsoContext.project.id, "build", build.orchestrationPlan.planId,timelineId,recId,"My_Attachment_Type",taskAttachment.name).then((attachementContent)=> {
function arrayBufferToString(buffer){
var arr = new Uint8Array(buffer);
var str = String.fromCharCode.apply(String, arr);
return str;
}
var data = arrayBufferToString(attachementContent);

My jQuery Ajax Call to pure Javascript

I asked about 5 month ago about rewriting my ajax call in pure Javascript. Here the original post: https://stackoverflow.com/questions/35415812/need-help-to-rewrite-my-jquery-ajax-call-to-plain-javascript
I never thought about to rewrite the script completely because it works but now i need to rewrite the whole script to plain js. I already startet.
Here is the jQUery/JS mix:
var cc = document.getElementsByClassName("cart-count");
var wc = document.getElementsByClassName("wishlist-count");
var url = wp_ajax.ajax_url;
var data = {
action: 'get_counts'
};
// JQUERY JS mixed VERSION
$.ajax({
type: 'POST',
url: url,
data: data,
success: function (data) {
var counts = JSON.parse(data);
console.log(data);
for(var i = 0; i < cc.length; i++){
cc[i].innerText=counts["cartCount"];
}
for(var i = 0; i < wc.length; i++){
wc[i].innerText=counts["wlCount"];
}
}
});
console says:
{"cartCount":"(1)","wlCount":"(3)"}
That's right!
But now i tried to rewrite the rest. Here the latest:
var cc = document.getElementsByClassName("cart-count");
var wc = document.getElementsByClassName("wishlist-count");
var url = wp_ajax.ajax_url;
var data = {
action: 'get_counts'
};
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
//document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
var counts = data
console.log(data);
for(var i = 0; i < cc.length; i++){
cc[i].innerText=counts["cartCount"];
}
for(var i = 0; i < wc.length; i++){
wc[i].innerText=counts["wlCount"];
}
console.log('done');
} else if (xmlhttp.status == 400) {
console.log('There was an error 400');
} else {
console.log('something else other than 200 was returned');
}
}
};
xmlhttp.open('POST', url, true);
xmlhttp.send(data);
It does't work. The console gives me not the value, just the var:
Object {action: "get_counts"}
My question/problem: How can i get the data action values without the jQuery ajax? Please no questions like "why not jQuery?".
Thanks for all help!!! Sorry for my english.
UPDATE:
I got it!
jQuery:
var data = {
action: 'get_counts'
};
JS:
url + '?action=get_counts'
add this
var data = JSON.parse(xmlhttp.responseText);//you have to parse result
before this
var counts = data
console.log(data);
You are not evaluating the AJAX response data, but the local variable data which is set above the AJAX call:
var data = {
action: 'get_counts'
};
You need to parse the AJAX response instead:
if (xmlhttp.status == 200) {
console.log( JSON.parse(xmlhttp.response) )
}
See: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/response
Its happening because Ajax is async request which the browser handers in a different thread than the one which is processing your code. Normally jquery and other similar frameworks have callback methods defined for that but in pure JS implementation you can use
xmlhttp.responseText
to fetch the output once the request is done

how to load json from url using javascript?

I'm new to javascript which should be really simple to solve, but I am lost as of now.
I have a url: http:getall.json
Using JavaScript (not JQuery or php. Just JavaScript), I want to read this JSON string and parse it. That's it.
access to your url doesn't work, you should show the JSON result. In javascript to get JSON object with AJAX request you can do something like this:
request = new XMLHttpRequest;
request.open('GET', 'http://v-apps-campaign.com/dunkindonuts/main/get_allStore', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400){
// Success!
data = JSON.parse(request.responseText);
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
your result will be in the data variable.
JSONP calls:
function getJSONP(url, callback) {
var script = document.createElement('script');
var callbackName = "jsonpcallback_" + new Date().getTime();
window[callbackName] = function (json) {
callback(json);
};
script.src = url + (url.indexOf("?") > -1 ? "&" : "?") + 'callback=' + callbackName;
document.getElementsByTagName('head')[0].appendChild(script);
}
getJSONP("http://v-apps-campaign.com/dunkindonuts/main/get_allStore", function(jsonObject){
//jsonObject is what you want
});
Regular ajax ajax call:
function getXHR() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
}
try {
return new ActiveXObject('MSXML2.XMLHTTP.6.0');
} catch (e) {
try {
// The fallback.
return new ActiveXObject('MSXML2.XMLHTTP.3.0');
} catch (e) {
throw new Error("This browser does not support XMLHttpRequest.");
}
}
}
function getJSON(url, callback) {
req = getXHR();
req.open("GET", url);
req.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var jsonObject = null,
status;
try {
jsonObject = JSON.parse(req.responseText);
status = "success";
} catch (e) {
status = "Invalid JSON string[" + e + "]";
}
callback(jsonObject, status, this);
}
};
req.onerror = function () {
callback(null, "error", null);
};
req.send(null);
}
getJSON("http://v-apps-campaign.com/dunkindonuts/main/get_allStore", function (jsonObject, status, xhr) {
//jsonObject is what you want
});
I tested these with your url and it seems like you should get the data with a jsonp call, because with regular ajax call it returns:
No 'Access-Control-Allow-Origin' header is present on the requested resource
with jsonp it gets the data but the data is not a valid json, it seems your server side has some php errors:
A PHP Error was encountered
...
In your HTML include your json file and a js code as modules
<script src="/locales/tshared.js" type="module" ></script>
<script src="/scripts/shared.js" type="module" ></script>
file content of tshared
export const loc = '{"en": { "key1": "Welcome" },"pt": {"key1": "Benvindo"} }'
file content of shared
import {loc} from "./../../locales/tshared.js";
var locale = null;
locale = JSON.parse(loc) ;
Adapt path and names as needed, use locale at will.

Not able to load the response

var soapre1 = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:glob=\"http://sap.com/xi/SAPGlobal20/Global\">";
var soapre2 = "<soapenv:Header/><soapenv:Body><glob:EmployeeLeaveRequestByParticipantQuery><EmployeeLeaveRequestSelectionByParticipant><EmployeeLeaveRequestParticipantRoleCode listVersionID=\"?\">2</EmployeeLeaveRequestParticipantRoleCode>";
var soapre3 = "<!--Zero or more repetitions:--> <EmployeeLeaveRequestParticipantWorkAgreementIDInterval><IntervalBoundaryTypeCode>1</IntervalBoundaryTypeCode> <!--Optional:--> <LowerBoundaryWorkAgreementID schemeID=\"?\" schemeAgencyID=\"?\">1009</LowerBoundaryWorkAgreementID></EmployeeLeaveRequestParticipantWorkAgreementIDInterval>";
var soapre4 = " <!--Zero or more repetitions:--> </EmployeeLeaveRequestSelectionByParticipant></glob:EmployeeLeaveRequestByParticipantQuery> </soapenv:Body></soapenv:Envelope>";
var soapRequest = soapre1+soapre2+soapre3+soapre4;
var authstr = 'Basic ' +Titanium.Utils.base64encode('S0009231839'+':'+ 'm8390967743!');
var soapxhr = Ti.Network.createHTTPClient();
soapxhr.setRequestHeader('SOAPAction',soapRequest);
soapxhr.open("POST","http://erp.esworkplace.sap.com/sap/bc/srt/pm/sap/ecc_empleavereqparctqr/800/default_profile/2/binding_t_http_a_http_ecc_empleavereqparctqr_default_profile");
soapxhr.setRequestHeader('Authorization', authstr);
soapxhr.setRequestHeader('Content-Type','text/xml','charset=utf-8');
soapxhr.send();
soapxhr.onload = function(e)
{
Ti.API.info('abcd');
//get the xml data and let it roll!
var doc = this.responseXML;
Ti.API.info(doc);
}
soapxhr.onerror = function (e){
alert('Error');
Ti.API.info(e);
}
Unable to load the response Its directly getting error
[INFO] {
source = "[object TiNetworkClient]";
type = error;
}
Any one advice how to fix the issue!
# Thanks in advance
In all browser its saying error! but i found some wsdl and soap request so in order to open the response i need to pass the method name to the http request ! then it working

Categories