jqGrid binary img wont show up - javascript

I use a standard function to retrieve an image within the system, as we have the binary in the database, this works good throughout the whole system.
Currently implementing jqGrid and have some issues to use the current structure as images don't show up and the jquery structure ($obj = $("<div>");) is not useable.
Now I try to implement to get the binary image, however it won't show up, when using a static url it works and image data is being retrieved.
$.extend($.fn.fmatter, {
getBinairy: function (cellValue, options) {
//var object = $();
var width = 50;
var html = "";
getImage(cellValue).success(function (data) {
$.each($.parseJSON(data.d), function (idx, obj) {
p_image = obj.img;
p_type = obj.type;
p_width = obj.width;
p_height = obj.height;
});
var _width = width / p_width;
var _height = _width * p_height;
html = "<img src='data:" + p_type + ";base64," + p_image + "' />";
//object = $("<img/>", {
// src: "data:" + p_type + ";base64," + p_image,
// width: width,
// height: _height
//});
//object.append($img);
});
//var html = "<img src='img/test/20131027_132450.jpg' />";
return html;
},
As far I think the fn is loading the "html" too fast, I can't understand other reason, however have no idea how to avoid this.
Any help?
---UPDATE---
var ip = "";
var station = "";
return $.ajax({
type: "POST",
url: "services/general.asmx/SendBinairy",
data: JSON.stringify({ session: 'ed6d1cc6-82f9-46e8-91bb-eae341a771cf', ip: ip, station: station, id: id }), ///, _filter: JSON.stringify(_json) }),
contentType: "application/json; charset=utf-8",
dataType: "json",
loaderror: function (xhr, status, error) {
},
success: function (data) { }
});
---UPDATE---
"dataset": [
{
"id": 5,
"suffix_type_id": 0,
"sexe_type_id": 1146,
"first_name": "Varvara",
"middle_name": "",
"last_name": "D",
"full_name": "Varvara D",
"company_name": "",
"nickname": "",
"birthday": "1983-12-18",
"age": 31,
"language_type_id": 6,
"relation_type_id": 0,
"job_status_type_id": 404,
"nationality_type_id": 0,
"last_online": "",
"last_online_app_id": 0,
"profile_image": 24,
"profile_rating": 7.000,
"number_contacts": 0,
"number_applications": 0,
"address_id": 0,
"address_1": null,
"address_2": null,
"address_3": null,
"number": 0,
"add": null,
"postal_code": null,
"city": null,
"city_type_id": 0,
"latitude": null,
"longitude": null,
"state": null,
"state_type_id": 0,
"country_type_id": 0,
"address_type_id": 0,
"image": [
{
"file_id": 24,
"binary": "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAIBAQEBAQIBAQECAgICAgQDAgICAgUEBAMEBgUGBgYFBgYGBwkIB
And this is how I add the data to the jqGrid
$("#" + grid_id).jqGrid({
loadonce: true,
type: "POST",
url: "services/general.asmx/HelloWorld",
postData: { q: session },
datastr: colD,
contentType: "application/json; charset=utf-8",
datatype: "jsonstring",
colModel: colM,
rowNum: 10,
rowList: [10, 20, 30],
pager: '#' + grid_id,
sortname: 'id',
viewrecords: true,
sortorder: "desc",

The function getImage is undefined in your code, but I still think that you've chosen wrong way for getBinairy formatter. I suppose that you makes asynchronous Ajax call to the server inside of the formatter. So the function getBinairy returns "" (the initial value of html variable).
I recommend you to change the format of cellValue - the format of data for the column which returned by filling the main grid. For example the data could be JSON encoded object {src:.., width:... , height:... } or {mimeType: ..., charset: ..., base64: ..., width: ... , height: ...} or some other. It's important just that the input data should be full and the formatter will be just produce <img> based on the data without any Ajax calls.

Related

JavaScript Read response - JSON - FaceAPI

I have this JSON response i need to get the values of some elements inside this response.
The values i want to display is the value of "makeup" which has to elements in it which are, "eyemakeup" & "lipmakeup"
i want to display it in an alert / or textbox.
[
{
"faceId": "90c30c46-2a51-4754-bff4-5079caf7e322",
"faceRectangle": {
"top": 91,
"left": 101,
"width": 121,
"height": 121
},
"faceAttributes": {
"smile": 0,
"headPose": {
"pitch": 0,
"roll": -0.8,
"yaw": -2.3
},
"gender": "male",
"age": 30.3,
"facialHair": {
"moustache": 0.1,
"beard": 0.5,
"sideburns": 0.3
},
"glasses": "NoGlasses",
"emotion": {
"anger": 0.013,
"contempt": 0.003,
"disgust": 0,
"fear": 0,
"happiness": 0,
"neutral": 0.983,
"sadness": 0.001,
"surprise": 0
},
"blur": {
"blurLevel": "medium",
"value": 0.28
},
"exposure": {
"exposureLevel": "goodExposure",
"value": 0.61
},
"noise": {
"noiseLevel": "medium",
"value": 0.39
},
"makeup": {
"eyeMakeup": false,
"lipMakeup": true
},
"accessories": [],
"occlusion": {
"foreheadOccluded": false,
"eyeOccluded": false,
"mouthOccluded": false
},
"hair": {
"bald": 0.02,
"invisible": false,
"hairColor": [
{
"color": "brown",
"confidence": 1
},
{
"color": "black",
"confidence": 0.78
},
{
"color": "blond",
"confidence": 0.23
},
{
"color": "other",
"confidence": 0.13
},
{
"color": "red",
"confidence": 0.09
},
{
"color": "gray",
"confidence": 0.03
}
]
}
}
}
]
The below is the javascript i have used so far and it is not giving me the correct values.
<script type="text/javascript">
function processImage() {
var subscriptionKey = "mysubkey";
var uriBase = "https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect";
// Request parameters.
var params = {
"returnFaceId": "true",
"returnFaceLandmarks": "false",
"returnFaceAttributes": "age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise",
};
// Display the image.
var sourceImageUrl = document.getElementById("inputImage").value;
document.querySelector("#sourceImage").src = sourceImageUrl;
// Perform the REST API call.
$.ajax({
url: uriBase + "?" + $.param(params),
// Request headers.
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", subscriptionKey);
},
type: "POST",
// Request body.
data: '{"url": ' + '"' + sourceImageUrl + '"}',
})
.done(function(data) {
// Show formatted JSON on webpage.
$("#responseTextArea").val(JSON.stringify(data, null, 2));
$("#demo2").val(this.responseText);
var data =[JSON.stringify(data, null, 2)];
var json = JSON.parse(data);
alert(json["eyeMakeup"]);
})
.fail(function(jqXHR, textStatus, errorThrown) {
// Display error message.
var errorString = (errorThrown === "") ? "Error. " : errorThrown + "
(" + jqXHR.status + "): ";
errorString += (jqXHR.responseText === "") ? "" :
(jQuery.parseJSON(jqXHR.responseText).message) ?
jQuery.parseJSON(jqXHR.responseText).message :
jQuery.parseJSON(jqXHR.responseText).error.message;
alert(errorString);
});
};
</script>
First add contentType:"json" your $.ajax configuration,
Then you don't need to parse data to json since it's already json type
So remove this line.
var data =[JSON.stringify(data, null, 2)];
As per your json you added to question you receive a array of object
To get data from first object
Try this :
For eyeMakeup use :
data[0].faceAttributes.makeup.eyeMakeup
and for lipMakeup use
data[0].faceAttributes.makeup.lipMakeup
Or you can loop through your result data if you want to access multiple object data
$.each(data,function(obj,function(){
console.log(obj.faceAttributes.makeup.eyeMakeup);
console.log(obj.faceAttributes.makeup.lipMakeup);
})
$.ajax( {
url:'data.php',
data:{
'a' : 1,
'b': 2
},
type:'post',
cache:false,
dataType:'json',
success:function(data) {
do something...
},
error : function() {
do something
}
});
try use ajax like up above

Create datatable in js via json data in a variable?

now I encounter a problem. I want to use ajax to show a datatable via using data coming from sql server database. Current state is I have used ajax to call a Handler.ashx to connect sql server and convert the data to json (using newtonsoft.json). In ajax, all json data has been recevied from Handler.ashx and stored in a variable "msg" which could be successfully showed on page. I want to put this "msg" into a datatable but failed all the time. I tried almost all methods online to set the datatable but still give different errors. I want to create a datatable in js and fill in my json data. But the result is either null or no data available in table.
Here is the codes and json data looks like.
js:
$(document).ready(function () {
$("#eventsButton").click(function () {
$.ajax({
type: "POST",
url: "../Handler.ashx",
//contentType: "application/json",
data: { postcode: $("#eventsPostcodeTextbox").val() },
cache: false,
success: function (msg) {
//for (var i in msg) {
// $("#eventGrid").append(msg[i]);
//}
//var jsonStr = JSON.stringify(msg);
document.getElementById("result").innerHTML = msg;
$('#eventtable').dataTable({
//"paging": false,
//"searching": false,
//"retrieve": true,
//"bProcessing": true,
//"data": msg.data,
//"datatype": "JSON",
//"ajax": "HandlerAll.ashx",
//"aaData": JSON.parse(msg),
//"ajax":
//"dataSrc":virtualTable
//"aoColumns": [
// { "mData": "ID" },
// { "mData": "FESTIVAL" },
// { "mData": "SUBURB" },
// { "mData": "POSTCODE" },
// { "mData": "WEBSITE" },
// { "mData": "DESCRIPTION" }
// ]
});
},
error: function (data) {
alert("Server error.");
}
})
});
});
json data (the size depends on the search condition, the table columns should have "ID","Festival" and so on, but no "virtualTable"):
{ "virtualTable": [ { "ID": "1", "FESTIVAL": "Antipodes Festival", "SUBURB": "Lonsdale Street, Melbourne", "POSTCODE": "3000", "WEBSITE": "http://www.antipodesfestival.com.au/", "DESCRIPTION": "The greek precinct in melbourne cbd will transform into a huge, free street festival with the hosting of the antipodes lonsdale street festival which will hold sway from 14 february 2015 to 15 february 2015." }, { "ID": "5", "FESTIVAL": "Boite Singers Festival", "SUBURB": "Victoria", "POSTCODE": "3000", "WEBSITE": "http://boite.com.au/index.php", "DESCRIPTION": "The boite singers festival brings you four days of vocal inspiration and sheer fun on the second weekend of january each year." } ] }
Since you get a JSON as reponse, I would try to convert it to JSON object, take the virtualTable part that it is a set of records in JSON and convert it to an array to add it to my table.
$(document).ready(function () {
$("#eventsButton").click(function () {
$.ajax({
type: "POST",
url: "../Handler.ashx",
// dataType: "json",
data: { postcode: $("#eventsPostcodeTextbox").val() },
success: function (msg) {
var jdata = $.parseJSON(msg);
jdata = jdata.virtualTable;
if (jdata.length != 0) {
var array_data = [];
var temp_array = [];
$(jdata).each(function(key, value) {
temp_array = [];
temp_array = [value.ID,
value.FESTIVAL,
value.SUBURB,
value.POSTCODE,
value.WEBSITE,
value.DESCRIPTION
];
array_data[array_data.length] = temp_array;
});
$('#eventtable').dataTable().fnAddData(array_data);
$('#eventtable').dataTable().fnDraw();
},
error: function (data) {
alert("Server error");
}
SOLUTION
Use the code below to initialize the table:
$('#eventtable').dataTable({
data: msg.virtualTable,
columns: [
{ data: "ID" },
{ data: "FESTIVAL" },
{ data: "SUBURB" },
{ data: "POSTCODE" },
{ data: "WEBSITE" },
{ data: "DESCRIPTION" }
]
});
DEMO
See this jsFiddle for code and demonstration.

C# ListItemCollection to JSON, while keeping values and text items

I have created a web service (asmx file) that returns a serialized ListItemCollection with the following code.
public string getStates(string Country)
{
ListItemCollection lic = DBInterface.GetStates(Country);
var serialized = JsonConvert.SerializeObject(lic);
return serialized;
}
I call the web service via javascript when a user selects a country from a dropdown list using the following code.
//ajax function that uses web services to get states
function GetStates(val)
{
$.ajax({
type: "POST",
url: "/WebServices/getServerData.asmx/getStates",
data: JSON.stringify({Country: val}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#ddlState").empty();
var parsed = JSON.parse(data.d);
for (var i = 0; i < parsed.length; i++) {
$("#ddlState").append("<option value='" + parsed[i] + "'>" + parsed[i] + "</option>");
}
},
error: function (data) {
alert(data.status + " " + data.statusText);
}
});
}
The issue is that I want to also keep not only the ListItemCollection text, but also it's value. However the "JsonConvert.SerializeObject only returns the text items. Can someone help to return the value and text so that I can populate the dropdown via javascript?
Thanks!
One thing you can use the JavaScriptSerializer() in System.Web.Script.Serialization:
ListItemCollection lic = new ListItemCollection() {
new ListItem("Display Text", "val1"),
new ListItem("Display Text 2", "val2"),
};
var ser = new JavaScriptSerializer();
var serialized = ser.Serialize(lic);
Results in (I took the liberty to format) :
[
{
"Attributes": {
"Keys": [],
"Count": 0,
"CssStyle": {
"Keys": [],
"Count": 0,
"Value": null
}
},
"Enabled": true,
"Selected": false,
"Text": "Display Text",
"Value": "val1"
},
{
"Attributes": {
"Keys": [],
"Count": 0,
"CssStyle": {
"Keys": [],
"Count": 0,
"Value": null
}
},
"Enabled": true,
"Selected": false,
"Text": "Display Text 2",
"Value": "val2"
}
]

WoW Armory APi - Can't get Title

Hello I'm trying to pull my characters title from the Warcraft Armory but I don't get any returned results. My code is as follows with my character name being replaced with my actual character name .
HTML
<li>Title Prefix: <span id="title">Test</span>
Javascript
$(window).load(function getSite(){
$.ajax({
url: "http://eu.battle.net/api/wow/character/server/character?fields=titles&jsonp=GoGet",
type: 'GET',
dataType: 'jsonp',
});
}
);
function GoGet(data) {
$("#title").html(data.titles.name)
;}
The api documentation shows the json items for "titles" as follows:
{
"achievementPoints": 675,
"battlegroup": "Test Battlegroup",
"calcClass": "f",
"class": 10,
"gender": 1,
"lastModified": 1348187981118,
"level": 90,
"name": "Peratryn",
"race": 25,
"realm": "Test Realm",
"thumbnail": "test-realm/1/1-avatar.jpg",
"titles": [
{
"id": 285,
"name": "%s, Savior of Azeroth",
"selected": true
}
]
}
Where am I going wrong?
Not being a WOW player myself, I'll hazard one guess:
$(window).load(function getSite(){
$.ajax({
url: "http://eu.battle.net/api/wow/character/server/character?fields=titles&jsonp=GoGet",
type: 'GET',
dataType: 'jsonp',
success: UpdateTitle
});
}
);
function UpdateTitle(response) {
if (response.titles) {
for (var i = 0; i < response.titles.length; i++) {
if (response.titles[i].selected === true) {
$("#title").html(response.titles[i].name);
break;
}
}
}
}
What this is doing is calling UpdateTitle after a successful XHR response from your provided URL. This function will loop through each title and update your #title element with the FIRST selected: true title found in the json response.

Knockout.js mapping plugin how to update data

The following code will fetch and bind the JSON data correctly to the view but when I GET updated data the view will not update. The data has changed but the view doesn't update. Any ideas what I'm doing wrong? I have trouble understanding how the mapping plugin works.
jQuery(document).ready(function() {
setInterval(LeaderboardViewModel, (10 * 500));
function LeaderboardViewModel() {
var self = this;
this.ArrayOfPlayers = ko.mapping.fromJS([]);
$.ajax({
type: 'GET',
url: 'http://localhost:5500/leaderboard/',
context: this,
success: function(data) {
self.SuccessfullyRetrievedModelsFromAjax(data);
},
dataType: 'json'
});
this.SuccessfullyRetrievedModelsFromAjax = function(data) {
var array = $.map(data.leaderboard, function(value, index) {
return [value];
});
console.log(array);
ko.mapping.fromJS(array, {}, self.ArrayOfPlayers);
};
}
ko.applyBindings(new LeaderboardViewModel());
});
The following HTML renders the data correctly when I load the page:
<tbody data-bind="foreach: ArrayOfPlayers">
EDIT: When I load the page it works correctly. the set interval part doesn't work.
GET data:
{
"leaderboard": {
"1": {
"deaths": 52,
"game_count": 13,
"game_defeats": 0,
"game_deserts": 0,
"game_draws": 0,
"game_wins": 13,
"id": 2,
"kills": 78,
"level": 8,
"rank": 1,
"xp": 3260
},
"10": {
"deaths": 78,
"game_count": 13,
"game_defeats": 13,
"game_deserts": 0,
"game_draws": 0,
"game_wins": 0,
"id": 1,
"kills": 52,
"level": 5,
"rank": 10,
"xp": 1570
},
}
EDIT 2: no console errors.
That's because you use keyword 'new' for applyBinding, but set timeout to function definition.
It must work in this way:
jQuery(document).ready(function() {
function LeaderboardViewModel() {
var self = this;
this.ArrayOfPlayers = ko.mapping.fromJS([]);
this.SuccessfullyRetrievedModelsFromAjax = function(data) {
var array = $.map(data.leaderboard, function(value, index) {
return [value];
});
console.log(array);
ko.mapping.fromJS(array, {}, self.ArrayOfPlayers);
};
self.UpdateMappings = function(){
$.ajax({
type: 'GET',
url: 'http://localhost:5500/leaderboard/',
context: this,
success: function(data) {
self.SuccessfullyRetrievedModelsFromAjax(data);
},
dataType: 'json'
});
};
}
var viewModel = new LeaderboardViewModel();
setInterval(viewModel.UpdateMappings, (10 * 500));
ko.applyBindings(viewModel);
});

Categories

Resources