Python Object to json for jquery - javascript

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?

Related

jsGrid plugin - How to filter with remote data?

I'm a newbie when it comes to javascript. I'm using the jsGrid plugin to display a grid in the browser. The grid column headers will have the values "Request Status" and "Request Id". I can make it work with static data.
(function() {
var adminDashboardController = {
loadData: function(filter) {
return $.grep(this.requests, function(request) {
return (!filter.Status || request.Status === filter.Status)
&& (!filter.RequestId || request.RequestId.indexOf(filter.RequestId) > -1)
});
},
insertItem: function(insertingReq) {
},
updateItem: function(updatingReq) {
},
deleteItem: function(deletingReq) {
}
};
window.adminDashboardController = adminDashboardController;
adminDashboardController.status = [
{ Name: ""},
{ Name: "Requested"},
{ Name: "Declined"}
];
//This is the static data
adminDashboardController.requests = [
{ "Status": "Requested", "RequestId": "1"},
{ "Status": "Declined", "RequestId": "2"}
];
}());
But when it comes to fetching the data from an ajax call (using a json file for testing as the data source), the data no longer gets filtered when I choose "Requested" or "Declined" as the filtering criterion. I'm using the format mentioned in the documentation like this -
(function() {
var adminDashboardController = {
loadData: function (filter) {
return $.ajax({
type: "GET",
dataType: "json",
url: "/json/db514.json",
data: filter
});
},
insertItem: function(insertingReq) {
},
updateItem: function(updatingReq) {
},
deleteItem: function(deletingReq) {
}
};
adminDashboardController.status = [
{ Name: ""},
{ Name: "Requested"},
{ Name: "Declined"}
];
}());
I can't understand how to implement the filtering in this case!
The reason is that filtering should be implemented in the code.
In general it can be done:
on the client (just as in your first sample)
on backend, then you have to pass the filter to your endpoint, which will do filtering and return data.
combined approach (partially on backend and after on the client)
In your case you could either add an endpoint on backend, which will load json and filter data, or still do filtering on client-side, for example:
loadData: function (filter) {
return $.ajax({
type: "GET",
dataType: "json",
url: "/json/db514.json"
}).then(function(requests) {
return $.grep(requests, function(request) {
return (!filter.Status || request.Status === filter.Status)
&& (!filter.RequestId || request.RequestId.indexOf(filter.RequestId) > -1)
});
});
}
Checkout this issue on GtiHub https://github.com/tabalinas/jsgrid/issues/32.

Return back json data to $.ajax function

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

code igniter - how to submit an ajax javascript object to the database with jQuery

I have a javascript array of data that I want to submit to my codeigniter database:
[
{
"name": "title",
"value": "myTitle"
},
{
"name": "content",
"value": "myContent."
}
]
I want to submit this data to codeigniter, and have it update the database. Note that this is not data coming from a form, so I can't just use the typical code igniter form_open() / serialize() method. I am using an ajax post and dynamically building the data:
var submissionData = [];
instanceFields.each(function(index){
var $thisField = $(this);
var thisData = {};
thisData.name =$thisField.attr('data-name');
thisData.value = $thisField.text();
submissionData.push(thisData);
});
var submissionString = {arr: JSON.stringify(submissionData)};
var submissionURL = baseURL + 'instances/edit';
$.ajax({
type: "POST",
url: submissionURL,
data: submissionString,
success: function(data){
console.log("success:",data);},
failure: function(errMsg) {
console.error("error:",errMsg);
}
Normally, for data posted from a form, I could access it like this in code igniter:
$this->input->post('title')
But if I echo that out here, I get an empty string.
I would then insert the data like this:
$data = array(
'title' => $this->input->post('title'),
'content' => $this->input->post('content'),
);
return $this->db->insert('extra_instances', $data);
If I decode the JSON and do a var dump, it looks like this:
success: array(5) {
[0]=>
object(stdClass)#19 (2) {
["name"]=>
string(5) "title"
["value"]=>
string(21) "myTitle"
}
[1]=>
object(stdClass)#20 (2) {
["name"]=>
string(7) "content"
["value"]=>
string(238) "myContent"
}
}
How can I modify this to insert into the database?
If I understand you, you mean that you want to send directly the object to insert into the database so
Javascript: You send the array into the $_POST key 'insertData'
var submissionData = [];
instanceFields.each(function(index){
var $thisField = $(this);
var thisData = {};
thisData.name =$thisField.attr('data-name');
thisData.value = $thisField.text();
submissionData.push(thisData);
});
var submissionURL = baseURL + 'instances/edit';
$.ajax({
type: "POST",
url: submissionURL,
data: {
insertData : submissionData
},
success: function(data){
console.log("success:",data);
},
failure: function(errMsg) {
console.error("error:",errMsg);
}
});
PHP Controller: Receive the post, and you can insert an array directly to do both inserts.
$data = $this->input->post('insertData');
return $this->db->insert('extra_instances', $data);

