How to get "Data" field from xhr.responseText? - javascript

I have XMLHttpRequest() function given below
var searchFriendRequests = function (userid) {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost:6344/api/Registeration/searchFriendrequests?userid=' + userid, false);
xhr.setRequestHeader("Content-Type", "text/xml");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var data = xhr.responseText;
}
}
};
xhr.send(null);
}
where xhr.responseText returns value as
{
"$id": "1",
"ContentEncoding": null,
"ContentType": null,
"Data": [
{
"$id": "2",
"email": "anu#gmail.com"
},
{
"$id": "3",
"email": "anu#gmail.com"
}
],
"JsonRequestBehavior": 1,
"MaxJsonLength": null,
"RecursionLimit": null
}
How can I get the Data field from the responseText?

use JSON.parse(), like:
var data=xhr.responseText;
var jsonResponse = JSON.parse(data);
console.log(jsonResponse["Data"]);

You first need to parse responseText in JSON, for this you should use JSON.parse(). Then you can access it using key.
var json = JSON.parse(xhr.responseText);
var yourData = json.Data; // or json["Data"]

To simply get the email, or any other field, from the Data object, use the following:
data.Data[0].email
WORKING EXAMPLE

For sometime now you can use:
xhr.responseJSON
without any parsing needed. hope it helps

should parse the response to json object first,then get the data field from the response
var responseText = JSON.parse(xhr.responseText),
data = responseText.Data;

When you make your ajax request you can provide dataType option:
dataType: 'json'
For such request when you receive response:
If json is specified, the response is parsed using jQuery.parseJSON before being passed, as an object, to the success handler. The parsed JSON object is made available through the responseJSON property of the jqXHR object.
you can access your data like:
var data = xhr.responseJSON
Full example:
$ajax.({
dataType: 'json',
success: function( xhr ) {
var yourData = xhr.responseJSON;
console.log( yourData );
},
});

var jsonResponse = JSON.parse(xhr.responseText);
console.log(jsonResponse);

Related

how to call a service using ajax javascript?

I'm learning programing, could you explain me how to call a service using ajax javascript?
Service information:
Service type: REST
Basic authentication
Estructure: Application/JSON
Url: https://osb.urosario.edu.co/uxxi-URO/WsFotografias/proxy/AdministradorFotografiasJsonPS/fotos/consultar
User: Admi
Password: admi
Parameter JSON example: {"identificacion":["98122811999"]}
I've tested this service in postman
Service answer:
{
"respuesta": [
{
"estado": "Correcto.",
"identificacion": "98122811999",
"imagen": "return string Base 64 format"
}
]
}
Using JQuery :
$.ajax({
type: 'POST',
url: 'https://osb.urosario.edu.co/uxxi-URO/WsFotografias/proxy/AdministradorFotografiasJsonPS/fotos/consultar',
dataType: 'json',
data:{"identificacion":["98122811999"]}
contentType: "application/json"
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', make_base_auth("admi", "admi"));
},
success: function (data,status) {
//do what you want with the data after success
//in this example the response will be promoted in the browser console
console.log(data);
});
});
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = btoa(tok);
return 'Basic ' + hash;
}
You can call your above RestEndpoint using below:
xmlhttp.open("POST", "/EndpointURI", true);
xmlhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
//Use parse() method to convert JSON string to JSON object
var responseJsonObj = JSON.parse(this.responseText);
//use response
}
};
var jsonData = {"name" : "yourData"};
xmlhttp.send( JSON.stringify( jsonData ) );
For Authentication use this:
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://EndPointURI", true);
xhr.withCredentials = true;
xhr.setRequestHeader("Authorization", 'Basic ' + btoa('userName:password'));
xhr.onload = function () {
console.log(xhr.responseText);
};
xhr.send();
For authentication part, use JQuery then it will easy for the implementation and as well for understanding. as now aday no body use basic xmlhttp for calling api in javascript, last time i used was a 2003 developed application.

Can not get item of JSON-response

