Extract JSON returned from Servlet in JavaScript - javascript

Basically I am trying to extract JSON returned from servlet in JavaScript. I have tested my servlet class already and it did returned some JSON so I guess I no need to post the code for that class. Here is my returned JSON format:
[{"mrtpopAmt":"7000","mrtpopX":"17854.99820","mrtpopY":"35056.35003"},{"mrtpopAmt":"6300","mrtpopX":"29798.58427","mrtpopY":"37036.56434"}]
And in my JavaScript, I am trying to extract mrtpopAmt, mrtpopX and mrtpopY as one object. Then I will add all object into an array:
function getAllMRTPop(time){
var jsonArray;
var Data = JSON.stringify({ time: time });
$.ajax({
url: "/TrackNYP/TrackNYPServlet?action=GetAllMrtPop&time="+ Data + "",
type: "GET",
data: Data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var parsed = JSON.parse(data.d);
console.log(data.d);
$.each(parsed, function (i, jsondata) {
var jsonObject;
jsonObject.put("mrtpopAmt", jsondata.mrtpopAmt);
jsonObject.put("mrtstationX", jsondata.mrtstationX);
jsonObject.put("mrtstationY", jsondata.mrtstationY);
alert(jsonObject);
jsonArray.push(jsonObject);
});;
},
error: function (request, state, errors) {
}
});
}
However, I am getting error message like Unexpected token: u at this line:
var parsed = JSON.parse(data.d);
My URL for the servlet contains two parameter, one is action and the other one is time:
http://localhost:8080/TrackNYP/TrackNYPServlet?action=GetAllMrtPop&time=8:00
So I wonder am I passing the parameter correctly by passing it in url and as well as data from the code above?
I wonder which part went wrong? Thanks in advance.
EDIT
So I have updated my JavaScript part to this:
function getAllMRTPop(time){
var jsonArray = [];
$.ajax({
url: "/TrackNYP/TrackNYPServlet?action=GetAllMrtPop&time=8:00",
type: "GET",
data: time,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
console.log(data);
//var parsed = JSON.parse(data.d);
$.each(data, function (i, jsondata) {
var jsonObject;
console.log(mrtpopAmt);
jsonObject.put("mrtpopAmt", jsondata.mrtpopAmt);
jsonObject.put("mrtstationX", jsondata.mrtstationX);
jsonObject.put("mrtstationY", jsondata.mrtstationY);
jsonArray.push(jsonObject);
});;
},
error: function (request, state, errors) {
}
});
}
I tried to print out the mrtpopAmt and it did returned something. But there is an error message:
Cannot call method 'put' of undefined
Any ideas?

By specifying dataType: "json", jQuery already knows you will be getting a JSON response, there is no no need to do var parsed = JSON.parse(data.d)
Just do:
var parsed = data.d
Edit:
function getAllMRTPop(time){
var jsonArray = [];
$.ajax({
url: "/TrackNYP/TrackNYPServlet?action=GetAllMrtPop&time=8:00",
type: "GET",
data: time,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
console.log(data);
$.each(data, function (i, jsondata) {
var jsonObject = {};
jsonObject.mrtpopAmt = jsondata.mrtpopAmt;
jsonObject.mrtstationX = jsondata.mrtstationX;
jsonObject.mrtstationY = jsondata.mrtstationY;
jsonArray.push(jsonObject);
});;
},
error: function (request, state, errors) {
}
});
}

