I have jquery ajax call which will go to a .js file and returns JSON
var validate = function () {
alert('test string');
}
$.ajax({
url: "JS/JQB/SampleData/Filters.js",
async:false,
success: InitailiseJQB
});
Filters.js file contains below JSON,
[{
"id": "Group",
"filters": [{
"id": "49be7d78-4dcf-38ab-3733-b4108701f1",
"validation": {
"callback": validate
}
}]
}]
in the above JSON validate is the javascript function but the problem is when i am requesting for the JSON using ajax call, it is throwing run time error called JavaScript runtime error: Invalid character
On success, are you sure you mean to call:
success: InitailiseJQB
There may be an accidental spelling error there.
Related
I have jsonp callback functionalty. Response coming from server is undefined.I do not know where the problem is. I have made RND for jsonp. I am posting code
$.ajax({
url : 'http://192.168.16.111:8081/MiddleWareUsman/androidServlet',
type: "GET",
dataType: "jsonp",
crossDomain: true,
async: false,
data : {"fname": "chaaaaapiio","lname": "gya"},
jsonpCallback: function(data, status){
alert('callback');
alert(data);
},
success: function(data, status){
alert('sucess');
},
error : function(xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
});
And Servlet code is
String a=request.getParameter("fname");
String b=request.getParameter("lname");
String cb=request.getParameter("callback");
response.getWriter().write(cb+"("+a+" "+b+")");
First, jsonpCallback is used when you want to override the default function name. If you assign a function to it, then the return value of that function should be the name. Giving it a function that returns undefined is just going to break things.
Remove the jsonpCallback property from your object. Handle things in success.
Second, that servlet code is going to generate:
jQueryCallback23235(chaaaaapiio gya)
This isn't valid JavaScript. You need to have a real JavaScript data structure as your function arguments.
Typically, a JSONP response would consist of an object literal:
jQueryCallback23235({ "something": "chaaaaapiio", "something": "gya")
Find a Java library for generating JSON and use that to produce the contents of the parens, don't try to write JSON by hand.
I've looked around for a while now, seen many similar problems, but none that help. I have a getJSON call that calls my Spring controller and responds with JSON text (Verified that JSON text is indeed being returned), but the callback is never executed (Based that nothing executes within the callback function and I don't receive errors with bad JavaScript).
In my jsp file:
function getUserText(str)
{
$.getJSON("selectUser.htm", { id: str }, function(user)
{
//Doesn't matter what's here
});
}
In my controller:
#RequestMapping(value="/selectUser.htm")
public #ResponseBody String SelectUser(#RequestParam String id)
{
Users user = userMap.get(id);
if (user == null)
return null;
return createUserJSON(user);
}
I'm not sure about this, but my guess is the function you provide is the success function that gets called when ajax returns. It is possible that the request is not returning successfully.
It means the JSON is invalid. It could be the content is invalid or the content-type is not correctly set....
$.getJSON has no error callback
http://api.jquery.com/jQuery.getJSON/
to see what the problem is you need to use
$.ajax({
url: "myurl",
type: "GET",
dataType: "json",
success: function() {
//called when successful
},
error: function(e) {
//called when there is an error
},
});
Found the answer. Turns out that the JSON needs to be valid. I made a mistake so the JSON wasn't formatted correctly. I didn't know that the format mattered even before the callback function.
I am new on JQuery. I have this JSON response from the server how could I parse it?
[
{
"note": {
"created_at": "2012-04-28T09:41:37Z",
"updated_at": "2012-04-28T09:41:37Z",
"text": "aaaaaaaaaaafdafasd fasfasd dfa sdfasf asdfa fasdfda",
"lng": 44.5159794497071,
"id": 7,
"deleted": false,
"user_id": 1,
"note_type": "text",
"lat": 40.1884140543842
}
},
[ ... more JSON ...]
]
How could I parse this?
You have to set the data type of the request to "json", and the data will be already parsed in your success callback.
Everything you need to know at the moment is on http://api.jquery.com/jQuery.ajax/
Here is a very simple example of what you can do:
$.ajax({
url: url, // the service URL. Must answer proper JSON
data: { // the parameters of the request. This should be adapted to your case
param1: value1,
param2: value2
},
dataType: "json",
type: "POST",
success: function(resultData) {
// here, resultData is your parsed json
},
error: function() {
// handle error here
}
});
jQuery.parseJSON
Use this jQuery method to parse JSON objects.
If the server outputs actual JSON (the example in the question has errors) and it has the correct content type (application/json rather then the text/html that PHP defaults to) then you don't need to do anything.
jQuery will parse it for you (and present you with a JavaScript object in the success handler).
That's not JSON. What you have posted looks like a PHP array that had brackets wrapped around it to try to make it into JSON.
Use this site to validate your JSON in the future.
Now, to get your PHP array into JSON, use json_encode() and dispatch it to the browser with a specific header.
$array = array( 'test' => 'sure' );
header('Content-type: application/json');
print json_encode($array);
exit;
Now, you'll have actual JSON with which you can use in JavaScript.
$.get( 'yourFile.php',
function(data){
console.log(data);
}
);
I am trying to make an ajax call and it returns something like, a JSON object;
{
id: 6,
success: "true"
}
My ajax call is :
window.foobar = function(foo){
$.ajax({
url: "http://foobar.com/sites/foo/",
dataType: "jsonp",
success: function (data) {
alert(data);
},
error: function () {
}
});
}
This ajax call is cross site call.
On chrome it gives: Uncaught SyntaxError: Unexpected token :
On firefox it gives:
invalid label
http://localhost:8080/sites/foo/?callback=jsonp1324336100888&_=1324336100894
Line 1
But when I calling from the same domain it works fine.
If you are claiming to support JSONP, you need to actually support it. Your code is valid JSON, but it is not valid Javascript: a response to a JSONP request must be valid Javascript. (To be precise, your code is invalid because the {} delimit a block, rather than an object literal.)
If you implement JSONP, you need to wrap the data in a call to a function whose name is given in the URL, in the callback parameter. So in this case, you need to post the following code:
jsonp1324336100888({
id: 6,
success: "true"
});
Obviously the precise name of the function you need to call depends on the callback URL parameter.
I have a problem accessing JSON data. I'm new to JSON and jquery so there is probably a easy solution to it and I would be glad to find out.
My jQuery:
$.post(
"currentPage.php",
{
'currentPage': 1
},
function(data){
$("body").append(data);
}
);
currentPage.php:
$returnArray['left'] = 'test_left';
$returnArray['right'] = 'test_right';
$returnArray['numLeft'][] = 1;
$returnArray['numRight'][] = 2;
$returnArray['numRight'][] = 3;
print json_encode($returnArray);
I tried to access the data like this:
data.left
data['left']
but it returns blank, how is the best way to access the data in the HTML-file?
I could be wrong, but I don't think the post method assumes a data return-type of json. You could set that by changing the ajax function to:
$.post(
"currentPage.php",
{
'currentPage': 1
},
function(data){
$("body").append(data);
},
"json"
);
Provide the datatype you expect to get as parameter to the .post() method (in your case json):
$.post("currentPage.php",{'currentPage': 1},
function(data){
$("body").append(data);
},
'json' // <-- add the expected datatype
);
I think the default is to treat the result as HTML. Read the documentation.
jQuery.post( url, [ data ], [ success(data, textStatus, XMLHttpRequest) ], [ dataType ] )
urlA string containing the URL to which the request is sent.
dataA map or string that is sent to the server with the request.
success(data, textStatus, XMLHttpRequest) A callback function that is executed if the request succeeds.
dataType The type of data expected from the server.
In JQuery, you need to set the return data type (dataType) to json so the function knows what type of data to expect and process. From the manual:
"json": Evaluates the response as JSON
and returns a JavaScript object. In
jQuery 1.4 the JSON data is parsed in
a strict manner; any malformed JSON is
rejected and a parse error is thrown.
(See json.org for more information on
proper JSON formatting.)
You can do this with the full $.ajax() call, or you can use $.getJSON(). There is no HTTP POST shortcut to return JSON (i.e. $.postJSON doesn't exist), but you can supply the dataType parameter to $.ajax() or just add the parameter to $.post() . When you have a JSON object, use json.keyName to access the data.
$.ajax({
url: "currentPage.php",
data: {
'currentPage': 1
},
dataType: "json",
type: "post",
success: function(data) {
$("body").append(data);
}
});