Table sorting fix - javascript

I have data in a table coming from multiple json api links.
my code currently is
<script src="js/1.js"></script>
<script src="js/2.js"></script>
Above this is a table code. Allowing the table to be sorted. It only has <th> and <thead> tags.
The issue as it stands looks like this:
I'm wanting ideally the price field to be sorted. below is the inside of the JS files
1.js
$.ajax({
type : 'GET',
crossDomain : true,
dataType : 'json',
url : 'api link here',
success : function (json) {
//var json = $.parseJSON(data);
for(var i=0; i<json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].price;
var button = "<button class='redirect-button' data-url='LINK'>Compare</button>";
$("#tableid").append("<tbody><tr><td>"+section+"</td><td>"+no+"</td><td>"+price+"</td><td>"+button+"</td></tr></tbody>");
$("#tableid").find(".redirect-button").click(function(){
location.href = $(this).attr("data-url");
});
}
},
error : function(error){
console.log(error);
}
});
and here is the 2nd js file
$.ajax({
type : 'GET',
crossDomain : true,
dataType : 'json',
url : '2nd api',
success : function (json) {
//var json = $.parseJSON(data);
for(var i=0; i<json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].amount;
var button = "<button class='redirect-button' data-url='LINK'>Click Here</button>";
$("#tableid").append("<tbody><tr><td>"+section+"</td><td>"+no+"</td><td>"+price+"</td><td>"+button+"</td></tr></tbody>");
$("#tableid").find(".redirect-button").click(function(){
location.href = $(this).attr("data-url");
});
}
},
error : function(error){
console.log(error);
}
});
Now here is what i believe is the code to sort the js files in the table, Issue is I have no idea where to put it.
var sortTable = function(){
$("#tableid tbody tr").detach().sort(function(a,b){
//substring was added to omit currency sign, you can remove it if data-price attribute does not contain it.
return parseFloat($(a).data('price').substring(1))- parseFloat($(b).data('price').substring(1));
})
.appendTo('#tableid tbody');
};
And
for(var i=0; i<json.results.length; i++) {
....
}
sortTable();
I would use a tablesorter jquery plugin but i would rather not.

Since you're pulling data from two ajax requests, perhaps it will be better to store both results in one global array that you can sort and loop through to build your table in price order.
var resultsArray = new Array();
for (var i = 0; i < json.results.length; i++) {
resultsArray.push(json.results[i]);
}
resultsArray.sort(function(a,b) {
return a.price - b.price;
});
for (var i = 0; i < json.results.length; i++) {
//print your table here
var price = resultsArray[i].price;
//etc...
}
I fully demonstrated this in a fiddle

is it possible for you to take both of the json reponses, sort them in order by price, and then add them to the dom? This way you don't have to access the dom so much just to sort your data?
This would go something like this, if you're using jQuery. Basically once both of your ajax requests resolve you can do whatever with the data you have. Fromt here you can merge them, sort them, and then run your piece to populate the table.
var urlDatas = [];
$.when(
$.getJSON(someUrl, function(data) {
urlDatas.push(data);
}),
$.getJSON(someOtherUrl, function(data) {
urlDatas.push(data);
})
).then(function() {
//not completely sure if extend returns a value or just mutates, target.
finalData = $.extend(true, {}, urlDatas[0], urlDatas[1]);
//run a sort on that data
sortData(finalData);
//add it to your dom
insertData(finalData);
});

Related

Issues sending selected rows values into a controller MVC

