I am trying to use jQuery's $.getJSON()
function to make a server-side AJAX call:
$.getJSON() {
url: "/my-server/some-url",
success: function() {
alert("Success!");
}
}
Firebug shows this as a JavaScript error:
SyntaxError: missing ; before statement
[Break On This Error]
$.getJSON() {
In reading the tutorial it appears that I'm using it right, passing in a URL and then a success callback. This particular URL doesn't require any data parameters, so I omitted them. Can anyone spot where I'm going awrye? Thanks in advance!
You want to call a function, using the getJSON arguments:
$.getJSON("/my-server/some-url", function(data) {
alert("Success!");
});
Or use $.ajax passing an object:
$.ajax({
url : "/my-server/some-url",
dataType : 'json',
success : function(data) {
alert("Success!");
}
});
To pass data (e.g. { dog: 1, cat: 4 }
which will be converted to URL parameters) you can pass the object directly to both functions:
$.getJSON("/my-server/some-url", { dog : 1, cat : 4 }, function(data) {
alert("Success!");
});
// Or
$.ajax({
url : "/my-server/some-url",
dataType : 'json',
data : { dog : 1, cat : 4 },
success : function(data) {
alert("Success!");
}
});
Your code is wrong. Try this:
$.getJSON("/my-server/some-url",function() {
alert("Success!");
}
});
Your code is closer to the $.ajax
method.
$.ajax({
url: "/my-server/some-url",
success: function() {
alert("Success!");
}
});
EDIT:
You can also pass URL arguments with the data
parameter.
http://api.jquery.com/jQuery.getJSON/
Data that is sent to the server is appended to the URL as a query string. If the value of the data parameter is an object (map), it is converted to a string and url-encoded before it is appended to the URL.
$.getJSON("/my-server/some-url",{ dog: 1, cat: 4 },function() {
alert("Success!");
}
});
// Requests: "/my-server/some-url?dog=1&cat=4
http://api.jquery.com/jQuery.getJSON/
$.getJson('url', function(data) {
//do stuff with data
});
The .getJSON
function is a shorthand for the .ajax
function
jQuery.getJSON( url [, data] [, success(data, textStatus, jqXHR)] )
$.getJSON("/my-server/some-url", function() {
//Success
alert("success");
});
You are not using the correct syntax. $.getJSON is a function with parameters. The first parameter is mandatory, and it's a string containing the url.
$.getJSON(
"/my-server/some-url",
data,
function(callback) {
alert('success')
}
);
$.getJSON is a shortcut for $.ajax, which is similar to what you wrote. $.ajax takes a single object as a parameter..
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback
});