Converting from json array to json object not working properly - javascript

I have created a rest service like this:
#GET
#Path("/getsummary")
#Produces("application/json")
public Response summary()
{
VoltDAOImpl voltDao = new VoltDAOImpl();
Map<String ,List<HashMap<String,String>>> returnList= voltDao.getOrderDetails("PEAKM" , "Hydra" ,
"" , voltDao.client,"notional" ,1000);
List<HashMap<String,String>> totalSlpSummaryList = returnList.get("total_slp_summary");
List<HashMap<String,String>> totalSlpSummaryBySideList = returnList.get("total_slp_summary_by_side");
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json1 = null;
String json2 = null;
String json3 = null;
try {
json1 = ow.writeValueAsString(totalSlpSummaryList);
json2 = ow.writeValueAsString(totalSlpSummaryBySideList);
json3="["+json1+","+json2+"]";
//json3 = json1 + "\n" + json2;
System.out.println(json1);
System.out.println(json2);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return Response.status(200).entity(json3).build();
}
And then I'm consuming this in a javascript like this:
var rootURL = "http://localhost:8181/RestServiceProject/rest/WebService/getsummary";
function findBySummary() {
console.log("inside loading grid");
var returnval1;
$.ajax({
type: 'GET',
url: rootURL,
dataType: "json",
async: false,
success: function(json3){
returnval1 = json3;
console.log(returnval1);
}
});
return returnval1;
}
console.log(returnval1);
return the following result:
returnval1
later I'm calling findBySummary(); and doing the following:
var json3 = findBySummary();
var json4 = json3[0];
console.log("json4");
console.log(json4);
var json_temp = JSON.stringify(json4);
console.log("json_temp")
console.log(json_temp);
var json_temp1 = json_temp[0];
console.log("json temp1");
console.log(json_temp1);
Following is the log output for this:
log output
I am trying to convert json_temp, which is, :
[{"total_exec_qty":"286595","total_notional":"21820771.72","total_wt_arr_last_slp":"2.4364","total_num_ords":"1630","total_wt_ivwap_slp":"6.0969","total_wt_arr_slp":"1.7889","total_ord_qty":"576991"}]
to this(json_temp1):
{"total_exec_qty":"286595","total_notional":"21820771.72","total_wt_arr_last_slp":"2.4364","total_num_ords":"1630","total_wt_ivwap_slp":"6.0969","total_wt_arr_slp":"1.7889","total_ord_qty":"576991"}
But why am I getting [ only for json_temp1??

Note that JSON.stringify(json4) returns a string.
So, the code json_temp[0] will return the first element in this string.
What you want is:
var json_temp1 = json4[0];
and not:
var json_temp1 = json_temp[0];
The code below is wrong for your need:
var json_temp = JSON.stringify(json4);
console.log("json_temp")
console.log(json_temp);
var json_temp1 = json_temp[0];

Related

JavaScript - AJAX / 'Data' is empty / asp.net MVC

I found some similar questions but none of them resolve my problem.
The problem I have is that my data from my AJAX-call is empty but my controller return exactly I want him to return.
I tried to add a contentType, but neither contentType nor ContentType worked for me.
What am I doing wrong?
JavaScript:
function AddFunction() {
var ergebnis = "";
var zahl1 = $("#txt_1").val();
var zahl2 = $("#txt_2").val();
$.ajax({
async: false,
cache: false,
type: 'POST',
url: '/Calc/Add',
dataType: 'JSON',
data: {
'val_1': zahl1,
'val_2': zahl2
},
success: function (data) {
ergebnis = data.result;
alert(ergebnis);
},
error: function () {
alert("Fehler");
}
});
}
Controller:
public ActionResult Add(string val_1, string val_2)
{
string sUri = "http://192.168.111.173:35145/temppath/GVCalc/1.0/add";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(sUri);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"field_1\":\"" + val_1 + "\"," +
"\"field_2\":\"" + val_2 + "\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
var result = DeserializeFromStream(httpResponse.GetResponseStream());
return Json(result);
}
Controller result:
{{
"result": 3
}}
Ajax data:
kinda empty / no result at all
Edit:
DeserializeFromStream Method:
public static object DeserializeFromStream(Stream stream)
{
var serializer = new JsonSerializer();
using (var sr = new StreamReader(stream))
using (var jsonTextReader = new JsonTextReader(sr))
{
return serializer.Deserialize(jsonTextReader);
}
}
I solved my problem by sending a string and parse it in JavaScript. This worked fine for me :)
C#:
return Json(result.ToString());
JavaScript:
var ergebnis_json = JSON.parse(data)
ergebnis = ergebnis_json.result;
$("#ergebnis").val(ergebnis);
Thanks everyone for their help :)

