Parse JSON in Jquery with an API - javascript

I am trying to cancel all my listings on Bitskins, but they have a weird system where each listing is unique, even if its for the same item. Meaning my 88 pages of listings is an absolute pain to remove.
So I thought of going the autohotkey route, but my end goal is to actually use the API to create specific listings. So I wrote a little test script/link.
https://bitskins.com/api/v1/cancel_buy_order/?api_key=myapikey&code=mycode&buy_order_id=995544
It worked. I proceeded to make a html with a javascript linked to it, but to spam the link 8 times a second with a decreasing number of id ultimately did not work. The browser would just crash.
Then I realized I can make a little script and run it on the site.
var id = 995544;
function loop() {
setTimeout(function () {
id--;
$.ajax({
url: '/api/v1/cancel_buy_order',
type: 'post',
data: {
api_key: $('#apiKey').text(),
buy_order_id: id
},
});
loop();
}, 1000);
}
loop();
While this works, it would take me 11.5 days to remove all listings. Partially because the delay is 1 second as opposed to 1000/8. (The api only allows 8 request a second.) But the biggest reason would be because it attempts to remove listings that don't even exist.
What I mean by this is, Each by listing has a random increment after the last one (e.g. 994488 -> 994502 -> 994503 and so on).
I needed a way to find the buy order id, and then use it in the second code I put here.
var id = (function () {
var id = null;
$.ajax({
'async': false,
'global': false,
'url': '/api/v1/get_active_buy_orders',
type: 'get',
data: {
api_key: 'myapikey',
code: 'mycode',
},
dataType: 'json',
success: function (data){
id = data
}
});
return id;
console.log(id);
})();
This thankfully works, but unfortunately it does not parse the
"data" : {
"orders" : [
parts of the JSON.
While I would love not to ask how to parse the JSON on here and find the answer for myself, I'm either googling the wrong thing, or am too dumb to understand how to do it.
So my question is, how would I parse JSON in JQuery?
{
"status" : "success",
"data" : {
"orders" : [
{
"buy_order_id" : 503154,
"market_hash_name" : "P2000 | Pulse (Field-Tested)",
"price" : "0.03",
"suggested_price" : "0.14",
"state" : "LISTED",
"created_at" : 1454390518,
"updated_at" : 1454390518,
"settled_with_item" : null
},
],
"page" : 88
}
}

if you want to get all buy_order_ids from JSON try the following snippet
x = {
"status": "success",
"data": {
"orders": [{
"buy_order_id": 503154,
"market_hash_name": "P2000 | Pulse (Field-Tested)",
"price": "0.03",
"suggested_price": "0.14",
"state": "LISTED",
"created_at": 1454390518,
"updated_at": 1454390518,
"settled_with_item": null
}, {
"buy_order_id": 502154,
"market_hash_name": "P2000 | Pulse (Field-Tested)",
"price": "0.03",
"suggested_price": "0.14",
"state": "LISTED",
"created_at": 1454390518,
"updated_at": 1454390518,
"settled_with_item": null
}, ],
"page": 88
}
}
var ids = x.data.orders.map(function(d) {
return d.buy_order_id
})
document.write('<pre>' + JSON.stringify(ids, 0, 4) + '</pre>')

Related

Server side pagination in KTDatatable (Metronic)

I am new to KTDatatable in Metronic.
I am trying to use server side pagination in Metronic dashboard, and I am parsing the data in a KTDatatable, but I can't find a way to parse the returned data from the API and to view number of pages and each page URL.
The code that I was able to write so far is:
data: {
type: 'remote',
source: {
read: {
url: dataURL,
method: 'GET',
contentType: 'application/json',
map: function(data) {
var cards = data.cards.data;
var currentPage = data.cards.current_page;
var lastPage = data.cards.last_page;
return cards;
}
},
},
pageSize: 10,
serverPaging: true,
},
In this code I was able to get the first ten records but:
1- I wasn't able to parse them the way I want in the table.
2- I wasn't able to show the pages number nor calling the API for the second page or the (x) page I want.
These are the things I want to do.
Thanks in advance.
You can go back to the end of the KT-Datatable documentation to find most of answers you want KT-Datable documentation, but I am gonna explain more hoping it will be more clear.
So the returned value from the API (Json) should look have two main objects meta and data, and it looks something like this:
{
"meta": {
"sort": "desc",
"field": "IssueName",
"page": 1,
"pages": 2,
"perpage": "10",
"total": 11
},
"data": [
{
"IssueName": "******",
"CardNumber": "******"
},
{
"IssueName": "******",
"CardNumber": "******"
}
]
}
And after getting the values of the response from the API you should only return the data object to be parsed by the datatable so the map function should look something like this:
map: function(data) {
return data.data;
}
and it will process the meta data itself.
To parse the data into the columns you should use the same key name of the data in column definition array, so in my example I used it like this:
columns: [
{
field: 'IssueName',
title: columnsTitles.issue,
type: 'string',
},
{
field: 'CardNumber',
title: columnsTitles.card_number,
type: 'string',
},
]
And every time the datatable calls the API it will send more data that will help you give the right response, the data will be on a shape of an array (The field name should be the same as the key):
[
"pagination" => array:4 [
"page" => "1"
"pages" => "2"
"perpage" => "10"
"total" => "11"
],
"sort" => array:2 [
"field" => "IssueName"
"sort" => "desc"
],
]
The sent data is related with the pagination and sorting type you have to get from the API, and you can also add filters and they will be stored in the array in the "query" field, and you can handle them in the backend.

Unexpected end of JSON input whilr trying to post it to the sever

Whenever I am trying to send a JSON object to server it gives me this particular error.
This is my Javascript code where I send the above JSON object to the action class but getting this error:
error: [object Object] status: parsererror er:SyntaxError: Unexpected end of JSON input
I need to understand what should be my JSON format? Is it OK or are changes required?
function openLOV(obj) {
var requestData = {
objId : "productLOV",
attributes : [ {
label : "URL_ID",
column : "URL_ID",
visible : "N"
}, {
label : "URL",
column : "URL",
visible : "Y"
}],
searchKey : "obj.value",
queryKey : "SQL_GET_PRODUCT",
callback : "cb"
};
var requestJSONData = JSON.stringify(requestData);
alert(requestJSONData);
var encrUrl = crcEncodeUrl("/EPSWeb/util/lovAction.do?mode=init&element="+obj.id);
$.ajax({
type : "POST",
url : encrUrl,
dataType: 'json',
contentType : "application/json",
data : requestJSONData,
success : function(response) {
$("#_lov_modal").remove();
createLOVModal();
$("#lovContent").html(response);
$("#btnLOVModal").click();
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
}
});
}
Its a data issue in the JSON you are sending to server,
in your variable requestData you need to add double quotes to the key fields, that makes the JSON valid. As mentioned below.
var requestData = {
"objId": "productLOV",
"attributes": [{
"label": "URL_ID",
"column": "URL_ID",
"visible": "N"
},{
"label": "URL",
"column": "URL",
"visible": "Y"
}],
"searchKey": "obj.value",
"queryKey": "SQL_GET_PRODUCT",
"callback": "cb"
}
This would work.

MongoDB : Map Reduce : Create one sub-document from another one

I have a mongodb collection which has documents like this :
{
"_id" : ObjectId("safdsd435tdg54trgds"),
"startDate" : ISODate("2013-07-02T17:35:01.000Z"),
"endDate" : ISODate("2013-08-02T17:35:01.000Z"),
"active" : true,
"channels" : [
1, 2, 3, 4
],
}
I want to convert this to something like this :
{
"_id" : ObjectId("safdsd435tdg54trgds"),
"startDate" : ISODate("2013-07-02T17:35:01.000Z"),
"endDate" : ISODate("2013-08-02T17:35:01.000Z"),
"active" : true,
"channels" : [
1, 2, 3, 4
],
"tags" :[
{
"name": one
"type": channel
},
{
"name": two
"type": channel
},
{
"name": three
"type": channel
},
{
"name": four
"type": channel
}
]
}
I already have a mapping of what 1,2,3,4 mean. Just for the sake of simplicity I put them as their alphabetical format. the values could be different, but they're static mappings.
You seem to be trying to do this update without a big iteration of your collection, So you "could" do this with mapReduce, albeit in a very "mapReduce way" as it has it's own way of doing things.
So first you want to define a mapper that encapsulates your current document :
var mapFunction = function (){
var key = this._id;
var value = {
startDate: this.startDate,
endDate: this.endDate,
active: this.active,
channels: this.channels
};
emit( key, value );
};
Now here the reducer is actually not going to be called as all the keys from the mapper will be unique, being of course the _id values from the original document. But to make the call happy:
var reduceFunction = function(){};
As this is a one to one thing this will go to finalize. It could be in the mapper, but for cleanliness sake
var finalizeFunction = function (key, reducedValue) {
var tags = [
{ name: "one", type: "channel" },
{ name: "two", type: "channel" },
{ name: "three", type: "channel" },
{ name: "four", type: "channel" }
];
reducedValue.tags = [];
reducedValue.channels.forEach(function(channel) {
reducedValue.tags.push( tags[ channel -1 ] );
});
return reducedValue;
};
Then call the mapReduce:
db.docs.mapReduce(
mapFunction,
reduceFunction,
{
out: { replace: "newdocs" },
finalize: finalizeFunction
}
)
So that will output to a new collection, but in the way that mapReduce does it so you have this:
{
"_id" : ObjectId("53112b2d0ceb66905ae41259"),
"value" : {
"startDate" : ISODate("2013-07-02T17:35:01Z"),
"endDate" : ISODate("2013-08-02T17:35:01Z"),
"active" : true,
"channels" : [ 1, 2, 3, 4 ],
"tags" : [
{
"name" : "one",
"type" : "channel"
},
{
"name" : "two",
"type" : "channel"
},
{
"name" : "three",
"type" : "channel"
},
{
"name" : "four",
"type" : "channel"
}
]
}
}
So all your document fields other than _id are stuck under that value field, so that's not the document that you want. But that is how mapReduce works.
If you really need to get out of jail from this and are willing to wait a bit, the upcoming 2.6 release has added an $out pipeline stage. So you "could" transform the documents in your new collection with $project like this:
db.newdocs.aggregate([
// Transform the document
{"$project": {
"startDate": "$value.startDate",
"endDate": "$value.endDate",
"active": "$value.active",
"channels": "$value.channels",
"tags": "$value.tags"
}},
// Output to new collection
{"$out": "fixeddocs" }
])
So that will be right. But of course this is not your original collection. So to back to that state you are going to have to .drop() collections and use .renameCollection() :
db.newdocs.drop();
db.docs.drop();
db.fixeddocs.renameCollection("docs");
Now please READ the documentation carefully on this, there are several limitations, and of course you would have to re-create indexes as well.
All of this, and in particular the last stage is going to result in a lot of disk thrashing and also keep in mind that you are dropping collections here. It almost certainly is a case for taking access to your database off-line while this is performed.
And even as such the dangers here are real enough that perhaps you can just live with running an iterative loop to update the documents, using arbitrary JavaScript. And if you really must have to do so, you could always do that using db.eval() to have that all execute on the server. But if you do, then please read the documentation for that very carefully as well.
But for completeness even if I'm not advocating this:
db.eval(function(){
db.docs.find().forEach(function(document) {
var tags = [
{ name: "one", type: "channel" },
{ name: "two", type: "channel" },
{ name: "three", type: "channel" },
{ name: "four", type: "channel" }
];
document.tags = [];
document.channels.forEach(function(channel) {
document.tags.push( tags[ channel -1 ] );
});
var id = document._id;
delete document._id;
db.docs.update({ "_id": id },document);
});
})

Correct way to write ColdFusion service to send json data and catch by angularjs

I'm Very stuck in this case when working all day :(. please help me.
I have website need using $http provider to call ColdFusion file from other domain.
let's say this is link to cfm file : http://xample.com/getStockCodesTest.cfm
this is may sample ColdFusion file:
<cfcontent
type="application/json"
/>
{
"items": [
{
"StockCode" : { "col": "Stock Code", "value": "0231" },
"Qty" : { "col": "Qty", "value": "DS" },
"QtyOn" : { "col": "Qty On", "value": "Branch" },
"QtyVal" : { "col": "Qty Val", "value": "200" },
"ReleasedDate" : { "col": "Released Date", "value": "0" },
"S" : { "col": "S", "value": "0" },
"Description" : { "col": "Description", "value": "adfasdf" },
}
]
}
this is angular code (i use coffeescript to write)
ajax = $http {
url: 'http://xample.com/getStockCodesTest.cfm'
method: 'JSONP'
params: {
callback: "JSON_CALLBACK"
}
}
ajax.success (data, status, headers, config) ->
console.log data
but when check firebug. it always return error:
so how can i have a correct way to write a test ColdFusion with content json like that and use angularjs to catch in to my web :(
I'm not exactly sure what you are asking. But I can tell you that you are getting the error because you have invalid JSON.
That comma, right there, remove it. It makes for invalid JSON.
You have to wrap your JSON with the input function name, when a JSONP call is made from AngularJS. That is the reason you see the error.
Example of JSONP response:
/xxx.cfm?_jsonp=angular.callbacks._0 --- request
//expected response is like this - a function from your coldfusion
angular.callbacks._0([{"StockCode" : { "col":...
Then it will work.

Dynamically creating nodes in a jstree tree structure

I have to retrieve a list of menu item from a database and display it in a tree structure I want to use the menu name as the node name and menu id as the id of the node.
The method I used was to retrieve the data using an ajax call and put them into a list and then display it as a tree.But I think dynamically creating nodes depending on the data is more efficient.
function createNodeList(){
$('#menuCPanel #contentData #tree').jstree({
"json_data" : {
/*"data" : [{
"data" : {title : "menuName"},
"attr" : {id : "menuId"},
"state" : "closed"
}
],*/
"ajax" :{
"type" : "POST",
"url" : "?m=admin?action=getNodeList",
"dataType" : "json",
"data" : function(result){
return {
id : result.attr ? result.attr("id") : result['menuId'],
title : result.attr ? result.attr("title") : result['menuName']
};
},
},
},
"callback" : {
},
"themes" : {
"theme" : "classic",
"dots" : true,
"icons" : true
},
"plugins" : ["json_data", "themes"]
}).bind("select_node.jstree", function (e, data) { alert(jQuery.data(data.rslt.obj[0], "jstree").id) });
}
}
this is the stucture of my json data
"data":[{"menuId":"1","menuName":"Top Menu"},{"menuId":"2","menuName":"Main Menu"},{"menuId":"3","menuName":"Bottom Menu"},{"menuId":"4","menuName":"Main Menu"}]}
I would like to know what is wrong with the above result and how to dynamically create a node within in the ajax.success();
I went through some examples but all of them use the jstree.cretate() which i can't invoke inside jstree.json_data.ajax.success()
thanks in advance :)
This is a standard jstree with json data, which also binds select_node to do actions when a node is selected. Nodes must not have an ID which are plain numbers or contain jquery special selector characters. Number IDs must have a standard character first. so 1 should be N1, 2 should be N2 for example.
$('#MyTreeDiv').jstree({
"json_data": {
"ajax": {
"type": "POST",
"url": "/MyServerPage.aspx?Action=GetNodes",
"data": function (n) { return { id: n.attr ? n.attr("id") : 0} },
}
},
"themes": {
"theme": "default",
"url": "/Content/Styles/JSTree.css",
"dots": false
},
"plugins": ["themes", "json_data", "ui", "crrm"]
}).bind("select_node.jstree", function (e, data) {
var selectedObj = data.rslt.obj;
alert(selectedObj.attr("id"));
});
The json returned from your server must be in the correct format as defined in the jstree documentation, and must no include several special characters, unless those characters are escaped or the json created using serialization.

Categories

Resources