Serializing or passing json objects into Ajax - javascript

The Json object was returned and I want to extract the data in JavaScript
In the sense of how to pass on the loop fields and extract data
def For_Sale_Listing(request,id):
try:
listing = Listing.objects.filter(pk=id)
listing_json = serializers.serialize("json", listing)
except Listing.DoesNotExist:
raise Http404('listing not found!')
data = {"listing_json": listing_json}
return JsonResponse(data)
$.ajax({
url: "/For-Sale-Listing"+"/" + parseInt(data[0]),
type: "GET",
data: {'Subscription': 1},
success: function(data) {
console.log(JSON.parse(data.listing_json));
},
error: function(xhr, status, error) {
}
});
I want pass to fields with javascript
[{"model": "listings.listing", "pk": 3, "fields": {"property_type": 1, "user": 1, "price": 13000000, "roomsTotal": 78, "Bathrooms": 6, "bedrooms": 67, "Receptionrooms": 67, "livingArea": "67.000", "lotSize": "67.000", "unitType": 1, "yearBuilt": null, "remodelYear": null, "hoaPrice": null, "groundTankSize": null, "garageSize": null, "homeDescription": "", "whatYouLoveDescription": "", "Dishwasher": false, "Dryer": false, "Freezer": false, "GarbageDisposal": false, "Microwave": false, "Oven": false, "Refrigerator": false, "Washer": false, "RadioGroup_Rashan": null, "ACarpet": false, "AConcrete": false, "ATiles": false, "ALinoleum": false, "ADSoftwood": false, "ADOther": false, "BreakfastNook": false, "DiningRoom": false, "FamilyRoom": false, "LaundryRoom": false, "Library": false, "MasterBath": false, "Office": false, "Workshop": false, "roomCount": null, "attic": false, "cableReady": false, "ceilingFan": false, "doublePaneWindows": false, "fireplace": false, "intercom": false, "jettedTub": false, "securitySystem": false, "CCentral": false, "CEvaporative": false, "CGeothermal": false, "CRefrigeration": false, "CSolar": false, "CWall": false, "COther": false, "CNone": false, "HForcedAir": false, "HGeothermal": false, "HHeatPump": false, "HRadiant": false, "HStove": false, "HWall": false, "HOther": false, "FCoal": false, "FElectric": false, "FGas": false, "FOil": false, "FPropaneButane": false, "FSolar": false, "FWoodPellet": false, "FOther": false, "FNone": false, "basketballCourt": false, "doorman": false, "elevator": false, "fitnessCenter": false, "gatedEntry": false, "nearTransportation": false, "tennisCourt": false, "RadioGroup_Architectural": null, "Brick": false, "CementConcrete": false, "Stone": false, "EOther": false, "FloorCount": null, ...

I'm not 100% sure what you are asking, but if you want to read result, you can just use property names from your JSON object. Something like this:
var data = {"model": "listings.listing", "pk": 3, "fields": {"property_type": 1, "user": 1, "price": 13000000, "roomsTotal": 78, "Bathrooms": 6}};
var test = "Model: " + data.model + "<br/>PK:" + data.pk + "<br/> Fields: <br/> Property_Type:" + data.fields.property_type;
------Result----
Model: listings.listing
PK:3
Fields:
Property_Type:1
Fiddler

Related

Transform JSON form front end so it fits what API expects

I have the following data structure held in state by my React application.
{"assetNum": "SP234",
"eventDate": "2021-08-15 08:30:00Z",
"manufacturers": {
"part1":"mfg1",
"part2":"mfg2",
"part3":"mfg3"},
"part1":{
"inlet":[true, true, true, true, true],
"outlet":[false, false, false, false, false]}
"part2":{
"inlet":[false, false true, true, true],
"outlet":[false, false, false, false, false]}
"part3":{
"suction":[true, true, true, true, true],
"discharge":[false, false, false, false, false]}
}
On the other end I have a .NET API expecting the following data structure:
{"assetNum": "SP234",
"eventDate": "2021-08-15 08:30:00Z",
"details":[
{"part":"part1",
"label":"inlet",
"manufacturer":"mfg1",
"locations":[true, true, true, true, true]},
{"part":"part1",
"label":"outlet",
"manufacturer":"mfg1",
"locations":[false, false, false, false, false]},
{"part":"part2",
"label":"inlet",
"manufacturer":"mfg2",
"locations":[false, false, true, true, true]},
{"part":"part2",
"label":"outlet",
"manufacturer":"mfg2",
"locations":[false, false, false, false, false]},
{"part":"part3",
"label":"suction",
"manufacturer":"mfg3",
"locations":[true, true, true, true, true},
{"part":"part3",
"label":"fischarge",
"manufacturer":"mfg3",
"locations":[false, false, false, false, false]},
]
}
I'm trying to avoid changing the state on the front-end since a lot of other things already depend on it. I'm also trying to avoid changing the API.
How can I go about transforming one object into the other structure anytime the user clicks "SUBMIT"? I was thinking of creating a class with a constructor and a method to generate the other JSON but that might be an overkill? I'm hoping there's a straightforward way to do this in Javascript that I haven't learned yet.
Thanks to all in advance,
Easily achieved using ...
2 x Object.entries
Array#map
and
Array#flatMap
const input = {
"assetNum": "SP234",
"eventDate": "2021-08-15 08:30:00Z",
"manufacturers": {
"part1": "mfg1",
"part2": "mfg2",
"part3": "mfg3"
},
"part1": {
"inlet": [true, true, true, true, true],
"outlet": [false, false, false, false, false]
},
"part2": {
"inlet": [false, false, true, true, true],
"outlet": [false, false, false, false, false]
},
"part3": {
"suction": [true, true, true, true, true],
"discharge": [false, false, false, false, false]
}
};
const output = {
assetNum: input.assetNum,
eventDate: input.eventDate,
details: Object.entries(input.manufacturers).flatMap(([part, manufacturer]) => Object.entries(input[part]).map(([label, locations]) => ({ part, label, manufacturer, locations})))
};
console.log(output);
You can use Object.keys and map your objects
code:
const data = {
"assetNum": "SP234",
"eventDate": "2021-08-15 08:30:00Z",
"manufacturers": {
"part1": "mfg1",
"part2": "mfg2",
"part3": "mfg3"
},
"part1": {
"inlet": [true, true, true, true, true],
"outlet": [false, false, false, false, false]
},
"part2": {
"inlet": [false, false, true, true, true],
"outlet": [false, false, false, false, false]
},
"part3": {
"suction": [true, true, true, true, true],
"discharge": [false, false, false, false, false]
}
};
let model = {
"assetNum": data.assetNum,
"eventDate": data.eventDate,
"details": []
}
Object.keys(data.manufacturers).forEach(key=>{
const row = data[key]
Object.keys(row).forEach(innerKey=>{
let item = {
"manufacturer":data.manufacturers[key],
"part": key,
"label": innerKey,
"locations": row[innerKey]
}
model.details.push(item)
})
})
console.log(model)

Javascript updates entire column in boolean matrix

I'm trying to update a specific index in a boolean matrix but it update the entire column. what might be the problem?
I'm attaching the code here:
const booleanMatrix = Array(5).fill(Array(5).fill(false));
console.log(booleanMatrix);
booleanMatrix[0][0] = true;
console.log(booleanMatrix);
first and second prints:
[
[ false, false, false, false, false ],
[ false, false, false, false, false ],
[ false, false, false, false, false ],
[ false, false, false, false, false ],
[ false, false, false, false, false ]
]
[
[ true, false, false, false, false ],
[ true, false, false, false, false ],
[ true, false, false, false, false ],
[ true, false, false, false, false ],
[ true, false, false, false, false ]
]
I expect it to be:
[
[ true, false, false, false, false ],
[ false, false, false, false, false ],
[ false, false, false, false, false ],
[ false, false, false, false, false ],
[ false, false, false, false, false ]
]
Your code is equivalent to:
const inner = Array(5).fill(false);
const booleanMatrix = Array(5).fill(inner);
Of course when you update inner, it updates on each row, since each row is pointing to the same thing.
You need to do
let x = Array(5).fill(null).map((i) => Array(5).fill(false));
console.log(x);
x[0][0] = true;
console.log(x);
const booleanMatrix = Array(5).fill(Array(5).fill(false));
This fills an array with 5 references to the same array.
Array(5).fill(false) // reference to one array
When you change one array, you're changing all of them, because they're all the same object in memory.
You need to create 5 different arrays and load each one of them:
let booleanMatrix = [
Array(5).fill(false),
Array(5).fill(false),
Array(5).fill(false),
Array(5).fill(false),
Array(5).fill(false)
];
Alternatively:
let booleanMatrix = Array(5).fill("throwAway").map( () => Array(5).fill(false));
This will create 5 unique arrays

passing dynamic value from AJAX to custom parameter in jQuery dataTable

I'm using dataTable with server side processing. I want to send token as custom parameter to the server. Token is set by AJAX. When AJAX request on dataTable fired, token parameter that send always null. I think it is because AJAX request on dataTable fired before get token process finished. Here are ways that I already tried.
1. Using ajax.data
function GetToken() {
var token;
$.get("/User/GetToken?_=" + new Date().getTime(), function (token) {
token= token;
});
return token;
}
var dataTable = $('#dataTable').DataTable({
serverSide: true,
pagingType: 'full_numbers',
scrollY: false,
scrollX: true,
sort: false,
fixedColumns: true,
autoWidth: true,
language: {
paginate: {
first: "<<",
previous: "<",
next: ">",
last: ">>",
}
},
pageLength: 10,
lengthMenu: [[2, 5, 10, 25, 50], [2, 5, 10, 25, 50]],
columns: [
{ "data": "Name", "autoWidth": true },
{ "data": "Address", "autoWidth": true },
{ "data": "Gender", "autoWidth": true },
],
ajax: {
url: '#Url.Action("LoadData", "Student")',
type: 'POST',
data: { token: GetToken() }
dataSrc: "Data"
}
});
2. Using preXhr.dt
var dataTable = $('#dataTable')
.on('preXhr.dt', function (e, settings, data) {
$.get("/User/GetToken?_=" + new Date().getTime(), function (token) {
data.token = token;
});
})
.DataTable({
serverSide: true,
pagingType: 'full_numbers',
scrollY: false,
scrollX: true,
sort: false,
fixedColumns: true,
autoWidth: true,
language: {
paginate: {
first: "<<",
previous: "<",
next: ">",
last: ">>",
}
},
pageLength: 10,
lengthMenu: [[2, 5, 10, 25, 50], [2, 5, 10, 25, 50]],
columns: [
{ "data": "Name", "autoWidth": true },
{ "data": "Address", "autoWidth": true },
{ "data": "Gender", "autoWidth": true },
],
ajax: {
url: '#Url.Action("LoadData", "Student")',
type: 'POST',
dataSrc: "Data"
}
});
3. Add looping for delay on preXhr.dt
var isTokenChange = false;
var dataTable = $('#dataTable')
.on('preXhr.dt', function (e, settings, data) {
$.get("/User/GetToken?_=" + new Date().getTime(), function (token) {
data.token= token;
isTokenChange = true;
});
while(!isTokenChange) {
}
isTokenChange = false;
})
.DataTable({
serverSide: true,
pagingType: 'full_numbers',
scrollY: false,
scrollX: true,
sort: false,
fixedColumns: true,
autoWidth: true,
language: {
paginate: {
first: "<<",
previous: "<",
next: ">",
last: ">>",
}
},
pageLength: 10,
lengthMenu: [[2, 5, 10, 25, 50], [2, 5, 10, 25, 50]],
columns: [
{ "data": "Name", "autoWidth": true },
{ "data": "Address", "autoWidth": true },
{ "data": "Gender", "autoWidth": true },
],
ajax: {
url: '#Url.Action("LoadData", "Student")',
type: 'POST',
dataSrc: "Data"
}
});
For third way, it's works but I think it's not a good solution. My question is what is a good solution to hold or delay ajax request on datatable until token has received?
You can chain your calls, Only when you receive a token fire the datatable initialization.
function GetToken() {
var token;
$.get("/User/GetToken?_=" + new Date().getTime(), function (token) {
initializeTable(token);
});
}
initializeTable(token){
// Here initialize ur data table with the passed token.
}
This works for me:
dataTable.context[0].ajax.data.yourCustomValue = value;
Since my variable name is bwsValue:
var dataTable = $('#users-grid').DataTable( {
"dom": 'lrtip',
"order": [[ 0, "asc" ]],
"processing": true,
"serverSide": true,
"ajax":{
url :"users_list.php?active="+active,
"data": {
"bwsValue": 1
},
type: "post",
}
});
I can now set the data to:
dataTable.context[0].ajax.data.bwsValue = 2;
You do not want to do a async request in this case, so instead of using $.get try something like this (async:false):
$.ajax({
type: "GET",
async:false,
url: "/User/GetToken?_=" + new Date().getTime(),
success: function(token, textStatus, xhr) {
data.token = token;
}
});

Disable keyboard Keys in WYSIHTML5

I want to disable all keyboard keys in wysihtml5 text editor .
I am using this editor https://github.com/bassjobsen/wysihtml5-image-upload
can anyone help me to do this. I have try "load" event and its works perfectly but i cannot use "onkeypress" or "onkeyup"\
var defaultOptions = $.fn.wysihtml5.defaultOptions = {
"font-styles": false,
"color": false,
"emphasis": false,
"lists": false,
"html": false,
"link": false,
"image": true,
events: {
"load": function() {
console.log('loaded!');
}
},
I think that is the answer below
var defaultOptions = $.fn.wysihtml5.defaultOptions = {
"font-styles": false,
"color": false,
"emphasis": false,
"lists": false,
"html": false,
"link": false,
"image": true,
events: {
"load": function() {
$('.wysihtml5-sandbox').contents().find('body').on("keydown",function(event) {
return false;
});
}
},

retrieving records based on url parameters on angularJs using restangular

I am quite new to angularJs.
I am trying to retrieve an object based on the url parameter.
For example I have the following code:
var tripApp = angular.module('tripApp', ['ui.state', 'ui.bootstrap', 'restangular', 'tripApp.directives', 'restaurantServices'])
tripApp.config(function($stateProvider, $urlRouterProvider, RestangularProvider){
RestangularProvider.setBaseUrl('json');
RestangularProvider.setRequestSuffix('.json');
$urlRouterProvider.otherwise("/hotels")
$stateProvider
.state('hotels', {
url: "/hotels/:id",
templateUrl: "templates/hotels.html",
controller: "HotelDetailController"
})
And my controller as:
tripApp.controller('HotelDetailController', function($scope, $timeout, Restangular) {
});
How would I be able to retrieve a record based on the field 'url' if my json file was:
{
"hotels":
[
{
"url":"bandos-island-resort",
"name": "Bandos Island",
"city": "Male",
"country": "Maldives",
"img": "http://www.barcelo.com/BarceloHotels/en_GB/Images/oviedo-barcelo-hotels-views.jpg21-29254.jpg",
"price": 199,
"offer": 50,
"standard": [1, 2, 3, 4],
"roomsleft": 4,
"facilities": [
{
"wifi": true,
"breakfast": false,
"spa": false,
"beachAccess": false,
"pool": false,
"airportShuttle": false,
"restaurant": false,
"bar": false,
"coffeeShop": false,
"noSmoking": false,
"petFriendly": false,
"jacuzzi": false,
"laundry": true,
"miniBar": false,
"parking": false,
"roomService": false,
"sauna": false,
"scubaDiving": false,
"snorkeling": false,
"waterSkiing": false,
"windSurfing": false,
"tennis": false,
"golf": false,
"weddingPlan": false
}
]
},
{
"url":"bandos-island-resort",
"name": "Club Faru",
"img": "http://www.barcelo.com/BarceloHotels/en_GB/Images/oviedo-barcelo-hotels-views.jpg21-29254.jpg",
"price": 299,
"offer": 0,
"standard": [1, 2, 3],
"roomsleft": 4,
"facilities": [
{
"wifi": true,
"breakfast": false,
"spa": false,
"beachAccess": false,
"pool": false,
"airportShuttle": false,
"restaurant": false,
"bar": false,
"coffeeShop": false,
"noSmoking": false,
"petFriendly": false,
"jacuzzi": false,
"laundry": false,
"miniBar": false,
"parking": false,
"roomService": false,
"sauna": false,
"scubaDiving": false,
"snorkeling": false,
"waterSkiing": false,
"windSurfing": false,
"tennis": false,
"golf": false,
"weddingPlan": false
}
]
}
]
}
I am able to retrieve the whole file and repeat the data, but I would like to filter a record based on the url field and use it in my view. Any help would be appreciated. Thanks
What you are looking for is the service $routeParams. Once you got your data from your file or AJAX request, you use $routeParams.id to get your :id in your route.
Here is a very simple example (from fiddle)
<div ng-app="myApp">
<div ng-view></div>
<script type="text/ng-template" id="/page.html">
My ID is: {{id}}
</script>
</div>
app.js
var app = angular.module('myApp', [])
.config(function($routeProvider) {
$routeProvider
.when('/page/:id', {templateUrl: '/page.html', controller: 'PageController'})
.otherwise({redirectTo:'/page/50'});
}).controller('PageController', function($scope, $routeParams) {
$scope.id = parseInt($routeParams.id);
});

Categories

Resources