I want to create a JSON string in the following format as below using AngularJS:
{
"userid": 100,
"fleetid": 506,
"comments": "This is a test comment",
"fleetcheckdate": "29/10/1976",
"options": [{
"fleetcheckid": "1",
"fleetcheckvalueid": "1"
}, {
"fleetcheckid": "2",
"fleetcheckvalueid": "1"
}, {
"fleetcheckid": "3",
"fleetcheckvalueid": "1"
}]
}
Where
"userid"
"fleetid"
"comments"
"fleetcheckdate"
are all separate values know to me.
For "options" I have a multi-dimensional array that stores the values for "fleetcheckid" and "fleetcheckvalueid" that I create as follows:
$scope.selectedRadioArray = [];
$scope.doSomething = function(fleetCheckItemID, fleetCheckID)
{
$scope.selectedIDS = [fleetCheckItemID, fleetCheckID];
$scope.selectedRadioArray.push($scope.selectedIDS);
console.log("Array: " + $scope.selectedRadioArray); // Prints e.g. 4,3,8,6,34,8
}
The doSomething() method is fired each time the user interacts with a button and this generates the 2 values "fleetcheckid" and "fleetcheckvalueid". In the example above the user has clicked the button 3 times. The button can be clicked any number of times.
How do I convert the information above into a JSON string as per the example that I can send to my Database via a $http.post()?
When sending information to the server via $http, it's generally a good idea to use JSON. Don't convert it to a string.
Simply format your payload like this:
var payload = {
userId: $scope.userId,
/* etc.... */
options: $scope.optionsArray
};
Then, when sending to the server, do this:
$http.post('path/to/api', payload, { headers: { /* etc... */ }}).then(successCallback).catch(errorCallback);
you can use in the $http someething like this
$http({
url: uri,
method: 'post',
data: angular.toJson(categoria),
headers: {
'Authorization': 'Bearer ' + token.data.access_token,
'Content-type': 'application/json'
}
}).then(function successCallback(response) {
datosRecu = response;
deferred.resolve(datosRecu);
}, function errorCallback(response) {
datosRecu = response;
deferred.resolve(datosRecu);
});
in this case `angularToJson` convert it on a JSON and send it in the body
Related
I am using the Rasa X HTTP API to parse a yaml file and convert to a JSON object. I want to take this JSON object and then send it to my datatable to populate the rows. The problem is when I populate the datatable when calling the function in my datatable javascript, the JSON returns like this:
The API according to the docs here turns the payload into JSON format: https://rasa.com/docs/rasa-x/pages/http-api#operation/getDomain
Here is my code for the HTTP API:
export function getDomain(token) { //used to get auth token which is recreated each instance
var data = ""
//console.log(token);
var header_data = { Authorization: "Bearer " + token }
//console.log(header_data);
var sendData = {} //data to send. Check Rasa x API doc
$.ajax({
url: 'http://localhost:5002/api/domain',
type: 'GET',
async: false,
headers: header_data,
success: function (resp) {
//put name of json value you want to read after 'resp.'
//console.log(data);
var jsonDomain = yaml.parse(resp);
data = jsonDomain.entities;
console.log(typeof (data));
return data;
},
error: function (error) {
console.log('Error ${error}');
}
});
return data;
}
This function above parses the yaml file to get the data
export function getAuth() { //used to get auth token which is recreated each instance
var data = "";
var sendData = { "username": "me", "password":"huiwehfuiwfa" } //password changes each instance, there is a way to create a constant one too
$.ajax({
url: 'http://localhost:5002/api/auth',
//projects/default/intents',
type: 'POST',
async: false, //depracted but needs to be included to have it work
headers: {
"Access-Control-Allow-Origin": "*"
},
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(sendData),
success: function (resp) {
data = resp.access_token; //put name of json value you want to read after 'resp.'
return data;
},
error: function (error) {
console.log('Error ${error}');
}
});
return data;
}
This function gives authorization to use the API, gets the datatype as JSON, and stringifys it.
The console log for this shows as an object:
(3) ["plant", "water", "temperature"]
0: "plant"
1: "water"
2: "time"
length: 3
I then call this function to be able to use the data from the API in my datatables javascript:
import { getAuth, getDomain } from "./yaml.js";
export function populateTable() {
var token = getAuth();
var table_data = getDomain(token); // this gets the JSON data
var ieColumns = [{
title: "Name",
type: "text"
}];
var E = $('#Forestry').DataTable({
"sPaginationType": "full_numbers",
data: table_data,
columns: ieColumns,
dom: 'frtBip', // Needs button container
select: 'single',
responsive: true,
altEditor: true, // Enable altEditor
buttons: [
{
text: 'Add',
name: 'add' // do not change name
},
{
extend: 'selected', // Bind to Selected row
text: 'Edit',
name: 'edit' // do not change name
},
{
extend: 'selected', // Bind to Selected row
text: 'Delete',
name: 'delete' // do not change name
}
], style: "width:100%"
});
When I try to parse the JSON data using the parse function, I get an error from datatables complaining it is not in valid format.
I have also wrapped the function call getting the data from the API in brackets like this
var table_data = [getDomain(token)]; // this gets the JSON data
This returns one row with the first element in the JSON object which is plant but not the others.
The object type this returns is an array(3).
I want it to return each element in a separate row.
This is my function to fetch the array.
$scope.getclinicofuser = function()
{
var dataParameter = {
"primaryEmailId":$scope.data1.email
}
$http({
url: "/cms/api/user/getUserClinic",
method: "POST",
headers :{'Content-Type': 'application/json','Accept': 'application/json' },
data: dataParameter
}) .success(function(response) {
$scope.DomainName = response;
console.log($scope.DomainName);
});
};
});
Here is the api call response
{
"clinicNames": [2]
0: {
"clinicName": "testing"
"DomainName": "Aman.example.com"
"primaryEmailId": "example#gmail.com"
}-
1: {
"clinicName": "test-clinic"
"DomainName": "raman.example.com"
"primaryEmailId": "example#gmail.com"
}-
-
"status_code": "success"
}
My html tag
<li ng-repeat="response in DomainName">{{root.clinicNames}}</li>
Now what i want to do is to display BOTH DomainName in HTML i had a hussel with HTML ng-repeat tags but still no clues what i am doing wrong
Try
<li ng-repeat="response in DomainName.clinicNames track by $index">{{response.DomainName}}</li>
I have got back response at this line in form of json from web api controller action:
var json = await response.Content.ReadAsStringAsync();
The short version of the response is something like this:
{
"Response": {
"ResponseStatus": 1,
"Error": {
"ErrorCode": 0,
"ErrorMessage": ""
},
"TraceId": "83b04f8c-f7dd-4755-9767-b0c861ea9e28",
"Origin": "DEL",
"Destination": "BOM",
"Results": [
[{
"ResultIndex": "OB12",
"Source": 6,
"Fare": {
"Currency": "INR",
"OtherCharges": 58.29,
"ChargeBU": [{
"key": "TBOMARKUP",
"value": 8.29
}, {
"key": "CONVENIENCECHARGE",
"value": 0
}, {
"key": "OTHERCHARGE",
"value": 50.00
}],
"Discount": 0,
},
}]
]
}
}
The full version is shown at http://pastebin.com/eEE72ySk
Then i am returning back HttpResponse from webApi Controller by sending this json var data to CreateResponse method and returning back res like this:
HttpResponseMessage res = Request.CreateResponse(HttpStatusCode.OK, json);
return res;
I have to return back this res to $.ajax function on view page:
$.ajax(
{
url: "/api/Flight/SearchFlight",
type: "Post",
data: $('form').serialize() + '&' + $.param({ 'TokenId': $("#pageInitCounter").val()}, true),
success: function (data) {
alert(data);
var items = [];
$.each(data, function (key, val) {
items.push(key + ' : ' + val + '</br>');
});
}
});
I can see the whole content in alert box.
I want to know how to loop through each and every data i got back and assign their values to the respective <div> elements on the view page. The Response which i got back contains several arrays and arrays into arrays. I am confused how to manage each and every data.
Arrays are accessed with indexers and for an array containing an array, you use
XXX[0][0].YYY
to access the first array within the first array.
The code to access some of your properties would be
$.ajax(
{
url: "/api/Flight/SearchFlight",
type: "Post",
data: $('form').serialize() + '&' + $.param({ 'TokenId': $("#pageInitCounter").val()}, true),
success: function (data) {
var responseStatus = data.Response.ResponseStatus; // returns 1
var errorCode = data.Response.Error.ErrorCode; // returns 0
var origin = data.Response.Origin; // returns 'DEL'
var resultIndex = data.Response.Results[0][0].ResultIndex; // returns 'OB12'
}
});
Most of the data in the arrays seems to contain only one object, or one array containing one object and if that is always the case, then accessing it using [0] or [0][0] will be fine.
For the arrays containing multiple objects such as data.Response.Results[0][0].Fare.ChargeBU, you can use a for loop or $.each() loop, for example
$.each(data.Response.Results[0][0].Fare.ChargeBU, function (index, chargeBU) {
var key = chargeBU.key // returns "TBOMARKUP", "CONVENIENCECHARGE", "OTHERCHARGE"
});
Try This
{
url: "/api/Flight/SearchFlight",
type: "Post",
data: $('form').serialize() + '&' + $.param({ 'TokenId': $("#pageInitCounter").val()}, true),
success: function (data) {
alert(data);
var items = [];
$.each(data.Response.Results, function (key, val) {
items.push(key + ' : ' + val + '</br>');
});
}
};
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
How to get display return values from the JSON values.I need to get value the user id
$('User_id').observe('blur', function(e) {
var txt = $('User_id').value;
jQuery.ajax({
type: 'get',
url: BASE_URL + 'admin/index/user_id',
data: {
user_id: txt
},
dataType: 'json',
success: function(data) {
console.log('success' + data.success);
if (data.success) {
var Value = data.location.user_id;
alert(Value);
}
}
});
});
These values are getting in html form. In that I need to store user id in Value varable. But I receive successundefined as a output..
[{
"user_id": "139",
"mobile": "9042843911",
"gender": "male",
"hashcode": "DfAbMqLApAV6nVa1z940",
"username": "anandhsp21",
"password": "74bcff7d1199012e154f364e3f65e31d:8I",
"authorized_person": "Anandh",
"created": "2015-06-08 13:46:55",
"modified": "2015-06-08 06:43:35",
"logdate": "2015-06-08 08:16:55",
"lognum": "12",
"reload_acl_flag": "0",
"is_active": "1",
"extra": "N;",
"rp_token": null,
"rp_token_created_at": null,
"app_name": "",
"api_key": ""
}]
Please some one help. Thanks in Advance
Your get the data in array so use loop in success data
for (var i=0; i<data.length; i++) {
console.log('success' + data[i].user_id );
}
If you know the record length is 1 then use directly
console.log('success' + data[0].user_id );
Your data is an array that contains one object. So you can access this object using :
success: function(data){
console.log('success' + data[0].user_id );
Trying to log success is pointless, because there is no success key whatsoever in the received data.
Make sure that you get the response in proper json format,and as harshad pointed String male should be wrapped in double quotes.
After you get that fixed,you can access the user_id as:
data[0].user_id
data.success is undefined, because the received data is stored directly in data. That's the first argument of the success block. You can access the received data directly by data[0] to get the object inside of the array, or if you have a larger array you can do a for each loop over it, etc..
Try this, simply use json.parse()
$(document).ready(function() {
var v = ['{"user_id":"139","mobile":"9042843911"}'];
var obj = JSON.parse(v);
alert(obj.user_id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
To get userid please follow below code I edited,
$('User_id').observe('blur', function(e) {
var txt = $('User_id').value;
jQuery.ajax({
type: 'get',
url: BASE_URL + 'admin/index/user_id',
data: {
user_id: txt
},
dataType: 'json',
success: function(data) {
// this below userid is the value user_id you want.
var userid = data[0].user_id;
}
});
});
There is a json error
"gender":male
Strings male should be wrapped in double quotes.
you need to make sure that your response is formatted appropriately and according JSON.org standards.