How to get data from local JSON using Ajax? - javascript

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()
{}
});

Related

Wikipedia API. File not found Error

I'm trying to make a wikipedia search bar. The idea is to send a new AJAX request every time search input is changed. I'm using https://www.mediawiki.org/wiki/API:Search_and_discovery as a guideline.
var search = $('#search');
search.keyup(function() {
if (search.val() === '') {
result.html('');
}
$.ajax({
url: '//en.wikipedia.org/w/api.php',
data: {
action: 'query',
list: 'search',
format: 'json',
srsearch: search.val()
},
dataType: 'jsonp',
success: function(response) {
console.log("success!");
}
});
});
However, success function is not even triggered.
On any keypress the error I get is this ("d" pressed):
jquery-2.1.1.min.js:4 GET file://en.wikipedia.org/w/api.php?>callback=jQuery21107844703783826772_1484403407494&action=query&list=search&srse>arch=d&format=json&_=1484403407495 net::ERR_FILE_NOT_FOUND
Thank you in advance for any help or guidance!
Well, you're probably trying to do a AJAX request without a local server (opening your file directly in the browser).
First of all, your url options starts with //en... (without the protocol). It indicates that it'll construct your full url using the same protocol you're using. In this case: file://. That's because your browser is trying to reach file://en.wikipedia.org/....
So, you can set your url to https://en.wikipedia.org/w/api.php to make it work.
Just replace:
url: '//en.wikipedia.org/w/api.php',
with:
url: 'https://en.wikipedia.org/w/api.php',
Looks like you're running it from a simple html file located in your filesystem, in other words not running it from a web server (even local).
Try calling the api with
url: 'https://en.wikipedia.org/w/api.php'
or run the file from a web server (can be a local one).

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
}
});
}
}));

Path for jquery ajax for reading a json file

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

Strange javascript / json error after server migration

I have a website hosted on server A that sends a request to a website on server B.
The website on server B has recently seen moved to another server. Lets call that server C.
Since the server migration the information that gets requested is not longer being displayed on server A.
The javascript that server A uses to send the request can be seen below:
<script type="text/javascript">
jQuery(document).ready(function() {
var ppUrl = 'http://www.nowgamernetwork.com/widgets/index.php?widget=popular&sourcetag=/other/&callback=jsonp1372412035546&_=1372412036723';
jQuery.getJSON(ppUrl, function(data) {
jQuery('.ipPopularPosts').append(data.content);
});
});
</script>
Interestingly, if you put the request URL into a broswer, it dislays the correct information.
http://www.nowgamernetwork.com/widgets/index.php?widget=popular&sourcetag=/other/&callback=jsonp1372412035546&_=1372412036723
But when the website requests this information, I get the following javascript errors:
Resource interpreted as Script but transferred with MIME type text/html: "http://www.nowgamernetwork.com/widgets/index.php?widget=popular&sourcetag=/other/&callback=jsonp1372416916349&_=1372416917575". jquery.js:3501
Uncaught SyntaxError: Unexpected token < index.php:1
The error above relates to line 1 on index.php which can be seen below:
<script type="text/javascript">window.jQuery || document.write("<script src='http://www.nowgamernetwork.com/js/libs/jquery-1.5.1.min.js'>\x3C/script>")</script>
For some reason, Server A doesn't like the fact that the response it is getting from server C starts with a '<'.
How can I fix this problem?
Any help would be appreciated!
use &callback=?' in the url
dataType: 'jsonp'
(function($) {
var url = 'http://www.nowgamernetwork.com/widgets/index.php?widget=popular&sourcetag=/other/&callback=?';
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
$(document.body).html(json.content)
},
error: function(e) {
console.log(e.message);
}
});
})(jQuery);
<script src='http://www.nowgamernetwork.com/js/libs/jquery-1.5.1.min.js'>\x3C/script>
See the problem?
Fixed it.
The PHP script on server C was using 'ob_get_contents' to pull all of the html into a json format. I noticed ob_start was missing so I added that and it now returns that data in the correct format.
For some reason server B didn't require ob_start to make it work.

How to send XML request in JavaScript

I have an eye tracker (mirametrix) running as a server in localhost. In order to capture data from this I should send a xml request as given below;
SEND:<GET ID="TIME_TICK_FREQUENCY" />
I have a web-app running as the client and I need to make a request to this server through that. I wrote the following code but it doesn't seem to send the request properly to the server.
var request = $.ajax({
url: "http://127.0.0.1:4242",
type: "GET",
dataType: "xml",
data: {
data:'<GET ID="TIME_TICK_FREQUENCY" />'
},
});
Can someone please help me with this ?
Thanks in advance
$.ajax({
url: ajaxurl,
data: "<root><blah><blah></root>",
type: 'POST',
contentType: "text/xml",
dataType: "text",
success : parse,
error : function (xhr, ajaxOptions, thrownError){
console.log(xhr.status);
console.log(thrownError);
}
});
I think you need to post it.
this is not plain javascript.. looks more like jquery.. also what do you mean with 'properly'. It's kind sending it, but not really? Aside from that, I see the following problems
The url is wrong, and although your browser may handle it, your url should end with a slash.
Your xml is invalid. Needs to start with <?xml version="1.0"?>.
If you accessed this script through a different host than 127.0.0.1., or if the script is running on a different port than 4242, this will not work without CORS headers on the server.

Categories

Resources