how do i parse json value and get id into variable - javascript

hello i am having this code of jquery:
var fbuid = zuck;
var fbjson = $.getJSON("https://graph.facebook.com/"+fbuid);
how to get the id from json directly into var :
{
id: "4",
first_name: "Mark",
gender: "male",
last_name: "Zuckerberg",
link: "https://www.facebook.com/zuck",
locale: "en_US",
name: "Mark Zuckerberg",
username: "zuck"
}
all i would like to get id from json to var as below:
var fbjson.id;
how i do it using jquery?

So you're close but you've got some things you need to adjust. Ajax is async which means that you're waiting on a server response. You need to fill your data once you have that piece of data. Note you will not be able to reference fbjson until AFTER the getJSON has fired and completed.
According to the jQuery documentation for getJSON
you need to have a callback similar to this -
var fbuid = 'zuck';
var fbjson;
$.getJSON( "https://graph.facebook.com/"+fbuid, function( data ) {
fbjson = data;
});
Notice I assign the fbjson in the callback to data which is the server response. now you can reference it as
fbjson.id

Related

Refresh data in table after creating a record

In my Ui5 app I have added CREATE operation using oData. But when i am trying to create entry it is getting added in backend but in table it is showing NO DATA (refer image 1). but when I refresh the same page it is there (refer image 2). With single entry ,it is automatically getting refreshed 
problem is with Multiple entries.
Please refer the screenshot and code for clear view.
After Clicking CREATE button:
After Refreshing WebPage:
onCreate: function() {
var oModel = this.getView().getModel();
var contactEntry1 = {
ProductID: 'KT-1960',
TypeCode: 'AD',
SupplierID: '0100000001',
TaxTarifCode: 1,
Category: 'Notebooks',
MeasureUnit: 'EA',
CurrencyCode: 'EUR',
Name: 'Urvish',
Description: 'First batch entry',
},
contactEntry2 = {
ProductID: 'KT-1982',
TypeCode: 'AD',
SupplierID: '0100000001',
TaxTarifCode: 1,
Category: 'Notebooks',
MeasureUnit: 'EA',
CurrencyCode: 'EUR',
Name: 'Urvish',
Description: 'Second batch entry',
};
oModel.setUseBatch(true);
oModel.create('/ProductSet', contactEntry1);
oModel.create('/ProductSet', contactEntry2);
oModel.refresh(true);
},
Looks like that you use the asynchronous operation for create but think that they are synchronous.
In order to fix this out, you can send these 2 create in one $batch request, but use the createEntry method of ODataModel, in order to use the submitChanges method, the callback of which, will be called once two of items are successfully created on the backend side (the below code example should be relevant for v2.ODataModel):
var oTableItemsBinding = oTable.getBinding("items");
// define the group ID, which will be used later on
var aCurrentDeferredGroups = oModel.getDeferredGroups();
oModel.setDeferredGroups(aCurrentDeferredGroups.concat("createProductGroup"));
// create two entries one by one, specifying the 'groupId' parameter
oModel.createEntry("/ProductSet", {
properties: contactEntry1,
groupId: "createProductGroup"
});
oModel.createEntry("/ProductSet", {
properties: contactEntry2,
groupId: "createProductGroup"
});
// send 2 requests in one $batch, passing the name of the 'groupId'
oModel.submitChanges({
groupId: "createProductGroup",
success: function() {
// no need to call refresh() as the model already does it by default (See "refreshAfterChange")
}.bind(this)
});
If your service does not support $batch requests, then you can still use the create method, but make use of it's success callback to be sure that the entry has been persisted in the backend.

Dynamic http post parameter name in AngularJS

I'm using an API for updating profile, by adding nickname, email, phone or password in request parameters each of them will be updated in database.
I want to pass one of these each time depending on user's choice for example when I want to update Nick name:
{
"nickname": "alifa",
"device_id": "chrome",
"device_model": "browser",
"device_os": "angularJS"
}
or for updating email:
{
"email": "info#example.com",
"device_id": "chrome",
"device_model": "browser",
"device_os": "angularJS"
}
I want to do this by passing property name and property value to a function and it will make an object and send http post request:
this.updateDetails = function(dataName, dataValue){
Loader.global.show();
var data = $.param({
device_id: app.device_id,
device_os: app.device_os,
device_model: app.device_model
});
data[dataName] = dataValue;
console.log(data);
return $http.post(app.baseUrl + 'profile/' , data).success(function(){
Loader.global.hide();
}).error(function(){
Loader.global.hide();
})
}
but what it sends to server is just:
Is there any possible way to do this?
You need to modify the object you pass to param. Adding a property to the string you get out of param is pointless.
var data = {
device_id: app.device_id,
device_os: app.device_os,
device_model: app.device_model
};
data[dataName] = dataValue;
var encoded_data = $.param(data);

Data Model's "serialize" function not called on property "set"ting

