How to create JSON response to AJAX request locally without WWW server - html

I want to practice with JSON and AJAX with HTML pages only (no PHP, no asp.NET, no ruby, no Web server locally installed). I want to create web page which will produce JSON data as result for test AJAX request.
Is it possible?
ADDED:
Lets change it a bit, suppose that I have a webpage (no asp.net, no php).
How to create web page with will output Json data with header set to
header('Content-Type: application/json');

You can give the AJAX request url as "file:///D:/test.txt"
I think IE allows it and Chrome doesn't. And I'm not sure if all versions of IE support it.
Ofcourse this 'response' will be static. It wont change based on your request inputs.

JSON are just javascript objects. What you can do is, instead of invoking the real ajax requests, do a mock request that fetch the locally declared json. For e.g.
jQuery (A concrete implementation)
$.get("ajax/test.html", function( data ) {
console.log(data);
alert( "Load was performed." );
});
Mock implementation
Create a fake json "factory"
var MockJson = (function () {
return { "mockObject" : "mockValue" };
})();
console.log(MockJson);
Of course my example is trivial, you can use the response to manipulate the DOM or display the value somewhere.

Related

MEAN.js $http.get() return index html content instead of json file

I'm doing a web app based on original MEAN.js framework. When I want to request local json test file using $http.get() method in my AngularJS file, it returned my index html content.Is it a routing problem? I didnot change the original mean.js routing code(https://github.com/meanjs/mean), just added a $http.get() method in home.client.controller.js file. Can anyone help me with this? Thanks!
That is most likely happening, because you didn't define an endpoint for that particular GET request in your app.
Everytime you make a request to your server (for example a GET request to /my-request) nodejs/express are configured in MEAN.js so that your server will try to find the endpoint for that request, if it does not find any, that request will be handled by this particular code block (specified in /modules/core/server/routes/core.server.routes.js):
// Define application route
app.route('/*').get(core.renderIndex);
Which will basically render the index view.
I'm not sure if you're using a custom module or not, eitherway, if you want that request to be handled in a different way in MEAN.js, you can specify your endpoint in your custom module routes file (or in core.server.controller.js) like so:
// Define application route
app.route('/my-request').get(core.sendMyJSON);
Be careful, because this route must be placed before the one I mentioned earlier, otherwise your request will still be handled the same way and the index view will be rendered and served again.
Then you will have to create the controller that should be called to handle that request:
exports.sendMyJSON = function (req, res) {
// logic to serve the JSON file
};
This way you should be able to get it done with a few adjustments.
Side note:
I'm not entirely sure but I think if you place your JSON file in the public directory of your app you should be able to directly access it without the need for the extra logic.

Any Angular library to directly query on json?

I am building an angular app with a rest endpoint as back-end. I already have my data in a json file and my data is almost static and not that big. Is it possible to let angular directly query on this JSON file, instead of relying on the remote rest endpoint?
Solution:
I have used linqjs for my purpose and it works great. Thanks.
You can query it directly using $http.get or an equivalent call. It works the same as any other $http call, except you obviously can't post, put, or delete.
$http.get('mydata.json')
.success(function(data) {
$scope.mydata = data;
});

Data array from Couchdb documents into D3

