Get Response Data in XML format - javascript

We use JSON.stringify(oData); to get data in json, and how could we get data in the form of xml?
oModel.read('/', null, null, true, function(oData, oResponse){
var data = JSON.stringify(oData);
document.write(data );
});

You're using an OData service, but you're wanting the response in a certain format. That can only mean, to me, that you're wanting to bypass all the work that the ODataModel mechanism does for you and get the raw XML that is returned by the OData server. If that is the case, I have a question and an answer for you.
Question: Why?
Answer: If you really want to get the XML from the OData response, i.e. the raw Atom feed that typically comes back from, say, a Northwind entityset like http://services.odata.org/Northwind/Northwind.svc/Products , then you can actually access the whole HTTP response object in the success callback of the read() method. Extending the source code in your question a bit, it would look like this:
oModel.read('/', null, null, true, function(oData, oResponse){
document.write(oResponse.body);
});
This will produce something like this:
<feed xml:base="http://services.odata.org/Northwind/Northwind.svc/" xmlns="http://www.w3.org/2005/Atom" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
<id>http://services.odata.org/Northwind/Northwind.svc/Products</id>
<title type="text">Products</title>
<updated>2014-08-26T07:33:36Z</updated>
<link rel="self" title="Products" href="Products"/>
<entry>
<id>http://services.odata.org/Northwind/Northwind.svc/Products(1)</id>
...
But - are you sure you really want this?

To get XML formatted response, add $format=xml to your odata url
See example :
http://services.odata.org/Northwind/Northwind.svc/Products?$format=json
http://services.odata.org/Northwind/Northwind.svc/Products?$format=xml
And to get response in XML format, use the sap.ui.model.xml.XMLModel
oModel.read('/?$format=xml', null, null, true, function(oData, oResponse){
var xmlDataModel = new sap.ui.model.xml.XMLModel(oData);
});

Related

Parsing JSON to populate the dhtmlx grid

