Parsing json string from events(function) ajax in Full Calendar - json

I have no clue on how to parse events in full calendar
events: function(start, end, timezone, callback) {
$.ajax({
url: 'async/form.php?a=liste_consignes',
datatype:'json',
data: {
// our hypothetical feed requires UNIX timestamps
start: start.unix(),
end: end.unix()
},
success: function(msg) {
//not sur then how to parse
var events = msg.events;
callback(events); //this gives error
},
});
}
PHP (part of)
while($row = $query->fetch_assoc()) {
$cal['id'] = $row['consigne_id'];
$cal['title'] = $row['contenu'];
$cal['start'] = $row['date_consigne'];
array_push($return_arr,$cal);
}
echo json_encode($return_arr);
PHP is returning
[{"id":"5","title":"consigne","start":"2019-03-03"},{"id":"6","title":"test","start":"2019-03-02"},{"id":"7","title":"test 2","start":"2019-03-02"}]
I tried several way from events as json feed but none of them are returning something

PHP is returning an array. It doesn't have an events field. If your callback is meant to consume an array, simply call callback(msg)

Solution was to convert json string from php to object
success: function(msg) {
var events = [];
var data = jQuery.parseJSON(msg);
$.each(data, function(i, item) {
events.push({
title: item.title,
start: item.start, // will be parsed
end: item.end, // will be parsed
});
});
callback(events);
}

Related

ajax json parsing to return related values

