Reading contents from a JSON url and writing out those contents - javascript

I have a url [https://www.inquicker.com/facility/americas-family-doctors.json] that is a JSON data url. How can I access the contents of this url, and write out the values.
The format contains schedules as an array that inside it contains schedule_id, name, and available_times. I have tried various ways of getting the JSON file, but none have worked.
UPDATE:
Well I have got it this far with this code, and it's laying out what looks like objects from the array. So I believe I got the cross site issue under control. I just need to figure out how to access the data now.
<!DOCTYPE html>
<html>
<head>
<title>JQuery (cross-domain) JSONP</title>
<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"> </script>
<script>
$(document).ready(function(){
$.getJSON('https://www.inquicker.com/facility/americas-family-doctors.json',
function(data){
alert(data.facility);
$.each(data.schedules, function(i, name){
$('#names').append('<li>' + name.available_times[0] + '</li>');
});
});
});
</script>
</head>
<body>
<ul id="names"></ul>
</body>
</html>
Any help, or suggestions will be greatly appreciated, Thanks.

You cannot generally pass an Ajax request across domains. Normally a server will refuse any Ajax calls that don't come from the same source unless it is explicitly configured otherwise. I am guessing that you aren't calling from the same domain, given that you are using a fully-qualified URL. If you own the server, you will have to configure it to accept such calls from your other domain.
If this is not the case, launch the script in Firefox with Firebug running and look at the console output and tell me what error you get if any.
Once you manage to pass the JSON from your server back to the page, you will retrieve it in your JavaScript as a string. You then need to execute this function:
var jsonObject = JSON.parse(jsonString);
where jsonString is the string that you received from your server. jsonObject becomes an object representation of the JSON passed back to the answer that you can access using dot notation.

Try something like :
alert(json.facility);
There is no title json object in the url you have mentioned.

The JSON is already parsed when it comes to your function.
$.get('https://www.inquicker.com/facility/americas-family-doctors.json', function(result){
alert(result.facility); //Do whatever you want here
// result.schedules array is also ready
});

Related

How to change : Fullcalendar generates GET request

I am implementing fullcalendar on my website.
I have created a div with calendar as id.
I have put data from a SQL query in a php variable and used json encode to get the right format.
This is how I create the calendar :
$html .= "<script src='/wp-content/plugins/biobelt/moment.min.js'></script>
<script src='/wp-content/plugins/biobelt/fullcalendar.min.js'></script>
<link rel= 'stylesheet' href='/wp-content/plugins/biobelt/fullcalendar.css' type='text/css'>
<script>
jQuery(document).ready(function() {
var bevents = '".$buildingevents."'
console.log(bevents)
jQuery('#calendar').fullCalendar({
defaultDate: '" . $_SESSION['statDateFrom'] ."',
editable: true,
events: bevents,
});
});
</script>";
The console log gives me an output of the array that I am passing to events, and it is the correct format :
[{"id":"1","titre":"1","start":"2018-04-09 07:00:01","stop":"2018-04-09 11:00:00"},{"id":"2","titre":"1","start":"2018-04-09 07:00:01","stop":"2018-04-09 11:00:00"},{"id":"3","titre":"2","start":"2018-04-09 16:00:01","stop":"2018-04-09 21:00:00"},{"id":"4","titre":"2","start":"2018-04-09 16:00:01","stop":"2018-04-09 21:00:00"}, etc...
What I get from this is :
GET 403 Forbidden Error
I checked in apache logs, this is because the URL is too long since every field of the array is put into the url.
For some reason I don't want to change the limit request line in apache conf file.
I want to generate a POST instead of GET request.
And I would like to know how it generates a GET request since I didn't put GET anywhere in my files.
EDIT :
according to : https://fullcalendar.io/docs/events-json-feed
Fullcalendar create the get request and the URL. The problem persists since the URL is too long and I want to create a POST request instead. How to do that?
You seem to have misunderstood the documentation somewhat.
You said
The console log gives me an output of the array that I am passing to events, and it is the correct format
And indeed what you've showed does look like a Javascript array. So...it's a static array and not a URL. You do not have any kind of server endpoint to which you can make a separate ajax call to get your events. Therefore the article you linked to (https://fullcalendar.io/docs/events-json-feed) is not relevant. Instead you are providing a static list of events as per the method described at https://fullcalendar.io/docs/events-array).
Except that...you're not. Due to the way you've written your code, you're providing a string instead of an array. That is causing fullCalendar to assume you're providing a URL, and then trying to call that URL, and it's no surprise that it errors.
If you simply remove the single quotes from
var bevents = '".$buildingevents."'
so that it becomes
var bevents = ".$buildingevents.";
then your code should work ok, because this will inject a hard-coded array into the JavaScript instead of a string.

How can I get json content in <script src="url.json">

How can I get the content of url.json, and cast the json to a variable.
The content of url.json is pure json format.
Thanx
if you use jquery
<script type="text/javascript">
var json_variable;
$.getJSON('url.json', function(json){
json_variable = json;
});
</script>
Are you aware of the jquery getJSON api? You can use this to download json from an url. Not sure if you can embed some json directly in a script tag, though.
You need to read in the contents from the url using AJAX and then put that into your variable or use the data as soon as you successfully get the data.
See here for non jQuery vanilla javascript methods: reading server file with javascript
and also
Consuming JSON data without jQuery (sans getJSON)

node.js javascript var available in res.render()'s target

I'm trying to make a variable (eventually to be replaced by more complex json selected from the database) accessible to client-side javascript. I wanted to load it when the page is rendered instead of an ajax call and its not going to be rendered via a template like ejs (I want to pass the data to an extjs store for a combobox). So I have a standart response I render:
function (req, res) {
res.render('index.html', {foo: ['a','b']});
}
and a blank html page I want to access foo:
<!DOCTYPE html>
<html>
<head>
<script type=text/javascript>
console.log(foo);
</script>
</head>
<body>
</body>
</html>
any ideas? I've thought of maybe writing the whole html page via res.send() (which has a few more things than the example above) but that seems like such a workaround for something that should be obvious to do...
Assuming the same array foo in your question above, here are a couple ways you could do this.
This one uses an EJS filter to write an array literal:
<script type="text/javascript">
var foo = ['<%=: foo | join:"', '" %>'];
</script>
This one encodes it as JSON, to later be parsed by your client-side javascript:
<script type="text/javascript">
// note the "-" instead of "=" on the opening tag; it avoids escaping HTML entities
var fooJSON = '<%-JSON.stringify(foo)%>';
</script>
IIRC, ExtJS can handle JSON directly as its data. If not, then you could use its JSON parser first and then hand it a local variable. If you weren't using ExtJS, you could use this to parse on the client: https://github.com/douglascrockford/JSON-js
If you choose to encode it as JSON, it would make it also make it easier to later switch back to AJAX for retrieving your data. In some cases, that would have an advantage. The page could load and display some data, along with a busy icon over the element for which you're loading data.
This isn't to say there's anything inherently wrong with including all the data in the original request. It's just that sticking with JSON gives you the flexibility to choose later.
In EJS the following should work
<script type=text/javascript>
console.log( <%= foo %>);
</script>
I do recommend against dynamically generating JavaScript though as it breaks seperation of concerns and forces JavaScript to be on.
Edit:
Turns out the above doesn't work nicely for arrays. So simply encode your data in semantic HTML. Then enhance it with JavaScript. If the JavaScript must get data then store it somewhere more sensible like the cookie or retrieve it through ajax.

how to post a json from javascript?

i want to send a json string from a html webpage using javascript to a WCF.. is there any good tutorial for that?
this is the code i am using
<head>
<title>Test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.json.org/json2.js"></script>
<script type="text/javascript">
$(function() {
JSONStringer json = new JSONStringer()
.object()
.key("cno").value("2000")
.key("cname").value("HI")
.key("cmail").value("HI")
.key("cphno").value("9292")
.key("cmailtype").value("Home")
.key("cphnotype").value("Office")
.key("clientno").value("1")
.endObject();
var dat = JSON.stringify(json.serializeArray());
alert("I am about to POST this:\n\n" + dat);
$.post(
frm.attr("action"),
dat,
function(data) {
alert("Response: " + data);
}
);
});
</script>
</head>
let me know where i have to post it to a particular service.. something like specifying the URL
I think you are mixing up java with javascript. Despite their names they are not related to each other in any way. As far as I know, JSONStringer doesn't exist in javascript nor jquery. JSON stands for JavaScript Object Notation, so that means it is very native to the javscript languages (with some subtle differences). Since it's so close it is very easy to parse Json in javascript.
Also, javascript is a dynamically typed language so supplying the type as you did normally results in a parse error. Use firebug or the Chrome console when your code doesn't work. You will see an error when the browser was unable to parse your code.
for the serialization you probably want to use (in a browser that supports JSON and/or with json2.js)
var dat = JSON.stringify({
cno: 2000,
cname: 'HI',
cmail: 'HI',
cphno: '9292',
cmailtype: 'home',
cphnotype: 'Office',
clientno: 1
});
The url goes where you have put frm.attr("action"). I don't see where you create the frm object. I don't think you need a JQuery object for that, document.getElementById is supported in all major browsers and I bet it is faster too.
var myForm = document.getElementById('myformid');
$.post(
myForm.action,
dat,
function(data) {
alert('Response: ' + data);
}
);
Also as far as I know, postdata has to be in query parameter format so perhaps you need to put something like
'myData=' + dat,
Copy/pasting code from the web can get things started quickly but a lot of javascript programmers forget that you have to understand the language first. Don't just blindly copy code, try to understand what happens. Try to solve problems first without a library and discover where you actually need a library.
http://www.learn-ajax-tutorial.com/PassingData.cfm#JSON
Get json.js.
Encode array or object in to json.
Do Ajax.Request to post the json string. Simplez!
That is pretty much all you need, not sure about the WCF side but if it is a proper webservice then all you need is the descriptor to figure out the function names and their parameters.

parsing json response

I'm calling a REST webservice and getting JSON format as a result. I'm calling rest service from another domain than mine. How can I parse this?
To answer the question you asked: There is a long list of parsers, including several for JavaScript, at the bottom of http://json.org/
If your question is actually: "How can I read JSON data from another domain with client side JavaScript in the browser?", then you can either fetch it using a proxy on the same domain as the page, or you can provide the data using JSON-P instead.
<script type="text/javascript" src="http://www.json.org/json2.js"></script>
var myObject = JSON.parse(myJSONtext);
or use jQuery
$.getJSON('http://twitter.com/users/usejquery.json?callback=?', function(json) {
alert(json.followers_count);
});
if you need only parsing jQuery also can do this:
var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );
Are you getting the json result? Most implementations have protection agains cross site scripting and will only allow a request back to the original host of a page.
Could you please post some example code for your current implementation.

Categories

Resources