I'm trying to send the selected rows into a controller when I click on the button with id="send". The issue is that when I tried to send other values( in this case a number and a string) with the selected rows values, the selected rows values is sending null to the controller but the number and the string aren't null in the controller parameters.
This is my javascript code that works fine if only i send the selected rows values:
$('#send').click(function () {
var items = {};
var grid = $('#grid').data('kendoGrid');
var selectedElements = grid.select();
for (var j = 0; j < selectedElements.length; j++) {
var item = grid.dataItem(selectedElements[j]);
items['grid[' + j + '].ParecidoCodigo'] = item.ParecidoCodigo;
}
$.ajax({
url: '#Url.Action("Index", "Busqueda")',
type: "POST",
async: false,
data: items,
success: function (result) {
console.log(result);
}
})
})
and this is my controller method action:
public ActionResult Index(MarcaParecido[] grid)
{ ... }
Everything works fine until now.But when I tried to send another values like this:
$('#send').click(function () {
var items = {};
var grid = $('#grid').data('kendoGrid');
var selectedElements = grid.select();
var enviarDest = $('#destinatario').val();
var marca = $('#numMarca').val();
for (var j = 0; j < selectedElements.length; j++) {
var item = grid.dataItem(selectedElements[j]);
items['grid[' + j + '].ParecidoCodigo'] = item.ParecidoCodigo;
}
$.ajax({
url: '#Url.Action("Index", "Busqueda")',
type: "POST",
async: false,
data: { items, marcas: marca, destinatario: enviarDest },
success: function (result) {
console.log(result);
}
})
})
The selected rows values is sending me null, but the others values aren't null
This is my controller now:
public ActionResult Index(MarcaParecido[] grid, string marcas, string destinatario)
{...}
I tried with JSON.stringify too but it doesn't work.
If items is a collection of the key/value pairs that you are sending to the server, add the two additional parameters to that, and then continue to send item the items object. MVC should read the "grid." items as the list of items in the collection (as you have working now), and see the other two parameters in the variables you have specified:
items["marcas"] = marca;
items["destinatario"] = enviarDest;
$.ajax({
.
.
data: items

fabric js load single objects to canvas from mysql database

I have a canvas that lives on top of a video. When a user pauses the video they are able to add fabricjs objects to the canvas. When an object is added to the canvas it is saved to a table in a mysql database as JSON.
When the user clicks a button it will query the mysql database for records and return via ajax the objects for each record in an array.
As it loops through this array I want fabricjs to render each object one at a time until all objects have been rendered.
I have tried using :
canvas.loadFromJSON(rData, canvas.renderAll.bind(canvas), function(o, object) {
fabric.log(o, object);
});
It will load all objects but clears the canvas before each load and will only display the last object.
I have tried the example here:
http://codepen.io/Kienz/pen/otyEz but cannot seem to get it to work for me. I have also tried http://jsfiddle.net/Kienz/bvmkQ/ but cannot see what is wrong.
So I have come to the experts! I appreciate all and any help. Thank you.
Here is my table in mysql wth 2 records:
CREATE TABLE IF NOT EXISTS `telestrations` (
`id_telestration` int(11) NOT NULL AUTO_INCREMENT,
`object` longtext NOT NULL,
PRIMARY KEY (`id_telestration`),
UNIQUE KEY `id_telestration` (`id_telestration`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=65 ;
--
-- Dumping data for table `telestrations`
--
INSERT INTO `telestrations` (`id_telestration`, `object`) VALUES
(63, '{"objects":[{"type":"i-text","originX":"left","originY":"top","left":161.05,"top":359.29,"width":69.3,"height":20.97,"fill":"#e6977e","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","fillRule":"nonzero","globalCompositeOperation":"source-over","text":"AAAAAA","fontSize":16,"fontWeight":"bold","fontFamily":"arial","fontStyle":"","lineHeight":1.16,"textDecoration":"","textAlign":"left","textBackgroundColor":"","styles":{"0":{"1":{},"2":{},"3":{},"4":{},"5":{}}}}],"background":""}'),
(64, '{"objects":[{"type":"i-text","originX":"left","originY":"top","left":463.68,"top":353.84,"width":69.3,"height":20.97,"fill":"#20f20e","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","fillRule":"nonzero","globalCompositeOperation":"source-over","text":"BBBBBB","fontSize":16,"fontWeight":"bold","fontFamily":"arial","fontStyle":"","lineHeight":1.16,"textDecoration":"","textAlign":"left","textBackgroundColor":"","styles":{"0":{"1":{},"2":{},"3":{},"4":{},"5":{}}}}],"background":""}');
Here is my php file:
$teles = Telestration::getTeleByVideo();
$objArray = array();
foreach($teles as $tele){
$obj = $tele->getValueEncoded('object');
$objArray[] = $obj;
}
echo json_encode($objArray);
Here is my JavaScript:
document.getElementById("get_json").onclick = function(ev) {
$.ajax({
url: 'getTelestrations.php',
data: dataString,
type: 'POST',
dataType:"json",
success: function(data){
for (var i = 0; i < data.length; i++) {
rData = data[i].replace(/"/g, '\"');
//Do something
canvas.loadFromJSON(rData, canvas.renderAll.bind(canvas), function(o, object) {
fabric.log(o, object);
});
}
}
});
}
Hello inside your success function use instead of canvas.loadFromJSON , the fabric.util.enlivenObjects() funtion, like this:
//inside the success function, you get the results data from the server and loop inside the items, allright if you have only one object but use loop for more.
results.data.forEach(function (object) {
var tmpObject = JSON.parse(object.table_data);
fabric.util.enlivenObjects([tmpObject], function (objects) {
var origRenderOnAddRemove = canvas.renderOnAddRemove;
canvas.renderOnAddRemove = false;
console.log(objects);
objects.forEach(function (o) {
canvas.add(o);
console.log(o);
});
canvas.renderOnAddRemove = origRenderOnAddRemove;
canvas.renderAll();
});//end enlivenObjects
});//end data.forEach
Hope this helps, good luck
I was able to figure out how to load each object. It turns that the json returned from my mysql was not "workable" for fabricjs. I had to clean my json and then the objects would load.
I only made changes to my javascript:
$.ajax({
url: 'getTelestrations.php',
data: dataString,
type: 'POST',
dataType:"json",
success: function(data){
for (var i = 0; i < data.length; i++) {
//clean results for json
json_result = data[i].replace(/"/g, '\"'); //remove quotes from entire result
json_clean = json_result.replace(/"objects"/, 'objects'); //remove quotes around first object
jsonObj = JSON.parse(JSON.stringify(json_clean)); // parse the entire result
jsonobj2 = eval('(' + jsonObj + ')');
// Add object to canvas
var obj = new fabric[fabric.util.string.camelize(fabric.util.string.capitalize(jsonobj2.objects[0].type))].fromObject(jsonobj2.objects[0]);
canvas.add(obj);
canvas.renderAll();
}
}
});

How to send JavaScript collection to PHP variable?

I am trying to send data from form to PHP file using JavaScript. PHP file pushes this data to database. For now, almost all works well but I have a problem with array from getElementsByClassName. After sending to database I can see only "Array" but no values of this array.
Here's a JS:
function przekaz_form($wejscie) {
var datas = document.formularz.datas.value;
var klient = document.formularz.firma.value;
var comment = document.formularz.comment.value;
var collect = document.getElementsByClassName($wejscie);
var datan = document.formularz.datan.value;
var items = new Array();
for(var i = 0; i < collect.length; i++) {
items.push(collect.item(i).value);
}
jQuery.ajax({
url: 'addtobase.php',
type: 'post',
data:{
devices: items,
datas: datas,
klient: klient,
comment: comment,
datan: datan
},
success: function(output) {
alert('Success');
}
});
}
One way to do this is:
$inputData = json_decode(file_get_contents('php://input'));
Once you have the $inputData variable you can access the data in the JSON by:
$devices = (!is_null($inputData) && property_exists($inputData, "devices")) ? strip_tags($inputData->{"devices"}) : 0;
You should also try to better format the JSON : http://json.org/example

Cant access Javascript multidimensional array

I have seen many of these questions on here but none seem to solve my problem. I have a multidimensional (nested) array which I am populating through query. I wish to send the final array over AJAX jQuery:
(function() {
var orderDetails = [];
orderDetails['retailer'] = [];
orderDetails['order'] = [];
db.transaction(function(qry){
qry.executeSql("SELECT * FROM retailers WHERE pending = '1' ", [], function(tx, results){
len = results.rows.length; //if rows.length, means retailer is pending so add details to array. If no length, means retailer exists
for (var i=0; i<len; i++){
console.log('start '+i+' loop in retailers qry');
orderDetails['retailer'][i] = [];
orderDetails['retailer'][i]['localID'] = results.rows.item(i).ID;
orderDetails['retailer'][i]['retailerName'] = results.rows.item(i).retailerName;
orderDetails['retailer'][i]['address'] = results.rows.item(i).address;
orderDetails['retailer'][i]['postcode'] = results.rows.item(i).postcode;
console.log('finish '+i+' loop in retailers qry');
}
}, function(err){console.log(err)})
}
This is how I am populating the array, and here is the AJAX request:
function(){
console.log('start orders qry success callback');
//alert(orderDetails['retailer'][0]['localID']);
var st = JSON.stringify(orderDetails['retailer']);
console.log(st);
$.ajax({//send retailer to server, bring back the ID of the retailer as it is on the server so we can insert it into the order
type: "POST",
cache: false,
//async: false,
url: "https://www.......processOrder.php",
data: { orderType: 'saved', orderDetails: st},
dataType: "json",
success: function(result){
}
})
});
When I log the above just before the ajax request, it returns [[],[],[],[],[],[],[],[],[],[],[]] so I know something is working, I just thought the whole contents of the object would be visible on the server side.
Also I have wrapped the whole thing in an anonymous function because I think this helps the array variable scope.
Change this orderDetails['retailer'][i] = []; to this orderDetails['retailer'][i] = {};
And if your item is not a function you want to call with parameter i, access it like this: results.rows.item[i].ID

Get JSON data from another page via JavaScript

I have a page where I want to add couple of controls
when I click on 1st control, I want my javascript to open particular JSONpage, gram the content and then output the content in specific <DIV id="one">. Then, when I select some of the elements in div id="one", I want The JavaScript to connect to another JSON page and get another array of data from there.
My question - how do I do the JSON part?
In other words, how do I get JavaScript version of:
$dataSet = json_decode(file_get_contents($url), true);
I am new to JavaScript and this thing takes so much time!!
Got this working
function getDates() {
jQuery(function($) {
$.ajax( {
url : "jsonPage.php",
type : "GET",
success : function(data) {
// get the data string and convert it to a JSON object.
var jsonData = JSON.parse(data);
var date = new Array();
var i = -1;
$.each(jsonData, function(Idx, Value) {
$.each(Value, function(x, y) {
if(x == 'date')
{
i = i + 1;
date[i] = y;
}
});
});
//output my dates; [0] in this case
$("#testArea").html(date[0]);
}
});
});
}

Categories