Reputation: 97
I am trying to send an AJAX request to my spring backend. I am hitting the controller, and am successfully responding. I am new to javascript and AJAX, so I have hit a ceiling that I cannot get through. I am trying to call "done" on a successful callback, and am getting a very non-descriptive error. This is my console after I push "button"
clicked testAjax. js:3
Uncaught SyntaxError: Unexpected token : product:1
I haven't created a product file, but when I go into it I get the object I am trying to send back on line 1 (the only line):
{"name":"Matthew","id":0}
My AJAX call is down below. How do I get the return object to enter my "done" function?
Also, what else am I doing wrong?
$("button").click(function(){
console.log("clicked");
var request = $.ajax({
type : "GET",
url : ***The problem is not here, I am hitting the controller***
dataType: "jsonp",
crossDomain: true,
success: done,
});
function done(obj, status, jqXHR){
alert("in success function");
console.log(obj);
$("li#pName").append("matthew");
};
});
Upvotes: 0
Views: 151
Reputation: 63587
Your code is a little hinky. Make sure you close the brackets properly too - I think that's what's getting you in trouble.
Here's the solution for using a anonymous function in the AJAX request:
$("button").click(function(){
console.log("clicked");
var request = $.ajax({
type : "GET",
url : ***The problem is not here, I am hitting the controller***
dataType: "jsonp",
crossDomain: true,
success: function (obj, status, jqXHR) {
alert("in success function");
console.log(obj);
$("li#pName").append("matthew");
}
});
});
And here's the solution for when you want to use a separate function.
function done(obj, status, jqXHR) {
alert("in success function");
console.log(obj);
$("li#pName").append("matthew");
}
$("button").click(function(){
console.log("clicked");
var request = $.ajax({
type : "GET",
url : ***The problem is not here, I am hitting the controller***
dataType: "jsonp",
crossDomain: true,
success: done
});
});
Upvotes: 2
Reputation: 42746
you are setting dataType
to jsonp
, but you are putting out straight json text, jsonp expects a function to be provided ie someFn({"name":"Matthew","id":0})
Since jquery automatically appends a random name for the callback function name if you do not provide one, you need to capture the callback
GET variable and echo out the json text wrapped by a function call named by the name in the callback
variable.
not familiar with spring but with php this would look something like
$fnName = $_GET["callback"];
echo $fnName."(".json_encode($someDataObj).")";
Change your backend to do something like that or change the dataType
to json
, so that it will parse straight json text.
Upvotes: 2