can you please help me to get these values using XMLHttpRequest ? How can I do it using javascript , I am unable to get them , it write undefined when I try to alert the value of any of these.£ It will help me a lot please ,
Thanks ! I also want the 'privilege values' , thanksenter image description here
You can use this
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://brainly.in/api/28/api_users/me", true);
xhr.onload = function () {
if (this.status === 200){
var data = JSON.parse(xhr.responseText);
var nick = data.data.user.nick;
var privlage = data.data.user.privileges;
alert(`The nick is ${nick} and privileges are ${privlage.join(',')}`
}else{
alert("Failed to load API")
}
};
xhr.send(data);
Next time post the text version of your JSON instead of an image that way I can be certain about the Objects, but that concept should work
Related
Using the code I found from one of the StackOverflow postings, I'm trying to call a REST service GET method. However, when the code runs it is not putting the GET format correctly in the URL.
Here's the code:
<!DOCTYPE html>
<script>
function UserAction(json)
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function ()
{
if (this.readyState == 4 && this.status == 200)
{
alert(this.responseText);
}
};
xhttp.open("GET", "http://localhost:8080/isJsonValid/json", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send(json);
}
</script>
<form>
<button type="submit" onclick="UserAction(json)">Check if JSON Valid</button>
<label for="json">JSON:</label>
<input type="text" id="json" name="json"><br><br>
</form>
</html>
The expected format of this GET REST service would be:
http://localhost:8080/isJsonValid/json
(where json in the line above is the actual JSON sent as a parameter.)
Yet, what is shown in the URL line includes the project, directory and the URL has the ?name=value syntax.
Since the GET doesn't match the simple http://localhost:8080/isJsonValid/json format, I get a 404 error.
I realize there's something obvious I'm missing.
Thanks to all for suggestions.
If you need to send data you need to either send it as a query param or as the body. If you want to send it as a body need to use POST type. Below is the example of POST type.
// Create a request variable and assign a new XMLHttpRequest object to it.
var request = new XMLHttpRequest()
// Open a new connection, using the GET request on the URL endpoint
request.open('GET', 'https://ghibliapi.herokuapp.com/films', true)
request.onload = function() {
// Begin accessing JSON data here
var data = JSON.parse(this.response)
if (request.status >= 200 && request.status < 400) {
data.forEach(movie => {
console.log(movie.title)
})
} else {
console.log('error')
}
}
// Send request
request.send()
For post Request. As I don't have any API with me I have used get API URL.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
console.log(this.responseText)
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
xhttp.open("POST", "https://ghibliapi.herokuapp.com/films", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send("Your JSON Data Here");
Thanks all for the great input and help!
The best solution for me was to just use, as suggested, a POST. The GET was always putting the "?" in the URL even if I concatenated it, That "?" isn't how the REST service interprets the GET parameters so it wouldn't work that way. In the REST framework I'm using, GET parameters are just concatenated with one or more "/" as separators in the URL.
Appreciate all the terrific help here on SO. :)
I'm trying to call a Restful service on my localhost. I am doing it this way because It's an asynchronous call. The appropriate Url plus the Uri-template to call my service is this:
"http://localhost:65016/Service1.svc/SN?lower=200&upper=300"
on the line where I try to open ( xhttp.open ), my client page only receives the proper data whenever I literally insert the url like this:
xhttp.open("GET", "http://localhost:65016/Service1.svc/SN?lower=200&upper=300" , true);
but I need the 200 and 300 numbers to be user input so I tried these two things:
I first tried grabbing the user input and simply concatenating it to the base URL in between the URi template like this:
<script>
function ServiceCall()
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function ()
{
if (xhttp.readyState == 4 && xhttp.status == 200) {
var ans = document.getElementById("secretNum");
ans.innerHTML = xhttp.responseText;
}
}
var base_uri = "http://localhost:65016/Service1.svc/";
// grab the lower number
var ln = document.getElementById("LN").firstChild;
var LN = ln.nodeValue;
// grab upper number
var un = document.getElementById("UN").firstChild;
var UN = un.nodeValue;
//complete
var URL = base_uri + "SN?lower=" + LN + "&upper=" + UN;
xhttp.open("GET", URL, true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send();
}
</script>
Doesn't work. So i tried looking at the documentation for the xmlHttpRequest.open, and I saw that the parameter had to be a URL. so I tried using the URL(string) function and using the output as a parameter and that didn't work either.
Any help please?
Thank you. I it helped to look at the network request. I was simply using the wrong syntax to obtain the value inside of the html input tag.
var ln = document.getElementById("LN").value;
returns the real value inside of html input tag given by the user input.
I'm answering my own question because this is a homework assignment.
(Not that I was cheating. Answering this is far from solving the homework)
Using a XMLHttpRequest with something like
xhttp.send('msg=message');
Causes a response from a server which returns "message" when asked to respond with req.body.msg.
How do I approach the problem if I want to store the msg value to send in a variable and write the request to post the variable as msg? In other words how to let what comes after msg= be interpreted as variable and not string?
You could use template literals to insert the variable value into the string
let text = "message";
xhttp.send(`msg=${text}`);
You could also just use +
let text = "message";
xhttp.send('msg=' + text);
Please show below code:
let text = "message";
var xhr = new XMLHttpRequest();
var params="msg="+${text};
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status==200) {
alert(xhr.responseText);
}
}
xhr.open('POST', url where you want post data, true);
xhr.send(params);
I am trying to write templates for a mobile app, as I only know pure JavaScript, so my plan is replacing the default template with a new one. After few hours I was nearly exhausted on this issue. It is not CORS thing and all the files are in localhost.
function getTheme(){
var xhr = new XMLHttpRequest();
xhr.open("GET", "model/1/index.html", true);
xhr.responseType = "document";
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 0) {
var customTheme = document.getElementById('crapDiv');
customTheme.innerHTML = xhr.responseXML;
}
}
}
xhr.send(null);
}
This Ajax works quite fine when I test with a text file, but as MDN said, to retrieve a html with ajax, a "document" responseType must be declared, thus, with the xhr.responseXML it only returns a DOM object, which is [object HTMLDocument]
I just can not parse this object back into contents so that I could not insert it into another html file.
So, How could I get through with this issue plz? and, plz only pure JS code.
You can't edit a file's content with JavaScripts, you can only read it. It's not for that. You need a server with eg PHP that can save your data.
You can get the response data as raw text with xhr.responseText.
Finally I got it.
function getTheme(){
var xhr = new XMLHttpRequest();
xhr.open("GET", "model/1/index.html", true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 0) {
var customTheme = document.getElementById('crapDiv');
customTheme.innerHTML = xhr.responseText;
}
}
}
xhr.send(null);
}
The diff is just the declare of the responseType, by default it is "", and xhr.responseText is the right way to retrieve the content, while the xhr.responseXML is the right way to retrieve the DOM object.
As it should be xhr.responseText, so there is no more need to declare responseType, and must be "" or "Text" if you still want a decalration.
Thnx.
I'm using XMLHttpRequest to read a text file (on local) after a period of time (after 10s).
After 10s, XMLHttpRequest retrieves the text file but the content (responseText) does not changed even though I have changed it.
Here is my code:
var list = [];
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
if (xhr.responseText.length == 0) {
undef();
}
else {
def();
}
}
}
getFile();
function getFile() {
list = [];
xhr.open("GET", chrome.extension.getURL('text/list.txt'), true);
xhr.send(null);
}
var myVar = setInterval(function(){getFile()}, 10 * 1000);
function def() {
// do something
}
function undef() {
// do something
}
I don' know why and how to fix it, please help.
The fast/lazy solution is to change your link address without changing the file it's accessing.
Modify your link with LinkToFile+"?="+Math.random()
It won't match anything in the cache but it will fetch the same file.
I found the problem, it is that the folder containing the file that I use when coding is different from the folder containing the extension when added to Chrome.
I just modified the wrong file.
Thank you everyone for your help.