Grails Ajax callback not rendering/responding properly - json

I'm doing an ajax request to an own rest api and trying to print in an alert the message I get.
The point is I'm getting the following error: SyntaxError: Unexpected token :
The code that makes the call is:
$.ajax({
url:"${g.createLink(controller:'report',action:'show')}",
dataType: 'json',
data: {
data: jSon,
},
success: function(data) {
alert(data)
},
error: function(request, status, error) {
alert(error)
},
complete: function() {
}
});
The return value i'm printing in the controller is:
JSON: {"results":"SELECT cliente.edad FROM Cliente cliente,Local local WHERE Local.numero==3 GROUP BY Cliente.edad ORDER BY Cliente.edad undefined""}
And what I'm doing in the controller is:
println "JSON: " + java.net.URLDecoder.decode((String)apiResponse.json)
render java.net.URLDecoder.decode((String)apiResponse.json)
I have also tried with respond instead of render but same error

Try using render as JSON
def results = ['a':'AA','b':'BB']
render results as JSON

Related

ajax returning json data as undefined

when i run below code.
it makes error and alert "fail error:StntaxError: Unexpected token < in JSON at position 0 data:undefined"
what is the problem ??
$("#a").click(function () {
st_dt = $("#st_dt").val();
end_dt = $("#end_dt").val();
lot_cd = $("#lot_cd").val();
var obj = { st_dt: st_dt, end_dt: end_dt, lot_cd: lot_cd };
var json_1 = JSON.stringify(obj);
$.ajax({
type: "POST",
url: '{{ url_for("get_operid") }}',
data: json_1,
dataType: "JSON",
success: function (data) {
alert("Success\n" + data);
},
error: function (request, status, error, data) {
alert("fail\n" + "error:" + error + "\n data:" + data);
}
});
});
Looking at the code it looks like a Laravel API request using Blade Template or the Function url_for is in Flask... In either case
That means the response for the api request is HTML string instead of
a json response...
i.e. The API request is returning a login page or some HTML page...
To check the response you can open the Chrome Devtools in the Network tab check the response of the API...
what you can try is :
var obj = { st_dt: st_dt, end_dt: end_dt, lot_cd: lot_cd };
console.log(obj);
var json_1 = JSON.stringify(obj);
console.log(json_1);
Then See in browser console what is your object and if the JSON converting your object properly.
If that is ok , Your request should be done currectly. And try to see what are the data you getting as response with:
success: function (data) {
consoel.log('response below');
console.log(data);
}
You will find the error. I hope.

Can't get data from Json array via an ajax get request

I am having a hard time getting the correct field out of an object from an ajax get request. The ajax request is in a Django app and corresponds with the view. The line:
console.log(data);
displays all the data in the object. I am trying to output the username in console.log() but I am not able to get it done.
I tried many variations i.e. I used filter instead of get in the Django view section. I tried to for loop over the data and use [i] but so far nothing worked.
Hopefully someone has an idea on how to solve this issue. I attached the django view, the template view and the chrome dev tools console output.
The django section view:
def Data(request, user_id):
if request.is_ajax():
sidebar_data = serializers.serialize("json",
[User.objects.get(id=user_id)])
return HttpResponse(
JsonResponse({'sidebar_data': sidebar_data}),
content_type="application/json"
)
return HttpResponse("not a ajax request")
The template view:
$( ".test{{ user.user.id }}" ).click(function() {
$.ajax({
url : ‘xxx/‘,
dataType : 'json',
method : 'GET',
success: function(data)
{
// this works - outputs all data
console.log(data);
// this does not work
console.log(data.sidebar_data.fields[1].username);
},
failure: function(){
}
});
});
The output for the browser in chrome console:
Object {
sidebar_data: "[{"fields": {"username": “xxx”, "first_name": “xxx”}, "model": "auth.user", "pk": 989}]”}
If i use console.log(data.sidebar_data); i get the following output which is a step closer. But as soon as i try any combination with fields or username i get the undefined error.
[{"fields": {"username": “xx”, "first_name": “xxx”}, "model": "auth.user", "pk": 989}]
change views.py like this:
from django.core import serializers
def data(request):
if request.is_ajax():
user = User.objects.filter(id=1)
data = serializers.serialize('json', user)
return HttpResponse(data, content_type ="application/json")
return HttpResponse("not a ajax request")
and change template like this:
$( ".test{{ user.user.id }}" ).click(function() {
$.ajax({
url : ‘xxx/‘,
dataType : 'json',
method : 'GET',
success: function(data)
{
console.log(data[0].fields.username);
},
failure: function(){
}
});
});
Try data[1].fields[1] instead of data.sidebar_data.fields[1].username

how tosend unlimited json data from jquery ajax to mvc razor controller

I have to send unlimited JSON data from ajax J query to MVC razor controller.
The method is triggered once we send limited data. if i send more data the method is not triggered and Am getting 500 Internal error.
$.ajax({
url: '../Offline/Save',
data: JSON.stringify(Item),
data: "{'Id':" + Results.rows.item(m).Id + ",'Item':" + JSON.stringify(Item) + "}",
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data, status) {
alert(data);
}
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
}
});
[HttpPost]
[ValidateInput(false)]
public JsonResult SaveFinding(int Id, SyncItem Item)
{
Result result = new DB().Process(Id, Item);
return Json(result);
}
have you tried debugging ?
Is the method SaveFinding() itself not throwing the error ?
Or is it after the method is completed you are getting the error ?
Here are a few links that you should consider looking at
Can I set an unlimited length for maxJsonLength in web.config?
http://binoot.com/2008/10/14/using-json-some-observations/
http://support.microsoft.com/kb/981884
http://dotnetbyexample.blogspot.com/2007/11/expanding-lenght-of-json-data-returned.html

