Why can I not extract the data from this basic JSON Example - json

This is my Java script
function displayCustomerData( p_customername )
{
$.ajax({
url: 'myservlet',
type: 'GET',
data: { requesttype : "getcustomerdata" ,
customername : p_customername } ,
contentType: 'application/json; charset=utf-8',
success: function ( data )
{
$("#usernametxt").val( data.customer);
},
error: function () {
alert("Error loading customer data");
}
});
on the server side I generate the JSON using the Gson library
Gson gson = new Gson();
return gson.toJson( customerData );
customerData is a simple POJO with two String fields
I have a breakpoint at the Success response from the server
This is what the "data" variable contains in my debugger when I try to get the data from it
data "{"customer":"cuatomer A","userName":"user A"}"
but on my browser console when I do "data.customer" it tells me that customer is undefined ?
This indicates that there is something wrong with the JSON data but I don't see anything wrong and I can't stare at it any longer... anyone see anything?
I have tried it on Chrome and Firefox incase it was a browser issue, same problem on both.

you can parse the Data like using JSON.parse(data) and try for data.customer u can get .the result ....
function displayCustomerData( p_customername )
{
$.ajax({
url: 'myservlet',
type: 'GET',
data: { requesttype : "getcustomerdata" ,
customername : p_customername } ,
contentType: 'application/json; charset=utf-8',
success: function ( data )
{
var data1 = JSON.parse(data);
$("#usernametxt").val( data1.customer);
},
error: function () {
alert("Error loading customer data");
}
});

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.

Post list of string null on web api controller

In my web api project, I got a controller named ContactController and a method named Synchro in it which waits for a list of string as below:
[HttpPost]
[Route("api/Contact/Synchro")]
public IHttpActionResult Synchro([FromBody]List<string> listNumTel)
{
List<Profil> listContact = new List<Profil>();
if (listNumTel.Count() > 0)
{
try
{
listContact = Librairie.Contacts.getContactSync(listNumTel);
return Ok(listContact);
}
catch(Exception e) {
return InternalServerError(e);
}
}
else
{
return BadRequest();
}
}
To test that method, I've created the ajax called below:
$("#btn_synchro").click(function () {
$.ajax({
url: '../api/Contact/Synchro',
type: 'POST',
data: {
"listNumTel": [
"+33640512999",
"+33640522997",
"+33640182998",
"+33640742996"]
},
dataType: 'json',
success: function (data) {
alert('Synchro réussi: ' + data);
},
error: function (request, error) {
alert("Erreur lors de la synchro");
}
})
});
When I test on debug mode, the call works fine but the method get a null list. I checked if the json is valid and it is. Does Somebody sees what could be wrong ? Thanks in advance !
Thanks for the answers, but I've just found out the solution. It was all about JSON sent. To send a list of string by an ajax call for example, the JSON should looks like below the variable listNumero
("#btn_synchro").click(function () {
var listNumero =
[ '+33640532999',
'+33640532997',
'+33640532998',
'+33640532996'];
$.ajax({
url: '../api/Contact/Synchro',
type: 'POST',
data: JSON.stringify(listNumero),
contentType: "application/json",
dataType: 'json',
success: function (data) {
alert('Synchro réussi: ' + data);
},
error: function (request, error) {
alert("Erreur lors de la synchro");
}
})
});
You can compare to my post, the JSON is different. Now my web api controller can get the values from the list.

JSON passed to controller has no value

I am unable to get my JSON to my controller, and I can't figure out why the value I get in javascript isn't being passed to the controller. Here is my ajax post in my javascript:
this.save = function () {
var data = ko.toJSON(this.Routines);
$.ajax({
type: 'POST',
url: "CreateJson",
data: data,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
if (!result.success)
alert("test")
else { }
}
})
}
now data contains
[{"routine_name":"new routine","duration":"20","rest":"10","rounds":1}]
which is what I want, but the controller shows nothing. Here is my controller
[HttpPost]
public JsonResult CreateJson(t_routine routine, string data)
{
var message = "success";
return Json(message);
}
As I understand it, MVC 3+ automatically receives JSON without any need for parameters like my string data, I just threw it in there to try and figure out if I'm getting anything at all. data is null and routine shows 0's and null for values. What am I missing?
If t_routine represents the server side type for
[{"routine_name":"new routine","duration":"20","rest":"10","rounds":1}]
Then it might be enough to call JSON.stringify on the ko.toJSON result like this
this.save = function () {
var data = JSON.stringify(ko.toJSON(this.Routines));
$.ajax({
type: 'POST',
url: "CreateJson",
data: data,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
if (!result.success)
alert("test")
else { }
}
})
}
the data parameter on your controller action is not needed then and you most likely need to change the t_routine parameter to t_routine[]

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

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