Json response as tooltip value lookup for a jquery sparklines graph - javascript

I'm trying to use a json response as the tooltipValueLookups parameter in a sparklines graph, without success. The tooltip just keeps showing 0:5 and 1:8 instead of Mulder:5 and Scully:8
It works perfectly if I just declare the variable agents with the exactly same json:
var agents = {"names":{"0":"Mulder", "1":"Scully"}}
But evrything goes south when I try to do it with the server response, as intended. Could anyone tell me please, what am I doing wrong?
var agents = $.ajax({
url : "/ajaxAgents",
type : "get",
dataType: 'json'
});
Response: {"names":{"0":"Mulder", "1":"Scully"}}
$("#mini-chart").sparkline([5,8], {
type: 'bar',
height: '30px',
barWidth: 6,
barSpacing: 2,
barColor: '#0aa699',
tooltipFormat: '<span style="color: {{color}}">●</span> {{offset:offset}}: {{value}}',
tooltipValueLookups:{offset:agents.names},
negBarColor: '#0aa699'});
Thanks in advance.
EDIT
After a lot of coffee and swearing, I finally got it to work. Not a very elegant solution, I must admit.
First, I had to change the server-side php function to return a string, rather than json.
Then in the ajax call:
var response = $.ajax({
url : "/ajaxAgents",
type : "get",
dataType: 'text',
global : false,
async : false,
success : function(data){return data;}
}).responseText;
Then, parse the response and filter it:
var agents = $.parseJSON(response);
var filteredNames = $.map(agents.names, function(el) {
return el;
});
And finally, the sparklines function:
$("#mini-chart").sparkline(agentsData, {
type: 'bar',
height: '30px',
barWidth: 6,
barSpacing: 2,
barColor: '#0aa699',
tooltipFormat: '<span style="color: {{color}}">●</span> {{offset:offset}}: {{value}}',
tooltipValueLookups:{offset:filteredNames},
negBarColor: '#0aa699'});
#Hüseyin: Thanks for your assistance, it was very helpful.

Filter json with $.grep
var filteredNames = $.map(agents.names, function(el, i) {
return el;
});
And use in your function like;
tooltipValueLookups:{offset: filteredNames}
You can see demo here: jsfiddle
Note: If you are returning string from server, you need to use;
var agents = jQuery.parseJSON(response);

Related

send an array per ajax to an python-server-script