Array value becomes null while passing from Ajax

I am making an ajax call in my javascript submit function. In this ajax call, I am passing an array(globalSelection) as data to the servlet. This array consists elements of function textSelection which is also pasted below.
globalSelection =[];
function submit() {
console.log("globalSelection start")
console.log(globalSelection)
console.log("globalSelection end")
$.ajax({
async : false,
type : "POST",
url : 'http://example.com:8080/myApp/DataServlet',
data: {globalSelection:globalSelection},
success : function(data) {
alert(data)
},
error : function(data, status, er) {
alert("error: " + data + " status: " + status + " er:" + er);
}
});
}
function textSelection(range, anchorNode, focusNode) {
this.range = range;
this.type = 3;
this.rCollection = [];
this.textContent = encodeURI(range.toString());
this.anchorNode = anchorNode;
this.focusNode = focusNode;
this.selectionId = getRandom();
this.yPOS = getYPOS();
this.getTagName = function(range) {
var el = range.startContainer.parentNode;
return el;
}
this.getTagIndex = function(el) {
var index = $(el.tagName).index(el);
return index;
}
this.simpleText = function(node, range) {
if (!node)
var entry = this.createEntry(this.anchorNode, this.range);
else
var entry = this.createEntry(node, range);
this.rCollection.push(entry);
this.highlight(this.rCollection[0].range);
this.crossIndexCalc();
textSelection._t_list.push(this);
pushto_G_FactualEntry(this);
}
this.compositeText = function() {
this.findSelectionDirection();
var flag = this.splitRanges(this.anchorNode, this.focusNode,
this.range.startOffset, this.range.endOffset);
if (flag == 0) {
for (j in this.rCollection) {
this.highlight(this.rCollection[j].range);
}
}
this.crossIndexCalc();
textSelection._t_list.push(this);
pushto_G_FactualEntry(this);
}
}
I am ading the screen of my browser console below, which prints the globalSelection(array).
In my servlet I am getting this array as follows
String[] arrays = request.getParameterValues("globalSelection[]");
System.out.println(arrays);
Here I am getting null value for arrays.
If I put globalSelection as follows in submit function for simple test to servlet, I am able to get the arrays.
var globalSelection = ["lynk_url", "jsonBody", "lynk_dummy1", "lynk_dummy2", "lynk_name", "lynk_desc", "lynk_flag"];
Why my actual globalSelection is shows null in servlet, what I am doing wrong here.
Try with :
String[] arrays = request.getParameterValues("globalSelection");
System.out.println(arrays);
Because the parameter submitted with name "globalSelection" only not "[]" symbol.
I see your problem and I have a simple solution.
I recommend in that case that you convert the array as a string in JS:
JSON.stringify(globalSelection)
and then reconstructing the object on the backend using some sort of library for JSON conversion like: https://code.google.com/archive/p/json-simple/
You could then do something like this:
JSONArray globalSelection = (JSONArray) new JSONParser().parse(request.getParameter("globalSelection"));
Iterator i = globalSelection.iterator();
while (i.hasNext()) {
JSONObject selection = (JSONObject) i.next();
String type = (String)selection.get("type");
System.out.println(type);
}
This will parse your array and print the selection type. Try it, hope it helps.

error in serialization javascript from json to text