Also asked on Sencha's site here
My data model's "serialize" function is not called when I call
model.set("<fieldName>", <newValue>);
Here's a fiddle
I'm pretty unclear on why the serialize function isn't called...am I missing something, or is this a bug?
(And here's the code from the fiddle)
Ext.application({
name : 'Fiddle',
requires: [
"Ext.data.Store"
],
launch : function() {
var store = Ext.create("Ext.data.Store", {
data: [{Id: 0, Name: "Bill", Props: "{foo: 2, bar:{pan:5}}"}],
fields:[
{name: "Id", type: "int"},
{name: "Name", type: "string"},
{name: "Props",
convert: function(value, record){
console.log("called convert");
return Ext.JSON.decode(value);
},
serialize: function(value, record){
alert("never getting called!! :(");
console.log("sure, i'll put log here too..not getting called though");
return Ext.JSON.encode(value);
}
}
]
});
console.log(store.getAt(0));
var rec = store.getAt(0);
var newProp = {rec:"junk", foo: "orange"};
console.log(newProp);
rec.set("Props",newProp);
}
});
Mappings from source content (JSON/XML) to business model (Ext.data.Model) are not automatically created in ExtJS's data model system. As such, another step is needed to produce this relationship using mapping/associationsor something similar.
I.e. The data model doesn't store the original JSON to read/write from, which is fine for most cases. When a JSON string needs to be updated via ExtJS, one solution is to, on the model, set
convertOnSet
to false, allowing for custom manipulation of the JSON string via extract/update functions on the data model.

How do you get the model.id from the collection.create call?

I need to use the model id from the COLLECTION.create call to redirect the user to do new page
window.href = 'https://example.com/document/' + model.id
I do not care if the ajax call to the rest api is async or sync (if that matters). I was hoping I could do something like this:
var OPTS ={}
OPTS['success'] = function( response, model, options ){
model.id
}
SOMECOLLECTION.create(json_attributes,OPTS)
But that does not work. I am using Django-Tastypie as my REST API.
This should work
var MyCollection = Backbone.Collection.extend({
url: '/echo/json/'
});
var my_collection = new MyCollection();
var model = my_collection.create({ name: "Eugene", age: 31 }, {
success: function(response, model) {
console.log(model.id);
// id: 123
}
});
console.log(model.id);
// id: undefined
I created working example here http://jsfiddle.net/6wup7q9e/3/
Please check your network tab to see what response you have from your REST API, it should have and your json_response and new id attribute which will be used as a model id. In my case it will be something like:
{
id: 123,
name: "Eugene",
age: 31
}

Load data into a Backbone collection from JSON file?

I'm trying to load some data into a Backbone Collection from a local JSON file, using this very basic code:
window.Student = Backbone.Model.extend({
});
window.Students = Backbone.Collection.extend({
model: Student,
});
window.AllStudents = new Students();
AllStudents.fetch({ url: "/init.json"});
console.log('AllStudents', AllStudents);
In the console statement, AllStudents is empty. But init.json is definitely being loaded. It looks like this:
[
{ text: "Amy", grade: 5 },
{ text: "Angeline", grade: 26 },
{ text: "Anna", grade: 55 }
]
What am I doing wrong?
UPDATE: I've also tried adding a reset listener above the .fetch() call, but that's not firing either:
AllStudents.bind("reset", function() {
alert('hello world');
});
AllStudents.fetch({ url: "/init.json"});
No alert appears.
UPDATE 2: Trying this script (reproduced here in full):
$(function(){
window.Student = Backbone.Model.extend({
});
window.Students = Backbone.Collection.extend({
model: Student,
});
window.AllStudents = new Students();
AllStudents.url = "/init.json";
AllStudents.bind('reset', function() {
console.log('hello world');
});
AllStudents.fetch();
AllStudents.fetch({ url: "/init.json", success: function() {
console.log(AllStudents);
}});
AllStudents.fetch({ url: "/init.json" }).complete(function() {
console.log(AllStudents);
});
});
Only one console statement even appears, in the third fetch() call, and it's an empty object.
I'm now absolutely baffled. What am I doing wrong?
The JSON file is being served as application/json, so it's nothing to do with that.
The attribute names and non-numeric attribute values in your JSON file must be double quoted (" ") . Single quotes or no-quotes produces errors and response object is not created that could be used to create the models and populate the collection.
So. If you change the json file content to :
[
{ "text": "Amy", grade: 5 },
{ "text": "Angeline", grade: 26 },
{ "text": "Anna", grade: 55 }
]
you should see the non-empty collection object.
You can change your code to see both success and failure as below:
AllStudents.fetch({
url: "/init.json",
success: function() {
console.log("JSON file load was successful", AllStudents);
},
error: function(){
console.log('There was some error in loading and processing the JSON file');
}
});
For more details, probably it will be a good idea to look in to the way ajax response objects are created.
I/O operations in javascript are almost always asynchronous, and so it is with Backbone as well. That means that just because AllStudents.fetch has returned, it hasn't fetched the data yet. So when you hit your console.log statement, the resources has not yet been fetched. You should pass a callback to fetch:
AllStudents.fetch({ url: "/init.json", success: function() {
console.log(AllStudents);
}});
Or optionally, use the new promise feature in jQuery (fetch will return a promise):
AllStudents.fetch({ url: "/init.json" }).complete(function() {
console.log(AllStudents);
});
fetch() returns a 'success' notification as already stated, but that just means that the server request was successful. fetch() brought back some JSON, but it still needs to stuff it into the collection.
The collection fires a 'reset' event when it's contents have been updated. That is when the collection is ready to use...
AllStudents.bind('reset', function () { alert('AllStudents bind event fired.'); });
It looks like you had this in your first update. The only thing I did differently was to put fetch() in front of the event binding.
I think you need to add {add:true} to the options of fetch,
if you assigned the fetch to a variable, you would get the result as well,
but then its not inside the collection you wanted

Categories

Resources