I am having a problem integrating Couchdb and D3. D3 is a Javascript library that performs document driven data visualization. Couchdb is a document database. They were made for each other.
D3 binds an array of data to DOM elements of a web page. In most of the examples I have seen on the web or in books, people are working on a static data set. Generally, examples will show an array written into the Javascript or a text.csv file loaded into the page.
I would like to take data directly from database documents and load it into D3. I'm uncertain how to do it. I have seen one example on the web where a person has loaded all of their data as an array into one couchdb document and then brought the data into index.html with a couchdb.jquery call:
/ This function replaces the d3.csv function.
$.couch.db("d3apps3").openDoc("sp500", {
success : function (doc) {
var data = doc.data;
data.forEach(function(d) {
d.date = formatDate.parse(d.date);
d.price = +d.price;
})
I tried something similar with db.allDocs:
<script type="text/javascript">
$dbname = "dataset2";
$appname = "dataset2";
$db = $.couch.db("dataset2");
$db.allDocs({
success: function (data) {
console.log(data)
}
});
</script>
I could get the data to render in console.log, but could not get it into D3 and index.html. I also realized that the datastream resulting from db.allDocs is limited to the _id and _rev of each document.
I also tried to GET the data from a Couchdb view with a d3.json call. That wouldn't work because d3.json is looking for an existing .json file.
It's funny, I can call the view with cURL using a GET command and see the datastream, but can't seem to bind it with D3.
~$ curl -X GET http://anywhere.com:5984/dataset2/_desing/list_view/_view/arnold
{"total_rows":25,"offset":0,"rows":[
{"id":"dataset.csv1","key":"0","value":null},
{"id":"dataset.csv2","key":"1","value":null},
{"id":"dataset.csv11","key":"10","value":null},
{"id":"dataset.csv12","key":"11","value":null},
Any ideas would be appreciated.
Part four of https://gist.github.com/anonymous/9275891 has an example that I think you'd appreciate. You don't need to rely on the jquery.couchdb library at all - d3 knows enough abuot http and json to work right out the box. The relevant piece of code is:
d3.json("_view/pricetimeseries", function(viewdata) {
// We just want rows from the view in the visualisation
data = viewdata["rows"];
data.forEach(function(d) {
// the key holds the date, in seconds
d.date = new Date(d.key);
d.price = +d.value;
});
// rest of the visalisation code
HTH
If the page in which your D3 code is embedded is not served from the same domain (+ port) than CouchDB you will have to enable Cross-Origin Resource Sharing.
Assume your page is at http://example.com/data.html which contains JavaScript D3 code that acesses data from http://db.example.com/ or http://example.com:5984/. In that case your browser (which is executing the JavaScript) will by default deny such (cross-origin) requests unless the requested domain explicitly allows it.
There are basically two solutions to this:
Serve both the data and the page from the same domain, either by
putting a reverse proxy in between that maps resources to upstream servers (eg /couch to your CouchDB server and everything else to your web server)
serving your static files directly from CouchDB
or by allowing Cross-Origin Resource Sharing, which is available in CouchDB since version 1.3. You can find a list of relevant settings in the CouchDB docs on CORS.

Preventing default views with RESTful api in CakePHP

I am following the tutorial in the CakePHP book that explains the basics of setting up a RESTful web service.
So far, I've updated my routes file to the following:
Router::mapResources('stores');
Router::parseExtensions('json');
I have also setup a blank layout in app/layouts/json and the appropriate json views. I am receiving my json output successfully when I navigate to controller/action.json
I am wondering though, without the.json extension it attempts to load the regular view. I am looking to build a pure api with only json output, is there any way to prevent regular render output instead?
You could force a rendering as JSON if you can recognise a JSON request another way. For example, if the Accepts HTTP header contains application/json, you could put this in your controller:
public function beforeFilter(){
if ($this->request->accepts('application/json')) {
$this->RequestHandler->renderAs($this, 'json');
}
parent::beforeFilter();
}
It's CakePHP 2.0 notation, but something similar probably exists for CakePHP 1.2 and 1.3.
You could also detect the request Content-Type instead, or as well, especially if Accepts is not used.
What are you seeing at the moment? If you've used bake Cake may have generated the views for you?
Just delete the views in /app/views/layout and /app/views/controllername
If you are trying to prevent the request from hitting the controller at all then I'm not so sure, you could just update your .htaccess file to only send requests ending in .json to the app or something similar.
here is what i did.
if i know i'm building only json API, i added to my AppController.php following:
public function beforeFilter()
{
if (empty($this->request->params['ext']) || $this->request->params['ext'] != "json")
{
$this->render(FALSE, 'maintenance'); //no view, only layout
$this->response->send();
$this->_stop();
}
}
and in my /app/Layouts/maintenance.ctp
echo __('Invalid extension');
this way all requests without the json extension will end up on the "maintenance" page where you can put any info you want, i'm planning to put there link to API docs.

How do I process Proxy Digg JSON for use with jQuery?

I'm trying to deal with: "Requests made from Javascript running on your web pages must be proxied to avoid same-origin policy conflicts."
I know how to work with the JSON once I've got it. But aside from copy-pasting the JSON results via my browser, I don't know how to localize it for use.
Did you tried
$.getJSON('url', function(data){
//do smth with data
})
?
After the request is complete, data will be an object with all JSON response and you can access it as regular js object: data.something and so on.