Return back json data to $.ajax function - javascript

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>');
});
}
};

Related

Python Object to json for jquery

I have code that gives me an object. I would like to send this object to jquery (ajax).
def create(country):
class Operator:
def __init__(self, name, id, a,b,c):
self.name = name
self.operator_id = id
self.product_type = self.Products(a,b,c)
class Products:
def __init__(self ,a,b,c):
self.name = "Data"
self.product_info = self.Items(a,b,c)
class Items:
def __init__(self, a,b,c):
self.min_value = a
self.max_value = b
self.currency = c
data = []
for operator in country.product_details:
provider_name = get_provider(operator)
product_name = get_product(operator)
data.append(Operator(provider_name.name, provider_name.provider_id,
operator.a ,operator.b, operator.c))
return data
This returns an array of objects with data in it. After looking online, I found that
json.dumps(data, indent=4, default=lambda x: x.__dict__)
was the way to convert it to json for ajax. Console.log shows jquery is getting the below data as a one liner string.
[
{
"name": "test",
"operator_id": 1,
"product_type": {
"name": "Data",
"product_info": {
"min_value": 1,
"max_value": 1,
"currency": "test"
}
}
},
My Javascript code.
$(function()
{
$('.search-form').on('submit', function (event)
{
event.preventDefault();
$.ajax(
{
url: '/getprod',
data: $('form').serialize(),
type: 'POST',
cache: false,
success: function (response) {
console.log(response);
$(response.name).each(function(){
console.log ("works")
});
},
error: function (error) {
console.log(error);
}
}
);
}
)
}
)
I try doing a for each of this but it isn't working. What am I doing wrong?

How to compare city obtained from geolocation with stored cities in my database and if city exists pass the id through ajax request?

My script is
<script type="text/javascript">
search = new Vue({
el: '#offers',
data: {
data: [],
authType: '{{uid}}',
key : '1',
with_ : 'district',
},
mounted() {
var self = this;
navigator.geolocation.getCurrentPosition( success, error );
data = {};
data['auth-token'] = this.authType;
data['key'] = this.key;
data['with_'] = this.with_;
function success( position ) {/* geolocation success callback */
var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + '%2C' + position.coords.longitude + '&language=en';
$.getJSON( GEOCODING ).done( function( location ) {
$('#country').html(location.results[0].address_components[5].long_name);
$('#state').html(location.results[0].address_components[4].long_name);
$('#city').html(location.results[0].address_components[2].long_name);
$('#address').html(location.results[0].formatted_address);
$('#latitude').html(position.coords.latitude);
$('#longitude').html(position.coords.longitude);
data['city'] = location.results[0].address_components[2].long_name;
$.ajax({
url: "http://127.0.0.1:8000/alpha/get/",
data: data,
type: "POST",
dataType: 'json',
success: function (e) {
if (e.status == 1) {
}
},
});
$.ajax({
url: "http://127.0.0.1:8000/city/",
method: "GET",
dataType: "JSON",
success: function(e) {
if (e.status == 1) {
self.cities = e.data;
}
},
});
});
}
},
});
</script>
Now with data['city'], I am passing the obtained city from geolocation. But I need to compare with the list of cities obtained through the ajax request http://127.0.0.1:8000/city/ and send the corresponding id as data['city'] instead of name.
I get json response of getting list of city as
{"status": true, "data": [{"id": 1, "name": "Palakkad"}, {"id": 2, "name": "kochi"}]}`
I need to compare the obtained city from geolocation with the above list and if city exists, I need to pass the corresponding ID as data['city'].
Please help me to have a solution for the same. I am very weak in js and this is my first project. I am a beginner. Please help me to provide a solution?
If I understand correctly, given an object with city data and a city name, you want to get the matching city's id from the city data (if there is a match). The function below should work for you.
It looks through cities.data to find an entry where the name matches. If one is found, the id is returned, otherwise, null is returned.
const cities = {"status": true, "data": [{"id": 1, "name": "Palakkad"}, {"id": 2, "name": "kochi"}]};
const cityName = 'Palakkad';
function findCity(name) {
const foundCity = cities.data.find(entry => entry.name === name);
return foundCity ? foundCity.id : null;
}
console.log(findCity(cityName));
console.log(findCity('Houston'));

the processResult in select2 do not working

I use select2 loading remote data I send an ajax request and get the response correctly but the processResult don't run and nothing will be show
the javascript code :
var formatProduct=
function(product) {
console.log("formatProduct");
if (product.loading) return product.text;
var markup = '<div class="product-to-compare" data=' + product.id + '>' + product.name + '</div>' ;
return markup;
}
var formatProductSelection =
function (product) {
console.log("formatProductSelection");
return product.name || product.text;
}
$(".js-data-example-ajax").select2({
placeholder: "Search for product",
minimumInputLength: 2,
ajax: {
url: '/product/ajax_product_list/',
dataType: 'json',
quietMillis: 300,
data: function (params) {
var id = $('#product-no-1').attr('data') ;
return {
key: params,
id: id
};
},
processResults: function (data) {
return {
results: data.items
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
templateResult: formatProduct, // omitted for brevity, see the source of this page
templateSelection: formatProductSelection // omitted for brevity, see the source of this page
});
and the JSON that my controller return as a response :
{
"items": [
{"id": "55dd980c8242b630cfaf4788", "name": "sallll"},
{"id": "55d58d7a8242b62c6b88504e", "name" : "inja"},
{"id": "55d58d558242b62c6b88504d", "name": "salam"}
]
}
You should rename your JSON to return text instead of name.
Note that if you're using an older version of select2 (<4) you should use results instead of processResults.
processResults: function (data) {
//There is my solution.Just directly manipulate the data
$.each(data.items, function(i, d) {
data.items[i]['text'] = d.name;
});
return {
results: data.items
};
}
In my case, I was refreshing the page and looking for the http request sent to fetch search data. So make sure you do a search to processResult get called.
In your JSON data, you rename name to text. Because select2 data only accepts column names id and text.

How to display returned JSON from a jQuery

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.

How to use jQuery .each() - I get a value, but it's the wrong one

I am returning a JSON object (as a String) through a servlet. The JSON object looks like this:
{
"3": "Martin Luther",
"30": "Boris Becker",
"32": "Joseph Goebels",
"19": "Leonardo Da Vinci"
}
My jQuery looks like this (the submission of data is correct because I get a proper looking result from the servlet):
$.ajax({
type: "GET",
url: "MyServlet",
data: queryString + "count=" + variables,
success: function(resultObj) {
$.each(resultObj, function(key, value) {
$("#resultCount").html(key + ", " + value);
});
}
});
However when I try to print the results, that is the variables key and value, I get a number for the key but not a number from the JSONObject and an empty string instead of the value.
Essentially the question is about how to "extract" the information from a JSON object.
Your JSON is not an array. It should look like this:
[{ "3":"Martin Luther" },
{ "30":"Boris Becker" }]
or even better:
[{ id: "3", name: "Martin Luther" },
{ id: "30", name: "Boris Becker" }]
Then you can loop:
$.each(data, function(index, item) {
alert(item.id + ' ' + item.name);
});
Try specifying dataType as json in your AJAX call:
$.ajax( {
type : "GET",
url : "MyServlet",
data : queryString + "count=" + variables,
dataType : 'json',
success : function(resultObj) {
$.each(resultObj, function(key, value) {
$("#resultCount").html(key+", "+value);
});
}
});
Couple things:
You should be using the JSON data type. Try the simpler $.getJSON method.
Your iteration is correct, but you'll be overwriting the previous results on each iteration (i.e. it comes out as just the Hitler entry)

Categories