jsTree - Populate Tree Dynamically using AJAX/C#Web Method

I have a div which I would like to fill with a jsTree:
I get the "Loading" icon where the tree is meant to display, however, there would seem to be a javascript error, even though one is not thrown.
I load my folder structure from an AJAX Request as follows. The Documents.aspx/GetFolders Web Method returns a List containing FolderId, ParentId & Folder Name. I have debugged the web method and it is passing the correct results to the jsTree "data" function.
$.ajax({
type: "POST",
url: 'Documents.aspx/GetFolders',
contentType: "application/json; charset=utf-8",
success: function (data) {
data = data.d;
$("#tree").jstree({
"core": {
"themes": {
"responsive": true
},
"data": function () {
var items = [];
items.push({ 'id': "jstree_0", 'parent': "#", 'text': "Documents" });
$(data).each(function () {
items.push({ 'id': "jstree_" + this.DocumentFolderId, 'parent': "jstree_" + this.ParentId, 'text': "" + this.Name });
});
return items;
}
},
"types": {
"default": {
"icon": "fa fa-folder icon-lg"
},
},
"plugins": ["contextmenu", "dnd", "state", "types"]
});
},
error: function () {
toastr.error('Error', 'Failed to load folders<span class=\"errorText\"><br/>There was a fatal error. Please contact support</span>');
}
});
After debugging the code, it seems the data is being retrieved correctly and is returning the object array as intended.
Is there are any problem with the above (or is there somewhere else I should be looking)? Or is there a better method of achieving its intended purpose?
I think I have finally found the answer! :)
"core": {
"themes": {
"responsive": true
},
"data": {
type: "POST",
url: "Documents.aspx/GetFolders",
contentType: "application/json; charset=utf-8",
success: function (data) {
data.d;
$(data).each(function () {
return { "id": this.id };
});
}
},
}
Server side, you need to return the data in the array format required, i.e:
[{id = "node0", parent = "#", text = "Documents"},
{id = "node1", parent = "node0", text = "Public"},
{id = "node2", parent = "node0", text = "Restricted"}]
Just in case anyone has the "loading..." issue, this format fixed it for me when returning data.
[{"id":"node0", "parent":"#", "text":"Documents"},
{"id":"node1", "parent":"node0", "text":"Public"},
{"id":"node2", "parent":"node0", "text":"Public"}]

JQPlot, JSON and 'No data specified' Error