I get JSON as a response, from an ajax call, the contents of which I then want to be loaded in the grid.
From the JQuery documentation, http://api.jquery.com/jQuery.ajax/, for response of type JSON:
"json": Evaluates the response as JSON and returns a JavaScript
object.
So I convert the JavaScript object back to JSON using JSON.stringify:
importConfigurationStatusGrid.parse(JSON.stringify(result), "json");
But the grid doesn't get populated.
The response I get looks like this:
{"rows":{"Added to index":["file1", "file2",...."],
"Conflicting":["file3", "file4",..."], "Removed":["file5",
"file6",...."]}}
I checked the JSON format on https://docs.dhtmlx.com/grid__data_formats.html#jsonformat, and I think the difference between the two(the response I get and the format specified) might be the cause.
How can I parse the JSON string using the parse method of dhtmlxGridObject?
result = {"rows":{"Added to index":["file1", "file2",...."], "Conflicting":["file3", "file4",..."], "Removed":["file5", "file6",...."]}}
importConfigurationStatusGrid.parse(result, "json");
Edit 1:
#ogui: I don't know what your AJAX request looks like, but you can add
a dataType property and set it to json so that your result gets
automatically parsed as an object for you.
The ajax request does have a dataType: 'json' property specified. So there isn't a need to use JSON.parse(). The problem lies in converting the JS object to a valid JSON format that the parse(dhtmlx) method requires.
#ogui: You could aso use jQuery.getJSON().
Even if I were to use this method, the grid object would have have to parse the same JSON, which it is failing at.
Use JSON.parse.
result = JSON.parse(result);
I don't know what your AJAX request looks like, but you can add a dataType property and set it to json so that your result gets automatically parsed as an object for you. This is mentioned in the jQuery AJAX documentation page you linked. You could aso use jQuery.getJSON().

JSON Reader issue: cannot access jsonData

I have a strange thing going on here: I am using a JSON reader within a store to fetch search results. After loading the store I receive data or error states (built together as a JSON, too). So in both ways I get a successfully response, so I have to check the JSON for myself to trap "error conditions". But I cannot access the jsonData property that shhould be a JSON object within the reader. Chrome tells me that:
I can access the applyDefaults though (it returns true in that case) but not the jsonData.
My code looks like this:
var result = searchStore.getProxy().getReader();
console.log(result.jsonData);
The output is "undefined". As you can see in the picture the jsonData object holds my JSON (with the isError property I wanted to access).
What I am doing wrong?
You need to think more async and think of the timing it takes for a request to return and when you are trying to get the jsonData. Instead of using console.log, set a breakpoint or use the debugger; statement so you can freeze the browser and walk through the code. You can then inspect variables and such to see what the object looks like.
Try to access your JSON data in a success callback, to make sure the data is gathered from the server.

get the geolocation from IP , with "ipinfodb"

i know good javascript but totally novice in json and need to do the following:
get the geolocation from IP , with "ipinfodb"
like this response:
OK;;174.88.229.95;CA;CANADA;QUEBEC;MONTREAL;H1A 0A1;45.5088;-73.5878;-04:00
i found many codes for that but all seem to be complicate and long with more options like saving the results in cookies
i want the least necessary code to retrieve those informations
for saving them in cookies and more i want to care for it my self after.. (i don't like to put code i dont understand)
the best would be a simple function that returns this information as string or array, like this
function getLocFromIP(IP){
(js + json code)
return result;
}
much thank in advance
thank you all for responding i was trying to filter out the solution, and it works but i'm not yet well satisfied of the result..
i gonna reformulate my question here:
is there i can retrive the geo location from ip with simplest way (javascript) that means without json or jquery..
ajax would be perfect but it doesnt work inter domain (different domains)
thanks again
OK;;174.88.230.88;CA;CANADA;QUEBEC;MONTREAL;H1A 0A1;45.5088;-73.5878;-04:00
The example you posted isn't valid JSON (you can check if something is valid JSON somewhere like here). That said, looking at the ipinfodb website they appear to have a way to get JSON output using their API (see here).
Once you have valid JSON, you can use JSON.parse. See here for some examples on using it.
So the general idea is
function getLocFromIP(IP){
//(js code to use ipinfodb API to get valid JSON reponse)
//(js code using JSON.parse to parse the received JSON reponse)
//(js code to get whatever you want as the result)
return result;
}
As a side note, if you use jQuery you can also use jQuery.parseJSON to parse JSON (see here) which will be more reliable if you anticipate clients using older browsers that might not support JSON.parse.
IP location XML API requires some query strings like &format=json&callback=? additional to ip address in order to get json.
Then you get json like this:
{
"statusCode": "OK",
"statusMessage": "",
"ipAddress": "175.108.204.0",
"countryCode": "JP",
"countryName": "JAPAN",
"regionName": "TOKYO",
"cityName": "TOKYO",
"zipCode": "214-002",
"latitude": "35.6149",
"longitude": "139.581",
"timeZone": "+09:00"
}
Here is a sample code (thanks to #iveoak for good template):
function getLocFromIP(IP){
//(js code to use ipinfodb API to get valid JSON response)
var url = 'http://api.ipinfodb.com/v3/ip-city/?key=<your_api_key>&ip=' + ip + '&format=json&callback=?';
var response = $.getJSON(url); // using jQuery
//(js code using JSON.parse to parse the received JSON response)
response.then(function (location) {
var info = '<ul>';
for (var key in location) {
info += '<li>' + key + ': ' + location[key] + '</li>';
}
info += '</ul>';
});
//(js code to get whatever you want as the result)
return result;
}
If you do not use jQuery, see How can I open a JSON file in JavaScript without jQuery?.
Sample (using jQuery): http://jsfiddle.net/tokkonoPapa/tevB4/
I post another answer.
This is a pure javascript solution using jsonp. Basically, it's a same concept using <script src="http://api.ipinfodb.com/..."></script>.
So you can accsess from anywhere, and do not need to handle json directly. You can simply get the javascript object.
Here is my demo: http://jsfiddle.net/tokkonoPapa/vCTpK/
UPDATE:
I/F is slightly different what you want. It uses a callback function.
getLocFromIP(ip, function(result) {
// use result
});
and the demo returns:
OK;;175.108.204.0;JP;JAPAN;TOKYO;TOKYO;214-002;35.6149;139.581;+09:00
I hope this basic solution satisfies you.

How does Javascript differentiate between Json Objects and String?

I was reading a code snippet and figuring out how it works when this weird javascript problem came up.
In their javascript they called
var apiUrl = '/api/v1/pin/?format=json&order_by=-id&offset='+String(offset);
...
$.get(apiUrl, function(pins) {
for (...; i < pins.objects.length; i++) ... // works fine
});
their api returns this json format:
{"meta": {"limit": 50, "next": "?limit=50&format=json&order_by=-id&offset=60", "offset":
10, "previous": null, "total_count": 79}, "objects": [ {...},{...}, ... ]}
I tried to mimic it but the $.get never accepted my simplified json string.
// my attempt
$.get(myApiUrl, function(pins) {
for (...; i < pins.objects.length; i++) ... // ERROR: undefined length
});
My Json string is in the similar but shortened format.
{"objects": [{...},{...}, ... ]}
I couldn't get it to work until I googled the $.getJson() command. I am just wondering why their javascript code works with just $.get whereas mine has to use $.getJson??
Is it some kind of header you can set to force javascript to read it as json?
If you don't specify content type explicitly jQuery will try to determine data type based on headers returned by server.
If you are not using JSON serializers, then verify validity of your JSON using http://jsonlint.com/ or this, otherwise you will get an error.
Correct ContentType header for JSON is: application/json
In both cases the AJAX call returns a string. jQuery somehow has to figure out what to do with it. How it does that depends on the dataType option.
The docs call the default value Intelligent guess. So how to guess? Evaluating the Content-Type header of the response. If it's application/jsonthen jQuerywill try to create an object.
To ensure that jQuerywill always try to interpret the response as JSON you can set the dataType to json.
Set the HTTP response header Content-Type to application/json
Eg:
HTTP/1.1 200 OK
Content-Type: application/json

AJAX responseXML

i have a problem regarding the responseXML of ajax..
I have this code from my callback function:
var lineString = responseXML.getElementsByTagName('linestring')[0].firstChild.nodeValue;
However, the linestring can only hold up to 4096 characters max.. the remaining characters are rejected.
I dont know what to use to get all the values that the lineString
returns. its quite a big data thats why I thought of using the responseXml
of AJAX, BUT turned out it still cannot accomodate everything.
My linestring consists of lines from a logfile which I concatenated and just
put line separator. I need to get this data in my form so that is why after reading from the php, i send it back via AJAX
Do you have suggestions guys.
XML adds a lot of extra markup for most ajax requests. If you are expecting some kind of list with data entities, sending them in a JSON format is the way to go.
I used JSON to get quite huge arrays with data.
First of all, JSON is just Javascript Object Notation meaning that the Ajax Request would request a String which will actually be evaluated as a Javascript object.
Some browsers offer support for JSON parsing out of the box. Other need a little help. I've used this little library to parse the responseText in all webapps that I developed and had no problems with it.
Now that you know what JSON is and how to use it, here's how the PHP code would look like.
$response = [
"success" => true, // I like to send a boolean value to indicate if the request
// was valid and ok or if there was any problem.
"records" => [
$dataEntity1, $dataEntit2 //....
]
];
echo json_enconde($response );
Try it and see what it echos. I used the php 5.4 array declaration syntax because it's cool! :)
When requesting the data via Ajax you would do:
var response
,xhr = getAjaxObject(); // XMLHttp or ActiveX or whatever.
xhr.open("POST","your url goes here");
xhr.onreadystatechange=function() {
if (xhr.readyState==4 && xhr.status==200) {
try {
response = JSON.parse(xhr.responseText);
} catch (err) {
response = {
success : false,
//other error data
};
}
if(response.success) {
//your data should be in response
// response.records should have the dataEntities
console.debug(response.records);
}
}
}
Recap:
JSON parsing needs a little help via JSON2 library
PHP can send maps as JSON
Success boolean is widely used as a "successful/unsuccessful" flag
Also, if you're into jQuery, you can just set the dataType : "json" property in the $.ajax call to receive the JSON response in the success callback.

Categories

Resources