Parsing JSON array in JQuery - javascript

I'm trying to get the hand on JQuery and JSON using an ASP.NET webservice. The Webservice returns this result:
{
MyResult: {
Ticket: {
"Author": "rd",
"CssClass": "RED",
"ExpirationDateTime": "2009-08-16T16:55:43.577+02:00",
"id": "38",
"Message": "We are going down",
"ModifiedDateTime": "2009-08-17T11:14:20.5+02:00",
"MoreInfo": null
}
}
}
On the client side I'm using JQuery to get the result using the ajax function like this:
$.ajax({
type: "POST",
url: "TickerFeeder.asmx/GetTicket",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(resultJSON) {
//-- Please fill your code here for getting the first item from the array into variables
}
But I'm missing out the stuff how to retrieve the first item from the JSON array into some variables. Something like this (pseudo-code):
var message = resultJSON[0].Message
var cssclass = resultJSON[0].CssClass
Anybody with a hint,help?
Thanks for your help
Cheers
Frank

Your JSON is not valid, you should use quotes on the MyResult and Ticket members.
{
"MyResult": {
"Ticket": {
"Author": "rd",
"CssClass": "RED",
"ExpirationDateTime": "2009-08-16T16:55:43.577+02:00",
"id": "38",
"Message": "We are going down",
"ModifiedDateTime": "2009-08-17T11:14:20.5+02:00",
"MoreInfo": null
}
}
}
Also there is no array involved, the arrays are defined with the square bracket characters [....] literal notation, so you can access your values directly:
resultJSON.MyResult.Ticket.Message;
resultJSON.MyResult.Ticket.CssClass;

Ok, found out that my Asp.Net webService was producing a wrong result set. So instead of returning a string item I returned a complete object and handled the Json conversion to Asp.Net webservice. That did the trick !

Related

jQuery won't correctly POST a JSON containing an array as one of its properties

I'm trying to use jQuery to send a JSON object, which has an array as one of its properties, to my API endpoint. I've defined it like this:
let bidding = {
"name": $("#name").val(),
"applicant": $("#applicant").val(),
"start_date": $("#start_date").val(),
"end_date": $("#end_date").val(),
"products": []
}
$("#products").children(".dropdown").each(function(key, value) {
bidding.products.push(
{
"product_name": $(value).children(".btn").text(),
"quantity": $(value).children("input").val()
}
);
});
And when I do a console.log(JSON.stringfy(bidding)) it parses just as expected, for example:
{
"name":"Material de Construção",
"applicant":"Prefeitura",
"start_date":"26/09/2017",
"end_date":"01/10/2017",
"products":[
{"product_name":"Cimento (5kg)","quantity":"200"},
{"product_name":"Tijolo","quantity":"100"},
{"product_name":"Caneta","quantity":"5"}
]
}
But when I POST it using $.post("/api", bidding); my API receives it like this:
{
name: 'Material de Construção',
applicant: 'Prefeitura',
start_date: '26/09/2017',
end_date: '01/10/2017',
'products[0][product_name]': 'Cimento (5kg)',
'products[0][quantity]': '200',
'products[1][product_name]': 'Tijolo',
'products[1][quantity]': '100',
'products[2][product_name]': 'Caneta',
'products[2][quantity]': '5'
}
How can I make it so jQuery will stop creating new properties for each entry in the array and instead send the entire array as a single property?
You need to set to false:
processData: By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.
Hence your post will be:
$.ajax({
type: "POST",
url: "/api",
data: JSON.stringify(bidding),
processData: false,
contentType: "application/json",
dataType:"json",
success: function () {
}
});
$.post("/api", JSON.stringify(bidding));
And in the server side decode the json. If you are using php use json_decode
Using json is always a good idea to preserve the data structure

How can I get response from webservice in jquery?

I want to get the data response from my login webservice. Here is my web service
http://41.128.183.109:9090/api/Data/getloginer?medid=a&pass=a
(for testing). Here is my code:
$("#login").click(function () {
var url = "http://41.128.183.109:9090/api/Data/getloginer?medid=a&pass=a";
$.ajax({
url: url,
type: 'Get',
success: function (data) {
alert(data.Medical_id);
},
});
});
The alert() shows me undefined. Please advise on what the problem could be.
The result is an array, so in order to get that field you have to iterate the result or get the first item:
for (var i in data) {
console.log(d[i].Medical_id);
}
Or you can simply get the first result:
$.ajax({
url: 'http://41.128.183.109:9090/api/Data/getloginer?medid=a&pass=a',
type: 'Get',
success: function (data) {
alert(data[0].Medical_id);
}
});
The JSON result you are getting is :
[{"$id":"1","id":8,"Medical_id":"a","Password":"a","Name":null,"Email":null,"gender":null,"Type":null}]
use for each to iterate through the results or
instead of this you can check the result like this :
var data = [{ "$id": "1", "id": 8, "Medical_id": "a", "Password": "a", "Name": null, "Email": null, "gender": null, "Type": null }]
alert(data[0].Medical_id);
If you develop application in localhost then refer this questions also.
"No 'Access-Control-Allow-Origin' header is present on the requested resource"
If you are using chrome, then use this link to use CORS enable plugin.
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en-US
hope this will help

MediaWiki JSON Api always returning "undefined"

I'm trying to retrieve some data from the MediaWiki Api; especifically the registration date of a certain user. Taking Wikipedia as a live example, according to their Api sandbox, the request URL to get the information of Jimmy Wales would be:
/w/api.php?action=query&list=users&format=json&usprop=registration&ususers=Jimbo_Wales
So I make an Ajax call:
$.ajax({
dataType: "jsonp",
url: "/w/api.php?action=query&list=users&format=json&usprop=registration&ususers=Jimbo_Wales",
success: function (data) {
var timestamp = data.query.registration;
console.log(timestamp);
}
});
But if I run that script on Firebug, I simply get "undefined". What am I missing?
The resulting JSON data is something like:
{
"batchcomplete": "",
"query": {
"users": [
{
"userid": 24,
"name": "Jimbo Wales",
"registration": "2001-03-27T20:47:31Z"
}
]
}
}
Of course, data.query.registration is undefined. it is not available. Your have to "address" the user itself. Like data.query.users[0].registration.

Value showing undefined when trying to output data returned as json from server

I am new to Yii2 framework and PHP.I used Mongo DB as the backend database.I fetched a document from a collection and returned the data as Json from the controller.The data returned back is given below.
{
"55b08c383e1a36233fdbdc06": {
"_id": { "$id": "55b08c383e1a36233fdbdc06" },
"address": [ "abcdgt", "zxcv" ],
"age": "23",
"email": [ "qwert#gmail.com","abcd#mail.com" ],
"location": "kollam",
"name": "ajiths",
"phoneno": [ "9522585456", "7875642256" ] ,
"sex": "male"
}
}
But I am getting 'Undefined' when trying to alert result.name in Javascript code.The code at the front end is given below.
function loadClient(id){
url = "<?= Yii::getAlias('#serverpathweb')?>/client/showclient?id="+id;
$.ajax({
url: url ,
method: "GET",
success: function(result){
alert(result.name);
}
});
}
The code at the controller end is given below.
public function actionShowclient($id) {
$clientdetail = Yii::$app->mongodb->getCollection('client');
$result = $clientdetail->find(["_id" =>$id]);
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return $result;
}
Can anyone tell me how to get the value result.name.
your getting JSON result with id as key so access ur JSON data like this
first get the key of ur JSON using Object.keys
next using key print the values you need
var id=Object.keys(result)[0]; //it will print your JSON key i.e. "55b08c383e1a36233fdbdc06"
alert(result[id]['name']); // it will print the name
Note if you are getting multiple user details please let me know
Your "result" object is probably a String because you're not telling jQuery otherwise. Trying adding the option dataType:json to your request as in:
$.ajax({ url: url, method: 'GET', dataType: 'json', etc...
Edit: It also looks like there's a simple bug in your code. You need to access your property where it's nested in the resulting object:
result[id].name

How to add the new JSON from existing JSON file

I searched here get few related posts found but not helpful. I created one json file it has some text i want to append some more json in that using javascript(JSON stored in locally).
I have json file like this:
{ "Home": [ "a", "b", "c" ] }
i want to include this text "Log": 1
want to achieve like this,
{ "Home": [ "a", "b", "c" ], "Log": 1 }
Now I have like this in my json file(currently i have but json format is not correct)
{ "Home": [ "a", "b", "c" ] }
{ "Log": 1 }
$.getJSON('myfile.json', function(data) {
alert("success");
}.error(function(data){
alert(JSON.stringify(data));
});
this returns parser error. I know the JSON format is wrong. Please guide me to create a correct JSON format.
The error is in both versions of the JSON. You are missing the " at the start of the string c.
http://jsonlint.com/ will help you track down where errors in JSON occur.
As a rule of thumb, you should create JSON using a JSON serializer in a mature library and not by hand or string concatenation.
Now i have like this in my json file
That's completely wrong. The code you had in "Now i want to achieve like this" was right (aside from the error mentioned above).
You need to read your JSON, parse it into a JS object, edit the object, and convert back into JSON before writing:
assuming myfile.json contains:
{ "Home": [ "a", "b", "c" ] }
$.getJSON('myfile.json', function(data) {
alert("success");
obj = JSON.parse(data);
obj.log = 1;
writeJSON(JSON.stringify(obj));
}.error(function(data){
alert(JSON.stringify(data));
});
and writeJSON will be something like:
function writeJSON(jsonString)
$.ajax({
type: 'POST',
url: 'myfile.json',
data: jsonString,
success: function(data) { alert('write succesful!'); },
contentType: "application/json",
dataType: 'json'
});
}
assuming that you are using a server which can both read and write via this endpoint.

Categories