I am trying to only parse the information related to a certain "market_name" however I cannot seem to figure out how. The api is located at https://stocks.exchange/api2/ticker which displays information related to the entire exchange. I simply need all of the information returned relating to the "market_name" I am searching for such as ETH_BTC
Ajax:
$.ajax({
url: "https://stocks.exchange/api2/ticker",
dataType: 'json',
success: function(data) {
last = data.last;
console.log(last);
$("#btcprice").text(last);
},
error: function() {
//alert("Was unable to get info!");
}
});
That's because data is an array of objects, not a single object.
Try:
$.ajax({
url: "https://stocks.exchange/api2/ticker",
dataType: 'json',
success: function (data) {
// find object
var market = data.find(function (obj) {
return obj.market_name == 'ETH_BTC';
});
$("#btcprice").text(market.last);
},
error: function() {
//alert("Was unable to get info!");
}
});
Use array filter() method to filter out the record having market_name as ETH_BTC.
array.filter(obj => {
return obj.market_name == 'ETH_BTC'
});
DEMO
var jsonObj = [{"min_order_amount":"0.00000010","ask":"0.00000017","bid":"0.0000001","last":"0.00000010","lastDayAgo":"0.00000009","vol":"154955.9586604","spread":"0","buy_fee_percent":"0","sell_fee_percent":"0","market_name":"ATR_BTC","market_id":338,"updated_time":1527789301,"server_time":1527789301},{"min_order_amount":"0.00000010","ask":"0.000032","bid":"0.000012","last":"0.00003200","lastDayAgo":"0.000065","vol":"372.5011152","spread":"0","buy_fee_percent":"0","sell_fee_percent":"0","market_name":"ETH_BTC","market_id":35,"updated_time":1527789301,"server_time":1527789301},{"min_order_amount":"0.00000010","ask":"0.00003595","bid":"0.00003","last":"0.00003000","lastDayAgo":"0.00003001","vol":"26.44435669","spread":"0","buy_fee_percent":"0","sell_fee_percent":"0","market_name":"ARDOR_BTC","market_id":262,"updated_time":1527789301,"server_time":1527789301}];
var res = jsonObj.filter(obj => {
return obj.market_name == 'ETH_BTC'
});
console.log(res);
$.ajax({
url: "https://stocks.exchange/api2/ticker",
dataType: 'json',
success: function(data) {
var results = [];
var searchField = "market_name";
var searchVal = "ETH_BTC";
for (var i=0 ; i < data.length ; i++)
{
if (data[i][searchField] == searchVal) {
results.push(data[i]);
}
}
$("#btcprice").text(results[0].last);
},
error: function() {
//alert("Was unable to get info!");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here is a simple code in which you find what you want simply just change searchVal statically or dynamically according to your need......

Wrong data format for store loadData method ExtJS

I want to call JSON data as much as the amount of data in the store. Here is the code:
storeASF.each(function(stores) {
var trano = stores.data['arf_no'];
Ext.Ajax.request({
results: 0,
url: '/default/home/getdataforeditasf/data2/'+trano+'/id/'+id,
method:'POST',
success: function(result, request){
var returnData = Ext.util.JSON.decode(result.responseText);
arraydata.push(returnData);
Ext.getCmp('save-list').enable();
Ext.getCmp('cancel-list').enable();
},
failure:function( action){
if(action.failureType == 'server'){
obj = Ext.util.JSON.decode(action.response.responseText);
Ext.Msg.alert('Error!', obj.errors.reason);
}else{
Ext.Msg.alert('Warning!', 'Server is unreachable : ' + action.response.responseText);
}
}
});
id++;
});
storeARF.loadData(arraydata);
StoreASF contains data[arf_no] which will be used as a parameter in Ajax request url. StoreASF could contain more than one set of the object store, so looping is possible. For every called JSON data from request would be put to array data, and after the looping is complete, I save it to storeARF with the loadData method.
The problem is, my data format is wrong since loadData can only read JSON type data. I already try JSON stringify and parse, but couldn't replicate the data format. Any suggestion how to do this? Thank you.
Rather than using Ext.util.Json.decode(), normalize the data in success() method using your own logic. For example:
success: function (response) {
console.log(response);
var myData = [];
Ext.Array.forEach(response.data, function (item) {
myData.push({
name: item.name,
email: item.email,
phone: item.phone
});
});
store.load();
}

Backbone - parsing JSON ID

I'm trying to parse JSON data using Backbone from a remote API. Here's what I've got so far:
// --------------------------------------------------
// MODELS
// --------------------------------------------------
var VideoModel = Backbone.Model.extend({
idAttribute: '_id',
parse: function(){
this.id = response._id;
}
});
var videoModel = new VideoModel({ parse:true });
// --------------------------------------------------
// COLLECTIONS
// --------------------------------------------------
var VideosCollection = Backbone.Collection.extend({
model: VideoModel,
url: 'redacted',
parse: function(response){
this.videos = response.data;
this.cid = response.cid;
return response.data;
},
render: function(){
this.collection.forEach(this.addone, this);
}
});
var videosCollection = new VideosCollection();
videosCollection.fetch({
success: function(videos){
console.log('success!');
},
error: function(){
console.log('failed.');
}
});
// --------------------------------------------------
// VIEWS
// --------------------------------------------------
var VideoView = Backbone.View.extend({
template: _.template('<%= videoModel.id %>'),
render: function(){
this$el.html(this.template(this.model.attributes));
return this;
}
});
var videoView = new VideoView({});
var VideosCollectionView = Backbone.View.extend({});
var videosCollectionView = new VideosCollectionView({
collection: videosCollection,
render: function(){
this.collection.forEach(this.addOne, this);
},
addOne: function(videoModel){
this.$el.append(videoView.el);
}
});
What I'm having trouble with is that console.log(videoModel.id) is still undefined.
The data is a playlist of videos, which is valid JSON:
{
"total":24,
"per_page":24,
"current_page":1,
"last_page":1,
"from":1,
"to":24,
"data":[
{
"_id":"55d1bb50140ba04c1d8b4583",
Be glad for some prompts in the right direction - especially since I had it working this morning and then ... reverted to a previous version without saving.
Thanks
From documentstion of parse method:
The function is passed the raw response object, and should return the
attributes hash to be set on the model. The default implementation is
a no-op, simply passing through the JSON response.
So by default it works like this:
parse: function(data) {
return data;
}
Your code now returns nothing and model takes no data.
As I see you want to set id attribute but you already have setted idAttribute property with _id and there is _id in your data so it should work fine without parse at all. Try to remove it.
The answer is that I was trying to parse via a Collection instead of a Model. So I would never have got the id I was looking for. For some reason.
I needed to move the URL into the Model and parse from there:
var VideoModel = Backbone.Model.extend({
idAttribute: '_id',
url: 'redacted',
parse: function(response){
var id = response._id;
var cid = response.cid;
return response.data;
},
}),
Now when I do videoModel.get(1) in the console, it returns the value of the first item in my array.

extract data from json

I have a json data coming from wcf servicein jquery like this
GetBedTypeList1Result1 is function in wcf
{
"GetBedTypeList1Result":[
{"Code":23,"CompanyCode":null,"Decode":"1 Class New Born Bed","DivisionCode":0,"LocationCode":0,"admDueDepAmt":0,"bedTypeCode":0,"caseTypeCode":0,"caseTypeDecode":null,"ptnClassCode":0,"ptnClassDecode":null,"rsvDueDepAmt":0},
{"Code":22,"CompanyCode":null,"Decode":"1st Class Bed","DivisionCode":0,"LocationCode":0,"admDueDepAmt":0,"bedTypeCode":0,"caseTypeCode":0,"caseTypeDecode":null,"ptnClassCode":0,"ptnClassDecode":null,"rsvDueDepAmt":0},
{"Code":5,"CompanyCode":null,"Decode":"Classique Bed","DivisionCode":0,"LocationCode":0,"admDueDepAmt":0,"bedTypeCode":0,"caseTypeCode":0,"caseTypeDecode":null,"ptnClassCode":0,"ptnClassDecode":null,"rsvDueDepAmt":0}
],
"strErrMsg":"Y",
"chrErrFlg":"c"
}
I am calling service like below
function CallWcfService() {
//alert("CallWcfServicexxxx");
jQuery.ajax
(
{
type: Type,
url: Url,
data: parameters,
contentType: ContentType, // content type sent to server
dataType: DataType, //Expected data format from server
cache: "false",
crossDomain: true, //Same result if i remove this line
processdata: ProcessData, //True or False
success: function (msg)
{
ServiceSucceeded(msg);
},
error: ServiceFailed// When Service call fails
}
);
}
function callService()
{
DataType = "json";
Type = "GET";
var par = 4;
parameters = null;
Url = "http://192.168.2.42/CWSERVERWCF/bedtypemasterService.svc/GetBedTypeList?callback=?";
parameters = "{'strErrMsg':'1'},{'chrErrFlg':'A'},{'pcompanycode':'0'},{'pdiv':'1'},{'ploc':'1'}";
// alert(parameters);
ContentType = "application/json; charset=utf-8";
ProcessData = true;
//alert("sssssasasadsds");
CallWcfService();
}
I am trying to fetch data but not getting lke below
function ServiceSucceeded(result)
{
if (DataType == "json")
{
var obj = jQuery.parseJSON(JSON.stringify(JSON.stringify(result)));
for (var x = 0; x < obj.length; x++)
{
}
}
}
In obj.length count of characters is coming and jQuery.parseJSON(result) is not working
Please help
If the result is json there is no need to parse it in this way. jQuery.ajax will return a javascript object if the datatype is set to json.
So in your ServiceSucceeded function you may operate on the result variable directly. If you are trying to iterate over the bed types change your for loop to something like this:
for (var i = 0; i < result.GetBedTypeList1Result.length; i++) {
// ...do stuff
// var bed = result.GetBedTypeList1Result[i]]
}
Try using JSON.parse(result) instead of: var obj = jQuery.parseJSON(JSON.stringify(JSON.stringify(result)));
Also, since you've mentioned the dataType as 'json' in your $.ajax call, your response should already be in JSON format with no parsing required.

How to post json data with extJS

I'm a bit of a newb with both extJS and json. What is the most painless route to POSTing json data using extJS? I'm not really interested any GUI features, just using the framework to send some sample data.
Ext.Ajax.request({
url: 'foo.php', // where you wanna post
success: passFn, // function called on success
failure: failFn,
params: { foo: 'bar' } // your json data
});
The following will identify as 'POST' request
Ext.Ajax.request({
url: 'foo.php', // where you wanna post
success: passFn, // function called on success
failure: failFn,
jsonData: { foo: 'bar' } // your json data
});
The following will identify as 'GET' request
Ext.Ajax.request({
url: 'foo.php', // where you wanna make the get request
success: passFn, // function called on success
failure: failFn,
params: { foo: 'bar' } // your json data
});
Just to add my two cents:
//
//Encoding to JSON:
//
var myObj = {
visit: "http://thecodeabode.blogspot.com/"
};
var jsonStr = Ext.encode(myObj);
//
// Decoding from JSON
//
var myObjCopy = Ext.decode(jsonStr);
document.location.href = myObj.visit;
The examples posted here show the basic idea. For complete details on all configurable options see the Ext.Ajax docs.
Code Snippet:
Ext.Ajax.request({
url: "https://reqres.in/api/users",
success: function (response) {
Ext.Msg.alert("success", response.responseText);
},
failure: function () {
Ext.Msg.alert("failure", "failed to load")
},
params: {
"name": "morpheus",
"job": "leader"
}
});
Fiddle: https://fiddle.sencha.com/#view/editor&fiddle/28h1