I am trying to create a AJAX call - and I would like to work with the response.
This is my response I see in my browser's network console:
{
"message": "success",
"file": "dump.xml"
}
And this is what I want to do:
onComplete: function onComplete(data) {
var vm = this;
console.log(data.file);
this.$set('upload', data);
this.$set('filename', file);
this.modal.show();
}
Okay. Well - I'm getting a response and if I write data to console.log, I'm getting this:
{"message":"success","file":"dump.xml"}
But if I try to do:
console.log(data.file);
I'm getting undefined. But why?
You are receiving it as a string. You have to parse it first to JSON by:
data = JSON.parse(data);
console.log( data.file )
OTHER OPTION: Or you can define it on request, add dataType: "json" so that you will receive json.
Like:
$.ajax(
{
type: "POST",
dataType: "json",
url: url,
data: {},
success: function( response ) {}
}
I think the problem is that data is a JSON string, so it will be printed in console, but when you call data.file it will be undefined. as string doesn't have a file property.
You need to parse your data object, before accessing file property:
data = JSON.parse(data);
console.log(data.file);
Most probably your data will be a JSON string. You have parse it into an Object like below
onComplete: function onComplete(data) {
data = JSON.parse(data)
var vm = this;
console.log(data.file);
this.$set('upload', data);
this.$set('filename', file);
this.modal.show();
}

Retrieving response payload elements from XMLHttpRequest

I'm sending a JSON request (an applicative login but the kind of request doesn't matter) to a server with the following function:
function login() {
var payload = {
"api_key" : "", "cmd" : "login",
"params" : {}
}
payload["params"]["username"] = document.getElementById("uname").value
payload["params"]["password"] = document.getElementById("passwd").value
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:4000/api", true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.setRequestHeader("Accept", "application/json");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
resp = JSON.parse(xhr.responseText);
console.log("resp.status=" + resp.status);
console.log("resp.[\"status\"]=" + resp["status"]);
}
}
xhr.send(JSON.stringify(payload));
}
I'm actually getting the correct reply in the responseText field. For example, if the credentials are wrong, I get
{
"status": "ko",
"errors": [
{
"cmd": "login",
"long": "Login error : 'user-20' has no access to the system",
"short": "login_error"
}
]
}
If the credentials are OK I get
{
"status": "ok",
... some additional data
}
Yet, I can't manage to get the status field : resp.status or resp["status"] are always undefined. Same if the call is done in asynchroneous mode (xhr.open("POST", "http://localhost:4000/api", false);) or if I don't JSON.parse() the reply, ie: resp = xhr.responseText;.
Update - 2017.09.06
I finally found a way to get it working, but I don't quite understand why it is so. I actually changed
resp = JSON.parse(xhr.responseText);
into
resp = JSON.parse(JSON.parse(xhr.responseText));
To figure this out, I printed typeof(xhr.responseText) which is a sting. Actually typeof(JSON.parse(xhr.responseText)) is also a string and this is why it has no fields like status. Eventually, parsing xhr.responseText twice gives an object from which I actually can retrieve my data.
If somebody has a clue about what is happening, I would be interested... I don't know if this is related, but the app server that is sending the JSON is the latest version of Elixir/Phoenix, ie, 1.5/1.3 and JSON encoding/decoding is done with poison.
This is because you have assigned the resp variable to responseText
resp = JSON.parse(xhr.responseText);
To get the response code
respCode = xhr.status
Or if you want both in the same resp variable you could do
resp = {
responseText: xhr.responseText,
status: xhr.status
}
Then you can access them as resp.responseText and resp.status

jQuery vs. JavaScript ajax 'POST' functions

This jQuery code is working:
$.ajax({
type: "POST",
url: "file.php",
data: { json: json },
complete: function (data) {
var result = data.responseText;
console.log(result); // logs 'echo' from PHP file
}
});
This JavaScript code is still not working:
var xhr = new XMLHttpRequest();
xhr.open("POST", "file.php", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var result = xhr.responseText;
console.log(result); // supposed to log 'echo' from PHP file
}
}
xhr.send(JSON.stringify(json));
Aren't these two approaches equivalent, or am I missing something?
Suppose 'file.php' looks something like this:
if(isset($_POST['json'])){
$obj = json_decode($_POST['json']);
//some php operation
// echo $obj keys and values
}
data : { json: json }
gets serialized to '{ "json": {data} }'
JSON.stringify(json)
gets serialized to '{data}' and there is no "json" key
add your javascript object to a parent wrapper object with a "json" key
JSON.stringify({ json: json });

Getting a JSON file using XMLHttpRequest() but when I console.log the responseText I get an empty string?

When I say console.log(getErrors) I receive this in the console:
XMLHttpRequest {statusText: "", status: 0, responseURL: "", response: "", responseType: ""...}
onabort: null
onerror: null
...
responseText: {"content":[{"id":1,"timeStamp":"2015-03-20T00:01:44.761","provider":"foo","providerId":null,"lineNumber":1,"summary":"foo","description":"foo: 1"}...
responseType: ""
responseURL: "http//localhost:8080/errors/findAll"
...
I know I'm getting the data because I can see it in responseText but when I say console.log(getErrors.responseText) I'm getting an empty string. I'm not sure what I'm doing wrong.
Javascript:
var getErrors = new XMLHttpRequest();
getErrors.open('GET', '/errors/findAll', true);
getErrors.send();
//var response = getErrors.responseText;
console.log(getErrors);
console.log(getErrors.responseText);
Here is my working code in Javascript:
getErrors = function(url, callbackFunction) // How can I use this callback?
{
var requestErrors = new XMLHttpRequest();
requestErrors.onreadystatechange = function()
{
if (requestErrors.readyState == 4 && requestErrors.status == 200)
{
callback(requestErrors.responseText); // Another callback here
}
}
requestErrors.open('GET', url);
requestErrors.send();
}
function callback(data) {
console.log(data);
}
getErrors('/errors/findAll', callback);

Categories

Resources