I think what is happening is that data.d is undefined, so you are getting the odd message about unexpected u.
Try this instead:
var parsed = JSON.parse(data);
Edit And I think you are probably not formatting your request right:
var Data = JSON.stringify({ time: time });
$.ajax({
url: "/TrackNYP/TrackNYPServlet?action=GetAllMrtPop&time="+ Data + "",
Seems to me that would make the final bit: &time={"time":"time"}, so you probably want to look at how you construct Data. Maybe just pass time directly?
url: "/TrackNYP/TrackNYPServlet?action=GetAllMrtPop&time="+ time + "",

Related

How to pass string array to controller using ajax?

// something defined deleteArr and pass values to it
var postData = { deleteArr: deleteArr };
if(deleteArr.length > 0)
{
$.ajax({
url: "#Url.Action("Delete", "ASZ01")",
type: "POST",
data: postData,
contentType: "application/json; charset=utf-8",
success: function (response) {
alert("success.");
},
error: function (response) {
alert(deleteArr[0]);
}
});
deleteArr.length = 0;
}
The above code is javascript.
Until $.ajax begin I can confirm that values in array is correct in immediate window,but when it comes to error: I got "undefined".
And the following is my function in controller
public void Delete(List<string> deleteArr)
{
service.Delete(deleteArr);
}
The second question is that I set breakpoint on that function but it can't stop.
I think maybe my ajax form is wrong?
Stringify to JSON, add the dataType: 'json' and then pass and also correct your ""
var postData = JSON.stringify({ deleteArr: deleteArr });
if(deleteArr.length > 0)
{
$.ajax({
url: #Url.Action("Delete", "ASZ01"),
type: "POST",
data: postData,
dataType: 'json'
contentType: "application/json; charset=utf-8",
success: function (response) {
alert("success.");
},
error: function (response) {
alert(deleteArr[0]);
}
});
deleteArr.length = 0;
}
Small change to your postData
var postData = { deleteArr: JSON.stringify(deleteArr) };
Idea is to convert your array data into string format ie:JSON and posting to the server, The default Model binder of MVC framework will handle the part to convert them into List<string> for you

Web service receiving null with jQuery post JSON

The web service on http://localhost:57501/api/addDatabase has the following code.
[System.Web.Mvc.HttpPost]
public ActionResult Post(addDatabase pNuevaConeccion)
{
pNuevaConeccion.insertarMetaData();
return null;
}
The Ajax function is on a javascript that creates the JSON from the give values on http://localhost:1161/CreateServer.
$(document).ready(function ()
{
$("#createServer").click(function (e) {
e.preventDefault(); //Prevent the normal submission action
var frm = $("#CreateServerID");
var dataa = JSON.stringify(frm.serializeJSON());
console.log(dataa);
$.ajax({
type: 'POST',
url: 'http://localhost:57501/api/addDatabase/',
contentType: 'application/json; charset=utf-8',
crossDomain: true,
//ContentLength: dataa.length,
data: dataa,
datatype: 'json',
error: function (response)
{
alert(response.responseText);
},
success: function (response)
{
alert(response);
if (response == "Database successfully connected") {
var pagina = "/CreateServer"
location.href = pagina
}
}
});
});
});
When I run this code an alert pops up saying "undefined" but if I delete the contentType the alert doesn't show up. The problem is that the variables that the function Post (from the web service) receives are NULL even though I know that the JSON named dataa is not NULL since I did a console.log.
I have seen various examples and pretty much all of them say that I should use a relative URL but the problem is that since there are 2 different domains and when I tried it, it couldn't find the URL since it's not in the same localhost.
Web service should return a JSON format instead of null. like below example.
public JsonResult Post()
{
string output = pNuevaConeccion.insertarMetaData();
return Json(output, JsonRequestBehavior.AllowGet);
}
try to use this code for calling the web method
$.ajax({
method: "POST",
contentType: "application/json; charset=utf-8",
data: dataa,
url: 'http://localhost:57501/api/addDatabase/',
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(error);
}
});
its my old code.(ensure action parameter variable name and post variable name are same)
$('#ConnectionAddres_ZonesId').change(function () {
var optionSelected = $(this).find("option:selected");
var id = { id: optionSelected.val() };
$.ajax({
type: "POST",
url: '#Url.Action("GetParetArea", "Customers")',
contentType: "application/json;charset=utf-8",
data: JSON.stringify(id),
dataType: "json",
success: function (data) {
$('#ConnectionAddres_ParentAreaId').empty().append('<option value="">Select parent area</option>');
$.each(data, function (index, value) {
$('#ConnectionAddres_ParentAreaId').append($('<option />', {
value: value.Id,
text: value.Area
}));
});
},
});
});
public ActionResult GetParetArea(int id)
{
var parents="";
return Json(parents, JsonRequestBehavior.AllowGet);
}

Getting the value of a returned string from Ajax JQuery

I have a web service which adds an item to the database after being called using JQuery Ajax. The web service returns a string, and I can't manage to pick up only the string part returned. Instead I receive {"d":"The message I want to display"} using alert(data);.
I also tried alert(Object.keys(JSON.parse(data))[0]); which returns d and alert(Object.keys(JSON.parse(data))[1]); or alert(data.d); returns Undefined.Here's what my code looks like
function AddAjaxJQuery() {
var isbn = $('#<%= txtIsbn.ClientID %>').val();
var pdata = { "book": { "Isbn": isbn} };
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/BookWebService.asmx/InsertBook",
data: JSON.stringify(pdata),
dataType: 'text',
async: true,
success: function (data, textStatus) {
alert(data);
},
error: function (error) {
alert(data);
}
});
}
If your data is a string, then you should parse it to JSON first:
var dataInJson = JSON.parse(data);
alert(dataInJson.d)
You have to access property d of data (response) so Replace success callback with
success: function (data, textStatus) {
alert(data.d);
},