How does JSON determine a success from an error?

I'm new to JSON and have been using it with MVC3 ASP.NET but could somebody shed some light on how to return an error per a JSON result?
I have the following call from my View:
$.ajax({
type: "POST",
dataType: "json",
url: "EditJSON",
data: { FilmID: InputFilmID, Title: InputTitle, Description: InputDescription},
success: function (result) {
alert(result.Message + " updating film " + result.Title);
window.location = "../All";
},
error: function (error) {
alert('error');
}
});
Controller handles the request as a success. What would I pass back for a JSON error so that the error: function handled back at the View?
[AcceptVerbs("POST")]
public JsonResult EditJSON(BobsMoviesMVC2.Models.Film film)
{
filmRepository.Update(film);
return Json(new {Message = "Success", Title = film.Title });
// What would I return for an error here?
}
Thanks!
jQuery uses the HTTP response code to determine success or failure.
HTTP response codes >= 400 are considered errors. HTTP response codes >= 200 and < 400 are considered successes.
Return appropriate HTTP codes from your server-side code to get the behavior you're after.
Confirmed, in .NET you can put:
Response.StatusCode = (int)HttpStatusCode.InternalServerError,
or whatever error status code you wish, right before your JSON return statement. (Thank you Mariah).
Check out the 'error' option of the jquery ajax call to see what you can do with the resulting error on the client-side.
A header with a status code other than 2xx or 3xx, probably a 5xx or 4xx error code.

Send generic JSON data to MVC2 Controller

I have a javascript client that is going to send json-formatted data to a set of MVC2 controllers. The client will format the json, and the controller will have no prior knowledge of how to interpret the json into any model. So, I can't cast the Controller method parameter into a known model type, I just want to grab the generic json and pass it to a factory of some sort.
My ajax call:
function SendObjectAsJSONToServer(object,url,idForResponseHTML) {
// Make a call to the server to process the object
var jsonifiedObject = JSON.stringify(object);
$.ajax({
url: url // set by caller
, dataType: 'json'
, data: jsonifiedObject
, type: 'GET'
, error: function(data) { alert('error in sendObjectAsJSONToServer:' + data); }
, success: function(data) {
alert(data.message); // Note that data is already parsed into an object
}
});
}
My MVC Controller:
public ActionResult SaveForm(string obj)
{
// Ok, try saving the object
string rc = PassJSONToSomething(obj.ToString());
string message = "{\"message\":\""+rc+"\",\"foo\":\"bar\"}";
return new ContentResult { Content = message, ContentType = "application/json" };
}
The problem is that obj is always null. Can anyone tell me how I should structure the ajax call and the controller parameter so that I get my json to the server? I'm using MVC2. This may appear to be a duplicate of some SO questions, but in my case I do not know the Model that the json maps to, so I can't use a specific model type in the controller parameter type.
Thanks very much.
Have you tried something like that?
$.ajax({
url: url // set by caller
, dataType: 'json'
, data: {obj :jsonifiedObject}
, contentType: 'application/json; charset=utf-8'
, type: 'GET'
, error: function(data) { alert('error in sendObjectAsJSONToServer:' + data); }
, success: function(data) {
alert(data.message); // Note that data is already parsed into an object
}
});