Path for jquery ajax for reading a json file - javascript

I use this to read a json file stored on my server:
$.ajax({
type:"GET",
url:path,
contentType:"application/json; charset=UTF-8",
dataType:"json"
success:function(response)
{
console.log(response);
//stuff...
}
});
I have tried specifying the path as MyProject/build/web/leaflet/temp/xyz.json and as build/web/leaflet/xyz.json.
In both the cases I get a response of 404.
I have tried with both paths using $.getJSON,I find that the error occurs when the readyState of the XMLHttpRequest is 1.
How should I specify the path for getting the json file?

A relative URI in JS in the browser needs to be relative to the HTML document that is hosting the JavaScript.

Add / before your path and have a try.
ex: /MyProject/build/web/leaflet/temp/xyz.json or /build/web/leaflet/xyz.json

Related

Relative path in Ajax works differently in different environment

It is a SpringBoot website. The html page url is http://xxxxx/trex/index/ And javascript code segment in index page as below
$(function(){
jQuery.ajax({
contentType:'application/json;charset=UTF-8',
type: "POST",
url: "getSignTypes",
cache: false,
dataType: "json",
success:function(data){
if(data !== 'NA'){
console.log(data);
$('#signType').combobox({
valueField:'id',
textField:'title',
editable:false,
data:data,
value:data[0].id
});
}
},
error:function(msg){
console.log(msg)
}
});
})
You can see I use relative path in url parameter of this ajax request. I guess since it is relative url, it should be converted into http://xxxxx/trex/index/getSignTypes. I test it in my local, and yes, it is as expected http://localhost:8088/trex/index/getSignTypes.
But when I deploy it to UAT, I find that the url is converted to http://hswcfc-trainexp-web.uat.homecreditcfc.cn/trex/getSignTypes. The index part is gone.
Why relative path in Ajax works differently in different environment? The ajax code is exactly the same. Any clue I can trace to find the difference? Thanks.
I past the UAT screen shot here.
A HTTP URL consists of several parts: protocol, hostname, port, username, password, path, query string (?....) and fragment (#....).
As suspected, your URL path ends in / in dev, but not in UAT. Think of it as "directories": /trex/index/ is the empty file name in /trex/index directory, while /trex/index is the file index in /trex directory. Web servers often treat the two the same way, but clients do not: when you do a relative path from there, you get /trex/index/getSignTypes in the first case, but /trex/getSignTypes in the second.
This is usually fixed by creating a redirect rule so that you can never accidentally write the same URL in two different ways (e.g. by redirect /trex/index to /trex/index/).

How to get data from local JSON using Ajax?

Hello brilliant people!
I've been sitting hours trying to figure out why I cant load a local JSON file using Ajax. I bet it's some silly typo, of that I totally misunderstand something. I'm using Node.js Express.
The location of the two files:
"trollytrains/views/trips.ejs" (Doing the ajax-request)
"trollytrains/json/allstops.json"
$.ajax(
{
type: "GET",
url: "../json/allstops.json",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert('success');
},
error: function (msg) {
alert("error");
alert(msg.responseText);
}
});
I have tried altering the URL in all kinds of variations:
./allstops.json
allstops.json
json/allstops
/json/allstops
/json.allstops.json
No matter what I type I get a 404 error.
GET http://localhost:1337/json/allstops.json 404 (Not Found) jquery.min.js:4
Am I entering the wrong URL, or is there some other problem in my code that I haven't detected? I'm very new to JSON and Javascript so I wouln't be surprised.
I'd really appreciate some tips!
Best
/ J
Am I entering the wrong URL, or is there some other problem in my code that I haven't detected?
It depends on whether you can access the URL in the request in your example:
GET http://localhost:1337/json/allstops.json 404 (Not Found) jquery.min.js:4
See if you see the correct JSON when you go to http://localhost:1337/json/allstops.json with the browser. If you get 404 then this JSON is not served at this PATH and the problem can be either your backend failing to serve the JSON or you using the wrong URL.
It's impossible to tell you if you backend code is fine if you didn't include even a single line of the code that actually attempts to serve the JSON in question.
My assumption would be that you're not serving the JSON files.
I assume that you entire app is located in trollytrains directory and you have a json directory inside. To serve what's there you need to use something like this if you're using Express:
app.use('/json', express.static(path.join(__dirname, 'json')));
For more options to serve static files with and without Express, see this answer:
How to serve an image using nodejs
Try this.
$.ajax({
url: '../json/allstops.json',
dataType: 'json',
data:
async: false,
success:function()
{}
});