i have an error in serialisation i need someone to fix it and that 's code controller
public string Getrowselec(string id)
{
GestionprojetEntities ddb = new GestionprojetEntities();
Ressourcehumaine _ressource = new Ressourcehumaine();
_ressource = ddb.Ressourcehumaine.Find(Convert.ToInt32(id));
int id_ressource = int.Parse(id);
var query = (from u in ddb.Ressourcehumaine
where (u.Id == id_ressource)
select new
{
id = u.Id,
nom = u.Nom,
prixrevient = u.Prixrevient,
prixvente = u.Prixvente,
coutdirect = u.Coutdirect,
});
string javascriptJson = JsonConvert.SerializeObject(query);
return javascriptJson;
and this is my code in twig code javascript:
function Getrows(s, e) {
debugger;
var id = e.visibleIndex;
var key = s.GetRowKey(e.visibleIndex);
idProduit = key;
$.ajax({
url: "/Projet/Getrowsselec?id=" + key,
type: "POST",
dataType: "text",
success: function (response) {
debugger;
$("#nomclient_I").val(jsonObject[0]['nom']);
$("#codeclient_I").val(jsonObject[0]['id']);
}
})
}
can someone help me fix this issue the error in serialisation i think some error in serialisation
from json to text
i think that you need to add this to your response ajax try it and tell me if it work or not
success: function (response) {
debugger;
var jsonObject = JSON.parse(response);
$("#nomclient_I").val(jsonObject[0]['nom']);
$("#codeclient_I").val(jsonObject[0]['id']);
}

Javascript list passing to c#

I have a Asp.net MVC program in which i want to get a list from the View using Javascript and pass that list to the controller. I want to the variables in the list to be string type except for one to be int32.
The problem is the list is either empty or does not pass.
I tried to use stringify but it doesn't fill the requirments.
Here is the code from the javascript part:
$('#AddColumn').click(function () {
var nodeURL = document.getElementById("IDHolder").innerHTML;
var nodeConfig= nodeURL+".CONFIG";
var nodeAdd=nodeURL+".CONFIG.AddColumn";
var nodeName = $("#ColumnName").val();
var nodeType = $("#ColumnType").data("kendoComboBox").value();
var ListNodedet = [nodeName, nodeType];
var Listmet = [nodeConfig, nodeAdd];
var ListNodeDetails = JSON.stringify(ListNodedet);
var ListMethod = JSON.stringify(Listmet);
var select = 1;
var url = "/Configuration/CallMethod";
$.get(url, { ListNodeDetails:ListNodeDetails, ListMethod:ListMethod }, function (data) {
$("#Data2").html(data);
});
})
The C# code for the controller were it calls another method in models:
public bool CallMethod(List<Variant> ListNodeDetails, List <string> ListMethod)
{
var AddMethod = RxMUaClient.CallMethod(ListNodeDetails, ListMethod, "127.0.0.1:48030");
return AddMethod;
}
The Model:
public static bool CallMethod(List<Variant> ListNodeDetails, List<string> ListMethod, string iPAddress)
{
var serverInstance = GetServerInstance(iPAddress);
if (serverInstance == null)
return false;
return serverInstance.CallMethod(ListNodeDetails, ListMethod);
}
The service model
public bool CallMethod(List<Variant> ListNodeDetails, List<string> ListMethod)
{
try
{
if (_mSession == null)
{
return false;
}
NodeId objectID = NodeId.Parse(ListMethod[0]);
NodeId Methodtype = NodeId.Parse(ListMethod[1]); ;
List<Variant> inputArguments = ListNodeDetails;
List<StatusCode> inputArgumentErrors = null;
List<Variant> outputArguments = null;
StatusCode error = _mSession.Call(
objectID,
Methodtype,
inputArguments,
new RequestSettings() { OperationTimeout = 10000 },
out inputArgumentErrors,
out outputArguments);
if (StatusCode.IsBad(error))
{
Console.Write("Server returned an error while calling method: " + error.ToString());
return false;
}
return true;
}
catch (Exception exception)
{
Console.WriteLine(exception.ToString());
return false;
}
}
At the end it calls some functions using OPC UA to add data.
I have changed it to be ajax function and it works well but only with one list form the lists passed to the method!
I dont know if this is because i read values from kendo box and text box, and they are different types but i tried to stringfy it and it still does not work. On the console both lists are out as strings. So still got a problem with passing the first List "ListNodeDetails"!
$('#AddColumn').click(function () {
var nodeURL = document.getElementById("IDHolder").innerHTML;
var nodeConfig= nodeURL+".CONFIG";
var nodeAdd=nodeURL+".CONFIG.AddColumn";
var nodeName = $("#ColumnName").val().toString();
var nodeType = $("#ColumnType").data("kendoComboBox").value().toString();
var ListNodedet = [nodeName, nodeType];
var Listmet = [nodeConfig, nodeAdd];
var params = {
ListNodeDetails: ListNodedet,
ListMethod: Listmet
};
var url = "/Configuration/CallMethod";
console.log(params); // added sanity check to make sure data is correctly passed
var temp = {
url: "/Configuration/CallMethod",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(params),
success: function (params) {
window.location.replace(params.redirect);
}
};
$.ajax(temp);
})

How to call server side function from json?

this is my code
<script type="text/JavaScript">
var myarray = new array();
function getsvg1() {
$.ajax({
alert("hello");
type: "post",
url: "WebForm1.aspx/getsvg1",
alert("abc");
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var cars = response.d;
alert(cars);
alert("hi");
},
failure: function (msg) {
$('#output').text(msg);
}
});
}
</SCRIPT>
webservices
[System.Web.Services.WebMethod]
public static ArrayList getsvg1()
{
XDocument doc = XDocument.Load(System.Web.HttpContext.Current.Server.MapPath("~/NewFolder1/10000.svg"));
//XDocument doc = XDocument.Load(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/Orders/100001_PRO/2/svg0.svg"));
//XNamespace ns1 = "http://www.w3.org/2000/svg";
//Namespace of a root element can also be retrieved like this:
//XNamespace ns1 = doc.Root.GetDefaultNamespace();
//var g = doc.Descendants(ns1 + "image").FirstOrDefault();
// XDocument doc = XDocument.Load(Server.MapPath("~/excelfiles/svg0.svg"));
XNamespace ns1 = "http://www.w3.org/2000/svg";
//Namespace of a root element can also be retrieved like this:
//XNamespace ns1 = doc.Root.GetDefaultNamespace();
var retrieveimage = doc.Descendants(ns1 + "image").FirstOrDefault();
var retrivetext = doc.Descendants(ns1 + "g").FirstOrDefault();
ArrayList arlelem = new ArrayList();
foreach (XElement element in doc.Descendants(ns1 + "g"))
{
//string[] parts = element.Split(',');
Console.WriteLine(element);
arlelem.Add(element);
}
// var retrivetext1 = doc.Descendants(ns1 + "text").SelectMany(i => i.ElementExtensions.Select(e => e.GetObject<XElement>().Attribute("url").Value)).ToArray();
//var retrivetext = doc.Descendants(ns1 + "text").All();
string v = arlelem[1].ToString();
string values = retrieveimage.ToString();
string values1 = retrivetext.ToString();
char[] delimiterChars1 = { ' ', ',', '"', '\\', '\t', '=' };
//string text = "one\ttwo three:four,five six seven";
//System.Console.WriteLine("Original text: '{0}'", text);
string[] words = values.Split(delimiterChars1);
string[] words2 = values1.Split(delimiterChars1);
string[] newword = v.Split(delimiterChars1);
//Session["newimgwidth"] = words[15];
return arlelem;
}
alert is not coming for cars values and breakpoint not going for success and failure. in this example i m calling server side function from
json that function result
To start with your ajax request is filled with syntax errors.
The $.ajax({ }) block cannot have a alert("hello"); inside it
Remove alert("abc"); too
use console.log() instead of alerts in your success method, this is not one of the error but a suggestion/advice.
What is your method returning in case of error ? In your ajax error method it seems to be expecting a string value.
Why are you using type: "post" when you are not posting any data to your method. Use a 'get' instead.
To debug your server side code, try opening the WebForm1.aspx/getsvg1 url in your browser window and see if you get the expected response. If all is well next try sending an ajax request using a client like postman rest client to check the response again.
Hope this helps.
you can use jQuery for this:
$.getJSON( "http://server.com/webservice", function( data ) {
console.log(JSON.stringify(data));
}
See more details at: http://api.jquery.com/jquery.getJSON/
{key,value } it allow json data.means already availble options or new define json value only. you can enter,if you try to alert("hello") it doest allow.so it stopped.so,try without alert message use inside brackets {}.

Categories