Why is my XML Http request not executing anything? - javascript

I have a XML http requests but for some reason it doesn't work. It is supposed to check the number of friends the person has then if there aren't enough displayed you know, do all that stuff. And don't worry, I checked the database and all the sql, it removes/adds friends successfully but the problem is that the console says it executes it but the function doesn't do anything
Here is the function :
x = document.getElementsByClassName("numoffriends");
numoffriends = x.length;
var fullurl = "../backend/friends.php?numoffriends=" + numoffriends + "&loadfriends=true";
var request = new XMLHttpRequest();
request.open("GET", fullurl , false);
request.onload = function(){
if(request.status == 200){
let testdivvv = document.createElement("element");
testdivvv.innerHTML = this.responseText;
groupchat = document.getElementById("leftsmallbox");
groupchat.append(testdivvv);
}
}
request.send();
}
setInterval(loadfriends, 1500);
If it makes any difference there are also 4 other functions on the same timing i.e gets executed. I checked, there is indeed an object called leftsmallbox.
If you have any questions just ask, I'll be available for a while

Related

BAD REQUEST When making an AJAX CALL: This.readyState is undefined

I wrote a function that fetches the guid of a lookup field and uses that to make an AJAX call. This is the the call that I made:
fetchOptionSet: function (executionContext) {
var formContext = executionContext.getFormContext(); //get form context
var client = Xrm.Page.context.getClientUrl(); //get client url
var childId = formContext.getAttribute("new_childid").getValue()[0].id;
var child = childId.replace(/[{}]/g, "");
var contract;
var req = new XMLHttpRequest();
req.open("GET", client + `/api/data/v8.2/new_childallergieses(${child})?$select=_new_childid_value`, true);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
req.onreadystatechange = function () {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var result = JSON.parse(this.response);
var _new_childid_value = result["_new_childid_value"];
contract = _new_childid_value.replace(/[{}]/g, "");
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}
};
req.send();
However, I get a bad request every time that the script runs. I need the guid returned by the call (contractid) to make another ajax call! The uri is fine,I tested the link in the browser and it returns the contractid that I want.
First issue Bad request can be solved by replacing GUID value childId for any {}.
Second issue, this is Ajax call which is asynchronous by mentioning true in req.open, hence you may have some other issue with request uri. That’s why readyState is undefined.
Try this. Take your uri & paste in browser address bar to see any clear error.
http://test.crm.dynamics.com/api/data/v8.2/new_childallergieses(guid)?$select=_new_childid_value
Changed from Asychronous to Sychronous and all of a sudden it worked!
var path_one = Xrm.Page.context.getClientUrl() + "/api/data/v8.2/new_childallergieses(" + child + ")?$select=_new_childid_value";
req.open("GET", path_one , false);
I did some investigating and realized that the function is set to execute on load, and sending an asynchronous call on load gives a bad request.

Data Cant Display in Rest API call by Javascript

I am using rest API in Javascript, Jquery to gepcoding. in this code i cant get data outside from xmlhttp.onreadystatechange = function() function
There is my Code to get data From Google API
var postdata = '{"cellTowers":[{"cellId": '+cid+',"locationAreaCode": '+lac+',"mobileCountryCode": '+mcc+',"mobileNetworkCode": '+mnc+'}]}'
xmlhttp = new XMLHttpRequest();
var url = "https://www.googleapis.com/geolocation/v1/geolocate?key=YOURKEY";
xmlhttp.open('POST',url,true);
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(postdata);
var lat;
var lng;
var data = '';
var json;
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
if (xmlhttp.responseText)
{
var data = xmlhttp.responseText;
var json = JSON.parse(data);
lat = json.location.lat;
lng = json.location.lng;
alert(lat+""+lng); //Working [1 operation]
}
}
};
alert(lat+""+lng); //Not Working [2 operation]
in this Code i am trying to get postdata out side xmlhttp.onreadystatechange = function() function and but i get null value. because when i run program i see first [2 operation] operation after then i see [1 operation]
have any problem in my code? or give me suggestion about that problem. or can any different way to use that API
Your code works just fine. Function runs asynchronous, when event happens. It is normal that 2 operation gets executed before the answer gets back from remote API. Please let me know what makes you unhappy. Code is fine, works as intended, gets the answer from remote API when available. The answer can only be received inside the function, then you should continue calling followup code, as for you app logic from there.

