For some context, I'm looking to read a csv file that is stored on a sharepoint - and I'm looking to do this from the frontend (a vue component) of my vue web application, and display it on that vue.
This post was really helpful
However, I don't make use of jquery anywhere in the application and only need to read the csv file in one part of my code. Therefore, I was wondering how I can go about implementing this with just the XMLHttpRequest API as opposed to jquery's AJAX?
I am not sure I understood your question completely, but here is what I think might be the answer:
using XMLHttpRequest():
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
document.getElementById("demo").innerHTML = xhttp.responseText;
// in here you basically manipulate your dom with fetched data or call on functions.
}
};
xhttp.open("GET", "yourApiUrl", true);
xhttp.send();
JSON:
let url = 'https://example.com';
fetch(url)
.then(res => res.text())
.then(out =>
console.log('My data here', out))
.catch(err => throw err);
JSON is Like XML Because
Both JSON and XML are "self describing" (human readable)
Both JSON and XML are hierarchical (values within values)
Both JSON and XML can be parsed and used by lots of programming languages
Both JSON and XML can be fetched with an XMLHttpRequest
JSON is Unlike XML Because
JSON doesn't use end tag
JSON is shorter
JSON is quicker to read and write
JSON can use arrays
The biggest difference is:
XML has to be parsed with an XML parser. JSON can be parsed by a standard JavaScript function.
Why JSON is Better Than XML
XML is much more difficult to parse than JSON.
JSON is parsed into a ready-to-use JavaScript object.
Source: W3School
Related
I have a directory that contains
--index.html
--script.js
--file.xml
and I want to read the content of the file.xml as a string in order to replace a few words within the xml-file. (Later on I would like to send the edited xml-file as e-mail).
I managed to access to xml-file, but did not manage to save the whole content in a string and/or replace some known keywords within the xml.
This is where I got so far:
var oXHR = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
function reportStatus2() {
if (oXHR.readyState == 4) // REQUEST COMPLETED.
console.log(this.responseXML) // This gets me the XML-document, but I want the complete xml content as string
}
oXHR.onreadystatechange = reportStatus2;
oXHR.open("GET", "../file.xml", true);
oXHR.send();
I found so many posts on that topic here, but none was able to answer my question!
Any ideas?
Look at the documentation for XMLHttpRequest.
Here is the documentation for the property you are reading:
XMLHttpRequest.responseXML Read only
Returns a Document containing the response to the request, or null if the request was unsuccessful, has not yet been sent, or cannot be parsed as XML or HTML. Not available in workers.
Now look around. Just three entries earlier it says:
XMLHttpRequest.responseText Read only
Returns a DOMString that contains the response to the request as text, or null if the request was unsuccessful or has not yet been sent.
So use that instead.
That said, XML is a structured data format with some fairly complex rules and it you should use DOM to edit it and not string manipulation (which is error prone and much more likely to result in invalid XML in your output).
I am referencing a JSON file through a web service. The file contains an unnamed object. How do I refer to the object?
I am referencing the file like any normal JSON file
<script src="http://somewebservice.com/object.json"></script>
object.json
{
"one":1,"two":2,"three":{
"one":1,"two":2
}
}
Do I really need to use JSON.parse()? It's already in a JSON file format.
JSON is format that uses human-readable text to transmit data objects, so if "referencing a JSON file through a web service" means you get it as String in HTTP response, then yes, you have to use JSON.parse() to get javascript object from the string.
Loading your data using <script src="http://somewebservice.com/object.json"></script> will leave you with no handle to the loaded resource.
Either use JSONP or, if a cross-origin policy is place, load the resource using some ajax mechanism.
Using fetch
fetch("http: //somewebservice.com/object.json").then(function (res) {
try {
console.log(JSON.parse(res));
}
}).catch(console.error);
I ended up using AJAX to retrieve the remote file.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var objects=JSON.parse(this.responseText);
console.log(objects);
}
};
xhttp.open("GET", "http://somewebservice.com/object.json", true);
xhttp.send();
I need some help trying to modify the response of an XHR request. My application is calling the api with the url:
https://xxxxxxxx.xxxxxxxx.com/api/bookings?locale=en
The api returns a objects in json format, where I need to replace this response with my own created json file (in the same object format)
I'm using Nightwatch, and have looked at this libery quite some time now.
Xhook
I have already created the JSON file with name "reservations.json".
Have looked at the xhook.after method which look like this:
browser.injectScript('//cdn.rawgit.com/jpillora/xhook/1.3.1/dist/xhook.min.js', function() {
xhook.after(function(request, response) {
if (request.url.match('api/bookings'))
response.text = "testtest";
});
})
Hope someone will help me on this one.
I am sending an AJAX request to server and retrieving a response as a json object from the server with javascript code to my android application. I know the key values of the json object(ID, name, status, etc.) but I do not know how to get their values.(100, Mark, success, etc.) I need those data for processing for some other task. Can someone please tell me how to extract data from that json object. When I use alert(http.responseText); as follows I get the json object displayed. I need to get the values out of it.
method used to receive response
http.onreadystatechange = function() { //Handler function for call back on state change.
if(http.readyState == 4) {
alert(http.responseText);
json object I receive
{"header": {"ID":100,"name:"Mark"},"body":{"status":"success"}}
You have to convert The string to an object by doing var response=JSON.parse(http.responseText);
Just treat it like any object - console.log(response['name'])
You need to convert it to a JavaScript object using JSON.parse:
var obj = JSON.parse(http.responseText);
Since some legacy browsers do not have native JSON support you should include json2.js to shim it for those browsers.
you will have to eval the http.responseText to get the json object...
but using eval is not recommended, so you can use the json2 library to parse the text into json object..
or else you can even use the library like jquery and use function parseJSON to get it converted to json object
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.