Correct path structure to open JSON object using AJAX - javascript

I'm trying to create a "mock API" module in JS, so I want to request data from a source (products.json) via a url like myapi.com/get/products. It doesn't have to be a legitimate API.
I have this working using an example JSON object from http://www.jsontest.com - but I'm not sure how to do this with my own external data, products.json
My function:
var displayProductList = (function() {
var productList = {
init: function(uri) {
this.getData(uri);
},
getData: function(uri) {
$.ajax({
context: this,
dataType: 'json',
url: uri,
success: this.runOutput
});
},
runOutput: function(data) {
...
}
}
productList.init('http://echo.jsontest.com/key/value/one/two');
})();
This works OK (I can't run it from JSFiddle as it's not https, but it should work): https://jsfiddle.net/xou1k8y8/1/
So my question is, how would I replace the URL in my code with the path to my directory get/products.json and be able to access the data therein?
For example:
productList.init('localhost/my-project/get/products.json');
Doing the above doesn't work. I've also tried adding /products so I can access the products JSON data below.
My JSON looks like this:
{"products":[
{
"id":"0001",
"title":"The Jungle Book",
"price":"13.60",
"currency":"GBP",
"isbn":"978-0062389503",
"stock":{
"in-stock":"yes",
"stock-quantity":"98"
}
}
};

Your localhost URL is not correct. You need to put // before the hostname in a URL, otherwise it's treated as a directory name.
productList.init('//localhost/my-project/get/products.json');
Note that because of the AJAX same-domain restriction, you can only do this when you loaded the HTML file from http://localhost.

Simply switch the URL for your file path:
getData: function(uri) {
$.ajax({
context: this,
dataType: 'json',
url: 'get/products.json',
success: this.runOutput
});
},
Simple as that c:

Related

AJAX POST successful but does not do anything

I am building a desktop app using electron. I want to keep the list of all the recent files opened, for this I am using jquery ajax. here is my code
// this function is expected to add a file entry to my json file
this.add_recent_file = function(file_id, file_name, date_opened) {
// Execute the ajax command.
$.ajax({
type: 'POST',
url: './data/recent-files.json',
dataType: 'json',
data: {
id: file_id,
name: file_name,
date: date_opened
},
success: function() {
console.log("Success");
}
});
}
and here is my sample json file:
[
{
"id" : "1",
"name": "File.json",
"date": "24-feb-2018"
}
]
the problem is that console says 'Success' but no changes in json file. Reloading the page didn't change anything.
You can use node.js filesystem to write to the json file. check out the following code.
var fs = require('fs');
var $ = require('jquery');
this.add_recent_file = function (object) {
$.ajax({
type: 'GET',
url: './data/recent-files.json',
dataType: 'json',
success: function (files) {
// append the entry to the array.
files[files.length] = object;
// Get JSON string representation of the array.
var str = JSON.stringify(files);
// Now write it to the json file.
fs.writeFileSync(recent_file_url, str);
},
error: function () {
alert('Error updating json file.');
}
});
}
As stated by #Gerrit Luimstra, you need a backend, If you're using PHP, you might use something like this:
data/update.php
<?php
$id = $_POST['id'];
$name = $_POST['name'];
$dateX = $_POST['date'];
//update database code here
Right now you are using AJAX to POST data to a JSON file and hope that this will update the file. This however is not the case.
What you can do instead is use Electron's file system to write changes to the JSON file.
In this case, your function would become something like:
this.add_recent_file = function(file_id, file_name, date_opened) {
// Create the JSON content
var data = {
id: file_id,
name: file_name,
date: date_opened
};
// If you want to prettify the JSON content
data = JSON.stringify(data, null, 2);
// Write it to the file
fs.writeFileSync('../path/to/recent-files.json', data);
}
This however requires you to use the node filesystem package.

How to write JSON array to file in node.js and request it again client side

I'm trying to create a drag-and-drop table with save and load functionality. I'm using code from REDIPS.drag.
When using the REDIPS save function the table content is returned, client side, to the console and alert like this:
[["d2",2,2,"blue","A1"],["d1",4,5,"blue","A2"],["d3",3,2,"blue","A3"],["d4",1,4,"blue","A4"]].
I've tried a few different ways to POST the data to node and write it to file.
With this method:
script.js
$.ajax({
type: "POST",
url:"post6/json",
data: {table_content},
dataType:'json',
contentType: "application/x-www-form-urlencoded"
});
App.js
var testjson = req.body;
var tablestringify2 = JSON.stringify(testjson);
fs.writeFile('views/test.json', tablestringify2,'utf8', function (err) {
if (err) {
// append failed
} else {
// done
}
})
The data saved to file is:
{"table_content":"[[\"ns1.8b\",3,1,\"\",\"ns1.8b\"],[\"ns3.1\",4,2,\"\",\"ns3.1\"]]"}
With this method:
script.js
$.ajax({
type: "POST",
url:"post6/json",
data: table_content,
dataType:'json',
});
The data is saved to file as:
{"[":{"\"ns1.8b\",3,0,\"\",\"ns1.8b\"":{"\"ns3.1\",3,2,\"\",\"ns3.1\"":""}}}
When I use a GET, I parse the data which returns;
{ table_content: '[["ns1.8b",3,1,"","ns1.8b"],["ns3.1",5,3,"","ns3.1"]]' }
or
{[:{"ns1.8b",3,0,"","ns1.8b":{"ns3.1",3,2,"","ns3.1":""}}}
Either form cant be loaded back into the table using the REDIPS load function.
Is there any way I could get the data in the following format;
[["ns1.8b",3,0,"","ns1.8b"],["ns3.1",3,2,"","ns3.1"]]
...returned on the client side?
Or would it be possible to save it to file like that?
Perform the stringify at the client side:
$.ajax({
type: "POST",
url:"post6/json",
data: {table_content: JSON.stringify(table_content)},
dataType:'json',
});
At the server side you should be able to access req.body.table_content which will be the (JSON) string representation of the array.

How to get Google maps URL with a 'placeid' with AJAX?

I have a URL which I can open on browser and view the JSON data. The URL looks something like this:
https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJZeH1eyl344kRA3v52Jl3kHo&key=API_KEY_HERE
Now when I try to access this with jQuery AJAX, I fail to get any results, instead I get an error.
My AJAX call looks some like this:
$.ajax({
url: https://maps.googleapis.com/maps/api/place/details/json,
data: {
'placeid': 'ChIJZeH1eyl344kRA3v52Jl3kHo',
'key': 'API_KEY_HERE'
},
dataType: 'json',
success: function(response) {
alert(JSON.stringify(response));
},
error: function(error) {
alert(JSON.stringify(error));
}
});
var API_KEY = api_key;
var placeid = placeid;
var API_URL = `https://maps.googleapis.com/maps/api/place/details/json?placeid=${placeid}&key=${API_KEY}`
$.getJSON(API_URL, {
tags: placeid,
tagmode: "any",
format: "json"
},
function(data) {
alert(data);
});
If I build it up correctly, this should be the way to send the data correctly to the api, using the placeid inside the url string together with the api_key.
Then you use a getJSON instead of json because I assume you want to get the place data? Assuming to what you're doing in the ajax you made.
Maybe explain further what you mean with how to get google maps url with place id? Hope it helps you out :)

Calling a C# method from JavaScript

I want to to call a method GetAccount from my controller AccountController.cs, in my JavaScript factory LoginFactory.js. Something like this:
AccountController.cs:
public Account GetAccount(string userName)
{ ... }
LoginFactory.js:
if(x>y) {
var account = <%AccountController.GetAccount(someParam);%>
}
I've tried using [WebMethod] and Ajax, but I can't get it to work: I get a 404 response.
Assuming your GetAccount method can be reached at /Account/GetAccount when your application runs, you could use the following:
$.ajax({
type: 'GET',
url: '/Account/GetAccount',
data: { 'username' : 'a-username' },
dataType: 'json',
success: function(jsonData) {
alert(jsonData);
},
error: function() {
alert('error');
}
});
Note - this is dependant on jQuery.
This causes the browser to make a request to /Account/GetAccount as if you had done so by entering the URL in the URL bar, but of course, captures the returned json for use in your client side (javascript) script.
If this returns a 404, it would be worth checking your routing.

How to use a JavaScript to load and parse a static JSON file in the server

I'm just starting to use javascript and json.
I need to read data (getInformation function) from a json file when processing an event in a javascript function. So I need it to be synchronic. I don't know if I am missing something in the code, or if I have to create an Request and handle the callback, or if I need to import additional javascript to use json. Because I don't know how to make it work. It doesn't work because at the end the array is empty. Any help is aprreciated.
The json file:
{"Users": [
{"Name": "Jane",
"Points": 67,
"age": 23},
{
"Name": "Sam",
"Points": 65,
"age": 21}
]}
Option 1 - Function called by another function which is processing an event:
var getInformation = function()
{
var path = "./data/users.json";
var informationArray= [];
console.log("Loading ....");
$.getJSON(path, function(data)
{
$.each(data, function(key, val)
{
informationArray.push(key + '-' + val);
});
});
return informationArray;
}
Option 2 - Function called by another function which is processing an event:
var getInformation = function() {
var path = "./data/users.json";
var informationArray= [];
$.ajax({
url: path,
async: false,
dataType: 'json',
success: function(response) {
$.each(response.items,
function(item) {
informationArray.push(item);
});
informationArray.push("success");
}
});
return informationArray; }
I have seen the following thread and tried what is there but doens't work for me. I would like to know where is the problem in my code or if require any special configuration.
Thread: Is there a version of $getJSON that doesn't use a call back?
When JavaScript is running in a browser it needs to make an AJAX request to the server to access a JSON file. It is possible to write the AJAX request by hand but that is complex and difficult to make work in all browsers. Instead most people use a library like jQuery. You will need to include jQuery in your web page with something like:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
Then in any script tag lower in the html page you should be able to do something like:
$.ajax({
url: "data/users.json",
dataType: "json",
success: function(response) {
$.each(response.Users, function(item) {
informationArray.push(item);
});
informationArray.push("success");
}
});
see http://api.jquery.com/jQuery.ajax/
To load a JSON file (and not require a callback) you'd use:
var url = 'http://yoursite.com/data/users.json';
var j = [];
$.ajax({
type: 'GET',
url: url,
dataType: 'json',
success: function(data) { j = data;},
async: false
});
alert(j.Users[0].Name);

Categories

Resources