JSON from get request not returning properly

I'm running a Heroku server and I'm trying to change the innerHTML on my website to display certain statistics gathered from an endpoint on the server:
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.send();
xhr.onreadystatechange = processRequest;
var element = document.getElementById('change');
element.innerHTML = xhr.valueinJSON;
function processRequest(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
alert(response.ip);
}
}
My script tag contains the above and although the endpoint works properly in Postman, the JSON is always null. Any suggestions?
I'm not sure if valueinJSON is from an API I'm not familiar with, but I can't find a reference to it. Either way, you need to change your innerHTML in the async function like this:
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
var element = document.getElementById('change');
element.innerHTML = response
}
You are trying to set the innerHTML before the browser has a chance to download it.
This assumes there is not a CORS issue. You should check your browser's console to make sure there are not errors.

How to set multiple HTTP headers in JavaScript get () method

I have been searching the total Internet from around a week and finally decided to post here. I want to send an HTTP get request to an API with two headers for authentication. These are custom headers and need to be sent at once.
I have tried the following code but it never gives me success. The API returns a JSON file which will have parameters like "title", "description". The URL and headers work fine, when I tried it using hurl.it.
This is the code. Please suggest some answer to solve this problem. And one more thing is, I want to do it using JavaScript only, no jQuery, AJAX, or AngularJS.
var xmlhttp = new XMLHttpRequest();
var url = "https://affiliate- api.flipkart.net/affiliate/offers/v1/dotd/json";
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 &&xmlhttp.status==200) {
var myArr = JSON.parse(xmlhttp.responseText);
function display(arr) {
var i;
var out = " ";
for(i = 0; i < arr.length;i++) {
out += "<p>title:" + arr.dotd[i].title + "<br>description:" + arr.dotd[i].description + "<br></p>";
}
document.getElementById("p1").innerHTML = out;
}
}
else {
alert(xmlhttp.status);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.setRequestHeader("Fk-Affiliate- Token","xxxxxxxxxxxxxxxxx");
xmlhttp.setRequestHeader("Fk-Affiliate-Id","xxxxxxxxx");
xmlhttp.send();

PubSub.js multiple subscriptions, or a different way to handle awaiting on multiple callbacks

I am trying to figure out the best way to handle this scenario. Basically I want the flow to work like this:
1.) Get configuration data from server (async)
2.) Run doStuff() after configuration data is received (async)
3.) Run postResults after doStuff() completes
Currently I seem to have this flow working using PubSub.js, however I am trying to figure out how I can provide the results from config data (#1) to postResults (#3). While I seem to have the flow working with PubSub, I'm not sure how to access the configuration (#1) callback data from postResults (#3)
Here is a code summary:
PubSub.subscribe('config', doStuff());
fetchConfigurations();
function fetchConfigurations () {
var req = new XMLHttpRequest();
var url = CONFIGURATION_SERVER_URL;
req.onreadystatechange = function() {
if (req.readyState == 4 && req.status == 200) {
var configObject = eval('(' + req.responseText + ')');
PubSub.publish('config', configObject);
} else {
console.log("Requesting config from server: " + url);
}
}
req.open("GET", url, true);
req.send(null);
}
function doStuff() {
PubSub.subscribe('results', postResults);
var results = {};
// do some async work...
results['test1'] = "some message";
results['test2'] = "another message";
PubSub.publish('doStuff', results);
}
function postResults (doStuffId, doStuffData) {
var req = new XMLHttpRequest();
var url = TEST_RESULTS_URL; // I want to get this from the configObject is get in fetchConfigurations
req.open("POST",url,true);
req.setRequestHeader("Content-type","application/x-www-form-urlencoded");
req.send(doStuffData['test1'] + doStuffData['test2']);
}
Using promise seemed like the a better fit for this problem instead of pub/sub, here is the implementation I ended up using:
https://github.com/hemanshubhojak/PromiseJS

Categories