jQuery: Calling a function from AJAX request

I'm trying to call a function when I get success from my ajax call, but it's not working. This is what I've tryed so far.
function dtMRPReasonCode(dt) {
var data = null;
jQuery.ajax({
type: "POST",
data: {},
url: "Index.aspx/getMRPReasonCodeReport",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
if (msg.d) {
console.log(dt);
console.log(msg.d);
buildTableBody(dt, msg.d);
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert("Error: dtMRPReasonCode");
}
});
return false;
}
function buildTableBody(dt, obj) {
dt.fnClearTable();
data = [];
$(obj).each(function(index, value) {
element = [];
element.push(value.Metric);
element.push(value.Region);
element.push(value.Plant);
element.push(value.Customer);
element.push(value.IMAC);
element.push(value.NotFilled);
element.push(value.Filled);
element.push(value.Total);
data.push(element);
});
dt.fnAddData(data);
}
Thanks in advance!
Edit #1
I used console.log in order to show you what I got from dt and msg.d (Image)
Edit #2
If I paste the commands from buildTableBody function in the success: handler instead of calling buildTableBody function in the success: handler it actually works:
function dtMRPReasonCode(dt) {
var data = null;
jQuery.ajax({
type: "POST",
data: {},
url: "Index.aspx/getMRPReasonCodeReport",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
dt.fnClearTable();
data = [];
$(msg.d).each(function(index, value) {
element = [];
element.push(value.Metric);
element.push(value.Region);
element.push(value.Plant);
element.push(value.Customer);
element.push(value.IMAC);
element.push(value.NotFilled);
element.push(value.Filled);
element.push(value.Total);
data.push(element);
});
dt.fnAddData(data);
},
error: function(xhr, ajaxOptions, thrownError) {
alert("Error: dtMRPReasonCode");
}
});
return false;
}
But it makes no sense to me, since this actually should work in both ways.
Pretty sure you have a typo on your function call
buildTableBody(td, msg.d);
should be
buildTableBody(dt, msg.d);
Also what is the return type from Index.aspx/getMRPReasonCodeReport? If it is string, you've got to unescape the string before you can treat it as JSON.
Try removing contentType : "application/json utf-8" from your AJAX call. That is the type of the data sent to the server. It is likely that you want the default content type.
Unless your server-side resource was configured to accept json it likely accepts application/x-www-form-urlencoded
http://api.jquery.com/jQuery.ajax/

JavaScript - Building JSON object

I'm trying to understand how to build a JSON object in JavaScript. This JSON object will get passed to a JQuery ajax call. Currently, I'm hard-coding my JSON and making my JQuery call as shown here:
$.ajax({
url: "/services/myService.svc/PostComment",
type: "POST",
contentType: "application/json; charset=utf-8",
data: '{"comments":"test","priority":"1"}',
dataType: "json",
success: function (res) {
alert("Thank you!");
},
error: function (req, msg, obj) {
alert("There was an error");
}
});
This approach works. But, I need to dynamically build my JSON and pass it onto the JQuery call. However, I cannot figure out how to dynamically build the JSON object. Currently, I'm trying the following without any luck:
var comments = $("#commentText").val();
var priority = $("#priority").val();
var json = { "comments":comments,"priority":priority };
$.ajax({
url: "/services/myService.svc/PostComment",
type: "POST",
contentType: "application/json; charset=utf-8",
data: json,
dataType: "json",
success: function (res) {
alert("Thank you!");
},
error: function (req, msg, obj) {
alert("There was an error");
}
});
Can someone please tell me what I am doing wrong? I noticed that with the second version, my service is not even getting reached.
Thank you
You may want to look at the JSON JavaScript library. It has a stringify() function which I think will do exactly what you need.
Your code:
var comments = $("#commentText").val();
var priority = $("#priority").val();
var json = { "comments":comments,"priority":priority };
Take out the quotes ( line 3 ):
var comments = $("#commentText").val();
var priority = $("#priority").val();
var json = { comments: comments, priority: priority };
Remove the quotes
data: '{"comments":"test","priority":"1"}',
becomes
data: {"comments":"test","priority":"1"},
JSONs are objects not strings.
This should work
var json = { comments: "comments",priority: "priority" };
this works for me.
var json = "{ 'comments': '" + *comments* +"','priority:' '" + *priority* +"' }";
italics are the variables.

Categories

Resources