I'm trying to convert an array of Hazards(class that i created) to JSON,
this is my code:
$.ajax({
async: true,
url: web + "/GetHazards",
method: "POST",
contentType: "application/json",
success: function (data) {
var res = data.d;
var i;
alert(res[0]);
the returned data is like this :
"[{\"Hazard_ID\":3014,\"Hazard_Lat\":32.2615929,\"Hazard_Long\":35.01423},{\"Hazard_ID\":3013,\"Hazard_Lat\":32.3426857,\"Hazard_Long\":34.9103165},{\"Hazard_ID\":3012,\"Hazard_Lat\":32.3426857
My server side code returns the correct values that i need, but the problem is when i alert the res[i] it behave like res is a string and alerts me "["
what i need to get is
{\"Hazard_ID":3014,\"Hazard_Lat\":32.2615929,\"Hazard_Long\":35.01423}
i dont know if it mind this is my server-side code by the way:
{
List<Returned_Hazard> rh = new List<Returned_Hazard>();
JavaScriptSerializer json = new JavaScriptSerializer();
.
.
.
while (reader.Read())
{
Returned_Hazard RH = new Returned_Hazard(
int.Parse(reader[0].ToString()),
float.Parse(reader[1].ToString()),
float.Parse(reader[2].ToString())
);
rh.Add(RH);
}
command.Connection.Close();
return json.Serialize(rh);
}
You need to parse the JSON, using JSON.parse:
var data = { d: "[{\"Hazard_ID\":3014,\"Hazard_Lat\":32.2615929,\"Hazard_Long\":35.01423},{\"Hazard_ID\":3013,\"Hazard_Lat\":32.3426857,\"Hazard_Long\":34.9103165}]"
};
var res = JSON.parse(data.d);
console.log(res[0].Hazard_ID); //3014
Related
I have a JSON data loaded from database using AJAX, it has name and value pair after serializing using JavaScriptSerializer, but I need to use it without the names, only the values is needed, how can I serialize the same data without the names
AJAX CALL
$.ajax({
url: 'RhemaServices.asmx/GetMapData',
type: 'POST',
dataType: 'json',
contentType: "application/json; charset-utf-8",
success: function (data) {
},
error: function (err) {
console.log(err)
},
complete: function () {
}
});
JSON data returned
[{"Code":"af","Total":16.63},{"Code":"al","Total":11.58},{"Code":"ve","Total":285.21},{"Code":"vn","Total":101.99}]
I need to re-serialize this data to get the below maybe looping through the data to read only the values
[{"af":"16.63","al":"11.58","ve":"285.21","vn":"101.99"}]
This is what I am trying to do with the AJAX JSON data, but its not working
var datas = [];
data.map(function (item) {
var newdata = item.Code + ":" + item.Total;
datas.push({ newdata });
})
Since your requested data is an object, I suggest you use forEach instead of map and create your properties as such:
let data = [{"Code":"af","Total":16.63},{"Code":"al","Total":11.58},{"Code":"ve","Total":285.21},{"Code":"vn","Total":101.99}];
var datas = {};
data.forEach(item => datas[item.Code] = item.Total);
console.log(datas);
// {"af":16.63,"al":11.58,"ve":285.21,"vn":101.99}
Is data coming all together as a single string? Then it's as simple as
var datas;
...
success: function (data) {
datas = JSON.parse(data);
}
Not sure what you mean by trim off the name ,only values - but you can do with the JavaScript object whatever you want
I am having trouble in sending a JSON array in an AJAX call. Following is my Code
var company_name = $('input#company_name').val();
var company_localname = $('input#company_localname').val();
var companytype = $('#companytype').val();
if (companytype == 'retailer') {
var bank_name = $('input#bank_name').val();
var account_title = $('input#account_title').val();
var business_nature = $('input#business_nature').val();
var gross_sales = $('input#gross_sales').val();
}
After getting all the values I am storing the data in Json like the following
var jsonArray = [];
jsonArray["company_name"] = company_name;
jsonArray["company_localname "] = company_localname;
if (companytype == 'retailer') {
jsonArray["bank_name"] = bank_name;
jsonArray["account_title"] = account_title;
jsonArray["business_nature"] = business_nature;
jsonArray["gross_sales"] = gross_sales;
}
Now for sending the jsonArray in Ajax call
$.ajax({
url : url,
type : "POST",
dataType : 'json',
contentType : 'application/json; charset=UTF-8',
data : JSON.stringify(jsonArray),
success : function(response) {
//Some Code here
}
});
Please help me sending data. Or tell me if I am making any mistake here. Thank you
In JavaScript / JSON arrays are 0 based indexed data structures. What you are using here is more like a Map:
var jsonArray = [];
jsonArray["company_name"]=company_name ;
In JavaScript you cannot use arrays like this (well you can, but it is probably not what you want). For a data structure like a map that maps strings to objects rather then an index to objects, just use an object.
Or in short: Use var jsonArray = {}; rather than var jsonArray = []; The {} will create an object that you can assign properties to like you did. And JSON.stringify will correctly translate this into a JSON string like this:
{ "property": value, "otherProperty", otherValue }
Do something like this.
$.ajax({
url: url,
type: "POST",
dataType: 'json',
contentType: 'application/json; charset=UTF-8',
data: JSON.parse(JSON.stringify(jsonArray)),
success: function(response) {
//Some Code here
}
});
The JSON.parse() method parses a string as JSON, optionally transforming the value produced by parsing. Read more about JSON.parse() method
The JSON.stringify() method converts a JavaScript value to a JSON string. Read more about JSON.stringify() method
Here simply you can send an array and Parse it in server side.
$.ajax({
url : url,
type : "POST",
dataType : 'json',
data : jsonArray,
success : function(response) {
//Some Code here
}
});
i try to use ajxt to send post request to my restful service
here is my ajax code
var lat = marker.getPosition().lat();
var lng = marker.getPosition().lng();
//xmlhttp.open("GET","http://192.168.1.100:8080/MapDemo/service/add?name=hieugie333&longitude=123&latitude=321",true);
//xmlhttp.send();
//document.getElementById("message").innerHTML=xmlhttp.responseText;
var JSONObject= {"name":name, "longitude":lng,"latitude":lat };
var jsonData = JSON.parse( JSONObject );
var request = $.ajax({
url: "http://192.168.1.100:8080/MapDemo/service/add",
type: "POST",
contentType: "application/json; charset=utf-8",
data: jsonData,
dataType: "json"
});
can anyone help me in this case ?
var JSONObject= {"name":name, "longitude":lng,"latitude":lat };
That is a JavaScript object, not a JSON text.
var jsonData = JSON.parse( JSONObject );
That will error (or return null) because you aren't passing it a string containing a JSON text.
Your later code is expecting a string containing a JSON text though.
You want JSON.stringify not JSON.parse.
You need to change your "JSON.parse" to "JSON.stringify". You called the opposite function that you should have.
I'm a bit new in web development and I can't achieve what I'm trying to do.
I have a Database with a table called "PI_Banners", where I store some images. This table stores an ID and a VARBINARY column that contains the binary data of the image.
What I'm trying to do, is to retrieve that data with an Ajax request to a C# function, and create a "img" tag using Data URI Scheme. Then append that new image to a div
This is what I got:
Ajax call:
$(document).ready(function() {
var dto = {};
var dtoJSON = JSON.stringify(dto);
$.ajax({
async: false,
url: 'BannerRotativo.aspx/devuelveBanners',
cache: false,
dataType: 'json',
type: "POST",
data: dtoJSON,
contentType: "application/json; charset=utf-8",
success: function(data, textStatus, jqXHR) {
responsedevuelveBanners(data);
},
error: errorResponse
});
});
Being "devuelveBanners" the C# function.
C# code:
public static string devuelveBanners()
{
DataReader DR;
DR = listaBanners();
//armaJson creates the Json string from the DataReader.
string strJson = GENERAL.armaJson(DR);
return strJson;
}
public DataReader listaBanners()
{
try
{
string strComando;
sqlCommand SQLC;
DataReader DR;
strComando = "SELECT banner_img FROM PI_Banners";
//sqlCon is the connection, and is open already.
SQLC = new System.Data.SqlClient.SqlCommand(strComando, sqlCon);
SQLC.CommandType = CommandType.Text;
DR = SQLC.ExecuteReader();
return DR;
}
catch (Exception ex)
{
throw ex;
}
}
When I parse the Json string back, and create the image:
function responsedevuelveBanners(data)
{
var datos = JSON.parse(data.d);
$("#imgContainer").append("<img src='data:image/jpg;base64," + datos.Rows[0].Row[0].banner_img + "' />");
}
the image is created but doesn't show up, because it has this URL:
data:image/jpg;base64,System.Byte[]
I know I'm doing something terribly wrong trying to retrieve the json data this way, but I don't know how to achieve this!
Thanks in advance!
In order to use <img src="data:image/PNG;base64' the base64 part is because you need to return a Base64 string instead of array of bytes therefore you need to convert your byte[] to 64Base using: Convert.ToBase64String(buffer)
So using your code as example:
ImageConverter imageConverter = new ImageConverter();
byte[] resourceByteArray = (byte[])imageConverter.ConvertTo(_YourObj.GetImage(), typeof(byte[]));
Your WebApi method should be returning:
return Convert.ToBase64String(resourceByteArray);
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 {}.