Simple jQuery script fails to do anything - javascript

I'm new to jQuery and I have a simple jQuery script.
I've put this in my header:
<script src='http://code.jquery.com/jquery-latest.min.js' type='text/javascript'/>
In my body, I have this:
<script type='text/javascript'>
$(document).ready(function() {
alert(1);
$.getJSON('http://puppygifs.tumblr.com/api/read/json', function(data) {
alert(2);
});
});
</script>
But, while Firebug says the JSON is accessed and there are no errors, I only get the first alert, not the second. Why doesn't the second alert execute?

The json response returned by http://puppygifs.tumblr.com/api/read/json is not valid json, which causes the success handler not to execute.
If you look at the first line the response its var tumblr_api_read={, which isn't valid. To see a valid json example checkout: http://json.org/example.html
This situation is noted in the Jquery Documentation:
As of jQuery 1.4, if the JSON file contains a syntax error, the
request will usually fail silently. Avoid frequent hand-editing of
JSON data for this reason. JSON is a data-interchange format with
syntax rules that are stricter than those of JavaScript's object
literal notation. For example, all strings represented in JSON,
whether they are properties or values, must be enclosed in
double-quotes. For details on the JSON format, see http://json.org/.
getJson Documentation
Also be sure to close the script tag with an end tag and not the shorthand end tag
<script src='http://code.jquery.com/jquery-latest.min.js' type='text/javascript'></script>
If you are accessing this json from outside the providing domain you must indicate its jsonp This can be accomplished by appending &callback=? to the url as described in the jQuery Documentation.
$(document).ready(function() {
alert(1);
$.getJSON('http://services.faa.gov/airport/status/SFO?' +
'format=application/json&callback=?', function(data){
alert(2);
});
});
JS Fiddle http://jsfiddle.net/J5jYW/

Related

Issue with displaying the Jquery Ajax response in HTML

I need to load a page where that page needs to display some values with a dynamic pagination. So to load the values I have a rest call, In that rest call I am returning a json object. In the browser console I am able to see the json output. Now My issue is I am getting the response on $document.ready() function. Now I am trying to display the json object values in the HTML which is not happening.
JavaScript:
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url : "http://localhost:8080/school-service/school/list/students/1/1",
type: "GET",
dataType: "json",
}).done( function(studentList) {
console.log("AJAX request success:" +studentList.pageNumber);
}).fail( function(jqXHR, textStatus) {
console.log("AJAX request failed with status:" + textStatus);
});
});
</script>
HTML:
<img onclick='previousPage("${studentList.pageNumber}", "${studentList.pageCount}")' src="${context}/images/previous.png">
<c:forEach var="i" begin="1" end="${studentList.pageCount}">
${i}
</c:forEach>
<img onclick='nextPage("${studentList.pageNumber}", "${studentList.pageCount}")' src="${context}/images/next.png"/>
Can anyone please help me that how can I display the json response object value in HTML.
I think you can't because the code you want to replace in your page is belong to a server-side language (i guess asp) and server-side code will be compiled before javascript execution so you'll not found the tags those tags.
So, if I understand what you are trying to do, you are trying to get the value from your AJAX request and include the returned value from .done in the html?
If that is the case, check this link out: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
If you are returning a JSON object from .done, you will need to parse the JSON object into a string in order to place it in the DOM. From that point, you will need to decide where it should be placed. For example, you can create a div and say $('that-div').append(returned value).
Another approach could be having a default value in the html, and on .done, replace the html by calling .html on your response. But to do that you will need to grab a reference of $(this).
I hope this helps, if not let me know where my gaps are and we can go over this in a different way.
The code which you write is a server side code with JSTL, and it is not available when the AJAX response is returned.
JSP page will be converted to HTML.
The HTML page will call the server by using AJAX.
The returned response is a JSON which is received in a Javascrip Object.
You need to do some javascrip work to make your a tags
You need to write some Javascript code to render the returned response.
Try this instead
int pageCount = studentList.pageNumber;
Then in your html simply do this
<c:forEach var="i" begin="1" end=studentList.pageNumber>
i
</c:forEach>

Reading contents from a JSON url and writing out those contents

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

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.

Categories

Resources