I am trying to use JQPlot within a VB.NET application under .NET 3.5. On a button click, using jquery, I am trying to populate the JQPlot Chart with JSON derived data using a ASP.NET Webservices Source file (which is part of the solution).
The JSON data is sent by the web service but when it is presented to JQPlot I get the javascript error 'No Data Specified' which is generated by JQPlot code.
My code listing is as follows:
Code to listen for the button to be clicked:
$(document).ready(function () {
$('#<%=btnASMX1.ClientID%>').click(function () {
getElectricDataJSON();
return false;
});
});
Javascript code outside the 'document.ready' function:
function ajaxDataRenderer() {
var ret = null;
$.ajax({
// have to use synchronous here, else the function
// will return before the data is fetched
async: false,
//url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: "AccountsService.asmx/GetJSONData",
data: "{AccountID: " + $('#<%= hiddenAccountID.ClientID%>').val() + " }",
dataType: "json",
success: function (response) {
var ret = response.d;
// The following two lines just display the JSON data for testing purposes
$('#<%=outputASMX.ClientID%>').empty();
$('#<%=outputASMX.ClientID%>').html("<div>" + ret + "</div>");
return ret;
},
error: function (request) {
$('#<%=outputASMX.ClientID%>').html("<div style='color:red;'>WEBSERVICE UNREACHABLE</div>");
}
});
return ret;
};
var jsonurl = "./jsondata.txt";
function getElectricDataJSON() {
var ret = ajaxDataRenderer();
var plot1 = $.jqplot('chart2', jsonurl, {
title: "AJAX JSON Data Renderer",
dataRenderer: ret, //$.jqplot.ciParser
dataRendererOptions: {
unusedOptionalUrl: jsonurl
}
});
}
The JSON data format is as follows:
[ { "todate": "2013-09-23T00:00:00", "Bill": 7095.65 }, { "todate": "2013-08-22T00:00:00", "Bill": 1137.96 }, { "todate": "2013-07-24T00:00:00", "Bill": 220429.41 }, ... ]
Any help or advice will be appreciated.
Thanks to #Fresh for their quick response. Here is the complete solution to my problem:
Code to listen for the button to be clicked:
$(document).ready(function () {
$('#<%=btnASMX1.ClientID%>').click(function () {
getElectricDataJSON();
return false;
});
});
JS function to get the data from a web service:
function ajaxDataRenderer() {
var ret = null;
$.ajax({
// have to use synchronous here, else the function
// will return before the data is fetched
async: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: "AccountsService.asmx/GetJSONData",
data: "{AccountID: " + $('#<%= hiddenAccountID.ClientID%>').val() + " }",
dataType: "json",
success: function (response) {
ret = response.d; // return response string object
},
error: function (request) {
$('#<%=outputASMX.ClientID%>').html("<div style='color:red;'>WEBSERVICE UNREACHABLE</div>");
}
});
return ret;
};
Data structure outputted by the web service is:
[ { "todate": "2013-09-23T00:00:00", "Bill": 7,095.65 }, { "todate": "2013-08-22T00:00:00", "Bill": 1,137.96 }, { "todate": "2013-07-24T00:00:00", "Bill": 220,429.41 }, ... ]
Data structure that is expected by JQPlot:
[ [ "2013-09-23T00:00:00", 7095.65 ] , [ "2013-08-22T00:00:00", 1137.96 ], [ "2013-07-24T00:00:00", 220429.41 ], ... ]
Note the removal of the comma's in the 'expected data' Bill field.
And finally, the function getElectricDataJSON() that is being called by btnASMX1 where 'chart2' is the ID of the div tags where the chart will be drawn.
function getElectricDataJSON() {
// Get JSON 'string' object
var ret = ajaxDataRenderer();
// If JSON string object is null, stop processing with friendly message
if (ret == null) {
$('#<%=outputASMX.ClientID%>').html("<div style='color:red;'>CHARTS ARE NOT AVAILABLE AT THIS TIME</div>");
return false;
}
// Now push required data into a JSON array object
var sampleData = [], item;
$.each(ret, function (key, value) {
sampleData.push([value.todate, parseFloat(value.Bill.replace(/,/g, ""))]);
});
var plot = $.jqplot('chart2', [sampleData], {
title: 'AJAX JSON Data Renderer',
dataRenderer: sampleData,
...
});
}
The method signature for your datarender (i.e. ajaxDataRender) is wrong. The signature should look like this:
function(userData, plotObject, options) { ... return data; }
(See the documentation here)
In your example you are passing the datarenderer "ret" which is not a function with the correct datarender signature. Also the jsonurl you are passing to getElectricDataJSON() is redundant as at no point in your code is the data from "AccountsService.asmx/GetJSONData" persisted to "./jsondata.txt".
Hence you should change your code to this:
$(document).ready(function(){
function ajaxDataRenderer(url, plot, options) {
var ret = null;
$.ajax({
// have to use synchronous here, else the function
// will return before the data is fetched
async: false,
url: url,
dataType: "json",
success: function (response) {
var ret = response;
// The following two lines just display the JSON data for testing purposes
$('#<%=outputASMX.ClientID%>').empty();
$('#<%=outputASMX.ClientID%>').html("<div>" + ret + "</div>");
},
error: function (request) {
$('#<%=outputASMX.ClientID%>').html("<div style='color:red;'>WEBSERVICE UNREACHABLE</div>");
}
});
return ret;
};
var url = "AccountsService.asmx/GetJSONData";
function getElectricDataJSON() {
var plot1 = $.jqplot('chart2', url, {
title: "AJAX JSON Data Renderer",
dataRenderer: ajaxDataRenderer,
});
}

Categories