I want to send all my names,values and labels of my form-elements when I klick on a button, I didnt make a submit-button, beause the I got them in a wrong order, so I make this in JavaScript:
$('#mybutton').click(function() {
m.modal('show');
var all=[];
$('textarea, select, input').each(function(index){
var label= $(this).parent().find('label').html();
var value= $(this).val();
var name= $(this).attr('name');
all.push([name,value,label]);
})
$.ajax({
dataType: "text",
url: "befund",
data: {
wert : all
},
success: function(data){
$('#mymodal').find('.modal-body').html(data);
}
})
});
in the python server-script (bottle) I try this:
#app.route('/web/befund')
def modalcontent() -> str:
x = request.query.wert[0][1]
print (x)
return('test')
the problem is that I see in the browser, that the right array is send but when I try to see one element of the array with "request.query.wert[0][1]" I only get a http-error 500 (internerl server error). Can anybody help me please?
You can use POST for this (and should, if this is sensitive data and your connection is secure).
However, you need to turn the data into a JSON string, then decode it on the server.
data: {
wert: JSON.stringify(all)
},
On the server:
wert = json.loads(request.params.wert);
print wert[0][1]
I think the wert it is the object on the server side. Try accesing data by `x=request.query.wert[0]
or
x=request.query['wert'][0]
Im not using python now, but it seems like right

pass data($post) to php file using javascript without callback

I need to pass data from HTML page to PHP page But without data callback ....
i'm used two method but One of them did not succeed
1)
$.ajax({
type: "POST",
url: 'phpexample.php',
data: {voteid: x },
success: function(data)
{
alert("success! X:" + data);
}
});
2)
$.post("getClassStudent.php",
{
},
function(data){
$("#div_id.php").html(data);
}
);
as i can understand, you just want to send info to a php script and don't need the response, is that right?
try this
$.post("phpexample.php", {voteid:x});
or simply remove the "succes" function from the equation if you feel more confortable using $.ajax instead of $.post
$.ajax({
type: "POST",
url: 'phpexample.php',
data: {voteid: x }
});
your fisrt example is correct, the second is not well formed.
more info:
http://api.jquery.com/jquery.post/
EDIT: to help you some more :)
<button type="button" id="element-id">click</button>
<button type="button" class="class-name">Click</button>
$(document).ready(function(){
//if you are marking ans element by class use '.class-name'
$(".class-name").click(function(){
$.post("getClassStudent.php");
});
//if marking by id element use '#id-name'
$("#element-id").click(function(){
$.post("getClassStudent.php");
});
});
be carefful with the markings, for debuggin try to use "console.log()" or "alert()" so you can see where is the problem and where the code crushes.
var formData = {
'voteid' : 'x',
};
$.ajax({
type : 'POST',
url : 'phpexample.php',
data : formData, // our data object
dataType : 'json',
encode : true
}).done(function(data) {
console.log(data);
});

single Ajax Post request not working in IE

I have some code that uses jquery to create dialogs from some hidden forms in my html:
$("#editdeletediv").load().dialog(
{ //Set options for the dialog here
title: 'Edit/Delete log',
modal: true,
autoResize:true,
maxWidth: 600,
minWidth: 500,
buttons: {
Delete: function(){
$('#confirmdelete').load().dialog(
{ //Set options for the dialog here
title: 'Confirm deletion',
modal: true,
autoResize:true,
maxWidth: 300,
minWidth: 250,
buttons: {
Yes: function(){
$.ajax({
url: 'removelog',
type: "POST",
data: { id: calEvent.id},
dataType: "json",
success:function(response){
window.location.href = response;
}
});
},
No: function(){
$(this).dialog('close');
}
}
});
},
Save: function(){
var input = $("<input>")
.attr("type", "hidden")
.attr("name", "id").val(calEvent.id);
$('#editdeleteform').append($(input));
var formdata = new FormData($("#editdeleteform")[0]);
$.ajax({
url: 'updatelog',
type: 'POST',
data: formdata,
async: false,
success: function (response) {
window.location.href = response;
},
cache: false,
contentType: false,
processData: false
});
}
}
});
This all works in chrome and firefox, but in IE it's a different matter.
The ajax post to 'updatelog' doesn't seem to work in IE but the post to 'removelog' does.
Does anyone know what might be the issue here, I think it might be the,
var formdata = new FormData($("#editdeleteform")[0]);
but I need that formdata variable as the fields I'm passing to the post might be different in the future (I might dynamically create more html elements), so I need a way to get everything from that form without hard coding it into my javascript
EDIT: figured out how to get a console open in internet explorer and now I know for sure it's the FormData where the problem is arising:
SCRIPT5009: 'FormData' is undefined
Does anyone know of an alternative that works in chrome, firefox and IE or does anyone know how I can work around this problem for IE?
EDIT: I decided it's more trouble than it's worth, this is for an intranet site solution so spending too much time on this would be a waste (I can just require my users to use specific browsers/versions if they want full functionality)
So I just did this:
if(typeof FormData !== 'undefined'){
var formdata = new FormData($("#editdeleteform")[0]);
}
else{
var formdata = {
'id' : calEvent.id,
'editdate' : $("#editdate").val(),
'editcomment' : $("#editcomment").val(),
'editworkhours' : $("#editworkhours").val(),
'editdoctorsnote' : ''
};
}
FormData isn't compatibile with ie 7-9 see: https://developer.mozilla.org/en-US/docs/Web/API/FormData
var formdata = $("#editdeleteform").serialize()
Try this to send form data to updatelog. This may helps you.
I decided it's more trouble than it's worth, this is for an intranet site solution so spending too much time on this would be a waste (I can just require my users to use specific browsers/versions if they want full functionality)
So I just did this:
if(typeof FormData !== 'undefined'){
var formdata = new FormData($("#editdeleteform")[0]);
}
else{
var formdata = {
'id' : calEvent.id,
'editdate' : $("#editdate").val(),
'editcomment' : $("#editcomment").val(),
'editworkhours' : $("#editworkhours").val(),
'editdoctorsnote' : ''
};
}

How to fetch JSON object though JavaScript or jQuery and generate dynamically content for multiple record through JavaScript or jQuery?

Understand already done process for single object and single data, which is working pretty cool.
1) output from the PHP Server encoded into JSON format.
JSON OUTPUT:
{"product_id":"1","sku":"FGDGE43","set":"4","type":"simple","categories":["2"],"websites":["1"],"type_id":"simple","name":"Honey","description":"Where sweetness belong.","short_description":"Sweetness.","weight":"100.0000","old_id":null,"news_from_date":null,"news_to_date":null,"status":"1","url_key":"hgjjhgjh","url_path":"hgjjhgjh.html","visibility":"4","category_ids":["2"],"required_options":"0","has_options":"0","image_label":"Honey","small_image_label":"Honey","thumbnail_label":"Honey","created_at":"2014-02-10 14:36:54","updated_at":"2014-02-19 11:37:07","country_of_manufacture":null,"price":"43.0000","group_price":[],"special_price":null,"special_from_date":null,"special_to_date":null,"tier_price":[],"minimal_price":null,"msrp_enabled":"2","msrp_display_actual_price_type":"4","msrp":null,"enable_googlecheckout":"1","tax_class_id":"0","meta_title":null,"meta_keyword":null,"meta_description":null,"is_recurring":"0","recurring_profile":null,"custom_design":null,"custom_design_from":null,"custom_design_to":null,"custom_layout_update":null,"page_layout":null,"options_container":"container2","gift_message_available":null,"0":{"file":"\/h\/o\/honey.jpg","label":"Honey","position":"1","exclude":"0","url":"http:\/\/127.0.0.1\/magento\/media\/catalog\/product\/h\/o\/honey.jpg","types":["image","small_image","thumbnail"]}}
2) Now
I can fetch above mentioned SINGLE JSON object through jQuery and dynamically change the content of the page.
$(document).ready( function() {
alert('bhoom : oh yea its coming');
$.ajax({
type: 'POST',
url: 'http://127.0.0.1/midserver.php',
data: 'id=testdata',
dataType: 'text',
cache: false,
success: function(data) {
var json = $.parseJSON(data);
$('#pname').html(json.name);
$('#pdesc').html(json.description);
$('#pprice').html(json.price);
$('#pweight').html(json.weight);
},
});
});
This is working fine.
Here come my Question
How can i fetch two or more object through JS or JQ and create dynamic elements though JS/JQ or any other mechanism and then put this data in dynamically generated elements.
i.e : for below mentioned JSON object ?
[{"product_id":"1","sku":"FGDGE43","set":"4","type":"simple","categories":["2"],"websites":["1"],"type_id":"simple","name":"Honey","description":"Where sweetness belong.","short_description":"Sweetness.","weight":"100.0000","old_id":null,"news_from_date":null,"news_to_date":null,"status":"1","url_key":"hgjjhgjh","url_path":"hgjjhgjh.html","visibility":"4","category_ids":["2"],"required_options":"0","has_options":"0","image_label":"Honey","small_image_label":"Honey","thumbnail_label":"Honey","created_at":"2014-02-10 14:36:54","updated_at":"2014-02-19 11:37:07","country_of_manufacture":null,"price":"43.0000","group_price":[],"special_price":null,"special_from_date":null,"special_to_date":null,"tier_price":[],"minimal_price":null,"msrp_enabled":"2","msrp_display_actual_price_type":"4","msrp":null,"enable_googlecheckout":"1","tax_class_id":"0","meta_title":null,"meta_keyword":null,"meta_description":null,"is_recurring":"0","recurring_profile":null,"custom_design":null,"custom_design_from":null,"custom_design_to":null,"custom_layout_update":null,"page_layout":null,"options_container":"container2","gift_message_available":null},[{"file":"\/h\/o\/honey.jpg","label":"Honey","position":"1","exclude":"0","url":"http:\/\/127.0.0.1\/magento\/media\/catalog\/product\/h\/o\/honey.jpg","types":["image","small_image","thumbnail"]}],{"product_id":"2","sku":"asdf654a6sd5f4","set":"4","type":"simple","categories":[],"websites":["1"],"type_id":"simple","name":"Butter","description":"Buttery Buttery Buttery","short_description":"Buttery Buttery ","weight":"100.0000","old_id":null,"news_from_date":null,"news_to_date":null,"status":"1","url_key":"butter","url_path":"butter.html","visibility":"4","category_ids":[],"required_options":"0","has_options":"0","image_label":"butter","small_image_label":"butter","thumbnail_label":"butter","created_at":"2014-02-25 11:35:49","updated_at":"2014-02-25 11:53:10","country_of_manufacture":null,"price":"100.0000","group_price":[],"special_price":null,"special_from_date":null,"special_to_date":null,"tier_price":[],"minimal_price":null,"msrp_enabled":"2","msrp_display_actual_price_type":"4","msrp":null,"enable_googlecheckout":"1","tax_class_id":"0","meta_title":null,"meta_keyword":null,"meta_description":null,"is_recurring":"0","recurring_profile":null,"custom_design":null,"custom_design_from":null,"custom_design_to":null,"custom_layout_update":null,"page_layout":null,"options_container":"container2","gift_message_available":null},[{"file":"\/b\/u\/butter.jpg","label":"butter","position":"1","exclude":"0","url":"http:\/\/127.0.0.1\/magento\/media\/catalog\/product\/b\/u\/butter.jpg","types":["image","small_image","thumbnail"]}]]
So,
what i've tried to create 'dynamic content and putting data in that' is here.
$(document).ready( function() {
alert('bhoom : oh yea its coming');
$.ajax({
type: 'POST',
url: 'http://127.0.0.1/test2.php',
data: 'id=testdata',
dataType: 'text',
cache: false,
success: function(data) {
// asumming that server returns more than one products
// in JSON Object.
// So iterate over this JSON Object through .each JQuery
// function.
var divHtml;
var productDiv = $("#productDetailsDiv");
//its reference
$(data).each(function(index, value) {
// Take Html of productTemplate Div in divHtml variable.
divHtml = $('#productsTemplate').html();
// Fill divHtml with values
divHtml.find('#pname').html(value['name']);
divHtml.find('#pdesc').html(value['description']);
divHtml.find('#pimage').html(value['url']);
divHtml.find('#pprice').html(value['price']);
divHtml.find('#pweight').html(value['weight']);
// Add divHtml to productDiv
$("#productDetailsDiv").children().add(divHtml);
// Loop for next value in data
});
},
});
});
So, Am I making mistake to fetching complicated JSON object or there is a code went wrong with jQuery?
Any help or suggestion will be appreciated.
Regards.
try the block with query $.each
$.each(data, function(index, item) {
$('#pname').html(item.name);
$('#pdesc').html(item.description);
$('#pprice').html(item.price);
$('#pweight').html(item.weight);
});
here pname, pdesc... etc,. you need to update with dynamic elements
You can user jquery each function to achieve this:
$(document).ready( function() {
alert('bhoom : oh yea its coming');
$.ajax({
type: 'POST',
url: 'http://127.0.0.1/midserver.php',
data: 'id=testdata',
dataType: 'text',
cache: false,
success: function(data) {
var json = $.parseJSON(data);
$.each(json, function(index, element){
$('#pname').html(element.name);
$('#pdesc').html(element.description);
$('#pprice').html(element.price);
$('#pweight').html(element.weight);
});
},
});
});
Thanks for your suggestion.
I find out that the JSON object i'm getting through PHP server as an output, is in multi-dimensional array. So for the shake of the simplicity, at server side, we have to generate one-dimensional array of JSON object as an output to be fetched and manipulated at client-side.
Now We can do stuff like generating dynamic content on through JS/JQ on HTML page and render(fill-in) the data with the same.
Regards.

JQGrid with dynamic column: cellattr does not work

I have built my JQGrid table with dynamic column in this way (ajax call) :
$.ajax(
{
type: "POST",
url: "Scripts/GetSummaryInformation.php",
data: { domain: "<?php echo $domain; ?>", etc. },
dataType: "json",
success: function(result)
{
var colD = result.gridModel;
var colN = result.colNames;
var colM = result.colModel;
var colSpan = result.colSpan;
jQuery("#FinalRatingList<?php echo $domain; ?><?php echo $companyID; ?>").jqGrid({
jsonReader : { repeatitems: false, root:"dataset", cell: "cell", id: "0" },
url: 'Scripts/GetSummaryInformation.php',
datatype: 'json',
mtype: 'POST',
postData : { domain: "<?php echo $domain; ?>", etc.},
datastr : colD,
colNames:colN,
colModel :colM,
height: 'auto',
pager: jQuery('#FinalRatingListPager'),
caption:"Final Rating",
loadComplete: function(data){
console.info("FinalRatingList Success");
notyMsg ("loadComplete", "info");
},
...
and it works fine :)
When I create a column in the PHP file like using the cellattr
$response->colModel[$colMod++] = array ('name'=>'DIR'.$projectName, 'index'=>'DIR'.$projectName, 'width'=>'40', "cellattr"=>"rowSetting" );
there is absolutely no effect at all.
Even when I put code directly in the cellattr like this
"cellattr"=>"function( rowId, value, rowObject, colModel, arrData) { return ' style=\"background:orange\"'}" );
Does anyone have faced or know the solution to this problem?
Thanks in advance for your collaboration
UPDATE
Thanks Oleg. It worked greatly for cellattr and for template (which is a really good advice).
For those who are interested here is the code:
var rowSetting = function (rowId, val, rawObject, cm) {
return 'style="background-color: orange;';
};
var cellattrMapping = {
"rowTemplate": rowTemplate
};
var rowTemplate = {
width:120,
cellattr: rowSetting
};
AJAX CALL
success: function(result)
{
...
for (i=0; i<colM.length; i++) {
cm = colM[i];
if (cm.hasOwnProperty("template") && cellattrMapping.hasOwnProperty(cm.template))
{
cm.template = cellattrMapping[cm.template];
}
It seems that what you do looks like you set cellattr to string value cellattr: "rowSetting" instead of initialysing it to the pointer of function. The problem is there are some restrictions in the data which you can send as JSON. It supports strings, numbers, boolean, arrays and objects, but you can's send functions as part of JSON data.
One can suggest many workarounds for the problem. For example you can create JavaScript code with some cellattr functions which you use. You can place all the cellattr functions which you need in one object: your custom cellattr "string to functions mapping". Inside of success callback you can examine result.colModel items for cellattr property. If you found cellattr property you should just replace the string value to the corresponding function reference.
In the old answer I described more detailed very close solution. You can use the same approach for cellattr.
More better way in my opinion would be to use template attribute of colModel more active (see the old answer). You will have the same problem as before, but you could provide common templates which you use in different grids and post first string values as the value of template attribute of colModel. Then you could replace the value to JavaScript object which hold all required implementation details. The main advantage of usage column templates is sharing common code over multiple grids. The information in colModel become smaller and more readable. The templates could be easy modified.

Categories

Resources