download a file from url - Javascript ajax

There's a CSV file uploaded to the server that I want to parse using javascript/jquery.
I'm trying to get the file using ajax call but it's always giving me error.:
XMLHttpRequest cannot load
https://1fichier.com/?w5hfqz60tk&_=1474818392318. No
'Access-Control-Allow-Origin' header is present on the requested
resource.
$.ajax({
url:'https://1fichier.com/?w5hfqz60tk',
type: "GET",
dataType: "text",
success: function (data){
parseFile(data);
},
error:function(e){
}
});
I need to run the above code in jsFiddle.. How can I bypass this error?
Or is there any alternative way to download a file?
Update: I just found out that adding url like this: https://crossorigin.me/MY_HTTP(S)_LINK solved my problem but I'm looking for an authentic way.
How can I bypass this error? Or is there any alternative way to
download a file?
You can use $.getJSON(), YQL
var url = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20csv%20where%20url%3D'https%3A%2F%2F1fichier.com%2F%3Fw5hfqz60tk'%0A&format=json&callback="
$.getJSON(url, function(data) {
console.log(data.query.results)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Content-Type Ajax json missing

I wrote some php code that outputs some valid json, and sets the content-type header to application/json in my dev setup. However when I deploy this script to a embedded webserver it works fine except it's not capable of sending the content-type. It's not possible to run a other webserver.
Now I have the following code for Dynatable. Even though my dev and my embedded webserver, serve exactly the same file, and the only difference is the content-type. It works for my dev setup, however it doesn't work for my embedded setup.
I use the following code to load the json file to dynatable.
document.ready(
$.ajax({
url: 'phpApi.php',
success: function(data){
$('#myTable').dynatable({
dataset: {
records: data
}
});
}
}));
So can someone explain me why the content-type is so important for ajax? How can I tell my code manually its json?
Without the content-type the returned data is assumed to be plain text. There is nothing in your code to tell it otherwise.
One way to get json would be to specify the return type in the jquery code. Just add dataType: 'json' into the ajax configuration.
Or you could use eval() to transform the returned text to json.
document.ready(
$.ajax({
url: 'phpApi.php',
success: function(data){
$('#myTable').dynatable({
dataset: {
records: eval(data)
}
});
}
}));
Using JSON.stringify(eval(data)) might give you better results by making sure its json.
As pointed out below, JSON.parse(data) would probably be safer. (Eval is evil after all.)
So can someone explain me why the content-type is so important for ajax?
It's important so the client can identify what type of content the server returned, content-type: application/json tells jQUery to parse the data as an object. If no content type is returned, the client will assume the returned data is just plain text.
How can I tell my code manually its json?
Add dataType: "json" parameter to $.ajax()
document.ready(
$.ajax({
url: 'phpApi.php',
dataType: "json",
success: function(data){
$('#myTable').dynatable({
dataset: {
records: data
}
});
}
}));

parse xml using jQuery

i am parsing Xml using ajax function in jquery in a jsp file
$.ajax({
type: "GET",
url: "sites.xml",
dataType: "xml",
success: function(xml) {
}
});
My problem is my xml file is not in the same path as my jsp file. The jsp path is webProject/webcontent/temlates/store/SearchResult.jsp and the xml path is webProject/webcontent/WEB-INF/config/ampliflex.xml.
What should my url be in the $.ajax({ function?
Please Suggest
I would have thought that the WEB-INF directory would be private by default and so not accessible via an AJAX request. Try moving the XML file to some other part of your project.
Why not simply use:
$.ajax({
type: "GET",
url: "webProject/webcontent/WEB-INF/config/ampliflex.xml",
dataType: "xml",
success: function(xml) {
}
});
Do you see the file if you try accessing it directly with your browser (via localhost i mean)? if your ajax request can see the file so can your browser directly. i would suggest trying to find the correct url in your browser and use that in your ajax request.
Furthermore as mentionned above it is possible the WEB-INF directory is not accessible to client (hence my first question in this comment) so you can also try moving the xml file to a directory you know is accessible.

Categories

Resources