Get Pointer Id only , using Parse - javascript

this returns an object. I just want to get the id. I will use it for a query
var q= new Parse.Query("Comments");
q.find({
success: function (results) {
for (var i=0; i< results.length;i++) {
console.log(results[i].get("user_id"));
}
});

i actually found it out by exploring, i've used to access just the id
results[i].get("user_id").id

Related

Parsing Json data from asp.net webservice and populating it in asp.net dropdownlist

i am trying to populate an asp.net dropdownlist returned as JSON from my webservice.
WebService
[WebMethod(EnableSession = true)]
public string GetActiveDepositAccountsForLoanAlert(string customerId)
{
var data = BusinessLayer.SMS.SmsSetup.GetActiveDepositAccountsForLoanAlert(customerId.ToLong());
var json = new JavaScriptSerializer().Serialize(data);
return json;
}
The webservice returns
[{"AccountNumber":"NS-0000092"},{"AccountNumber":"6MR-0000002"},{"AccountNumber":"1YFD-0000007"}]
I am calling the data from ajax call and populating it to my dropdownlist.
Ajax call
function GetActiveDepositAccounts(customerrId) {
var customerId = $('#CustomerIdHiddenField').val();
var data = { customerId: $('#CustomerIdHiddenField').val() };
var json_data = JSON.stringify(data);
$.ajax({
type: "POST",
url: "/WebMethods/Misc.asmx/GetActiveDepositAccountsForLoanAlert",
data: json_data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(r) {
var depositRadioList = $("[id*=DepositAccountDropDownList]");
depositRadioList.empty().append('<option selected="selected" value="0">Please select</option>');
for (var i = 0; i < r.d.length; i++) {
depositRadioList.append('<option>' + r.d[i] + '</option>');
}
}
The data gets populated in json.In my dropdown i only want the accountnumber as
NS-0000092.I am getting the whole json in my dropdown.i have searched and seen lots of question with this Json parse thing in here.But couldnt get hold of this.It isnt that i didnt tried,I am newbie,so before marking this as duplicate,please for once have a look at the code.Thank you.
I can't shake the feeling that because your GetActiveDepositAccountsForLoanAlert is returning a string and not an object, r.d is being seen as a string. Try one of 2 things. Either:
Change your method signature to return data type and don't use the JavaScriptSerializer. or,
In your OnSuccess function, add var data = JSON.parse(r.d) and use that variable in your for loop.
Single Object Returned
If by "whole json", you mean you are getting a single {"AccountNumber":"6MR-0000002"} per option -- try outputting the value of the target AccountNumber object (e.g. r.d[i].AccountNumber or r.d[i]["AccountNumber"]).
Modified Function
var depositRadioList = $("[id*=DepositAccountDropDownList]");
depositRadioList.empty().append('<option selected="selected" value="0">Please select</option>');
for (var i = 0; i < r.d.length; i++) {
depositRadioList.append('<option>' + r.d[i].AccountNumber + '</option>');
}
Array of Objects Returned
If the result per option is an entire AccountNumber array of objects, you'll need to loop through your r object until you get to the list of Account Number objects.
Take a look at my Example JS Fiddle. There is probably a cleaner way to do this, but to present the principle, I've laid out nested loops to get you into the list of object values that you need for your <select></select>.
I'm using the JQuery $.each() method, but you can use the for loop. I recommend just using one or the other for consistency. If the data set is really large, for loops have better performance.

ignore case in for loop when property does not exist

I am making a GET request to an endpoint.
This returns an array containing many objects, some of which contain a url for a photo.
If the individual object contains a photo I want to display it, if not just ignore.
I expected the following code to work, and ignore the cases where the photo does not exist, but I am still getting the following error message.
Uncaught TypeError: Cannot read property '0' of undefined(…)
$.get(url, function (data) {
for(var i = 0; i < data.length; i++){
if(data[i].media[0].img){
console.log(data[i].media[0].img);
}
}
});
$.get(url, function (data) {
for(var i = 0; i < data; i++){
if(data[i].media && data[i].media[0]){
console.log(data[i].media[0].img);
}
}
});

Parsing JSON array of objects: undefined property

So, similar to my my previous question here (I was unsure whether to make a new question or edit the old one), I managed to sucessfully parse the body JSON response using the code seen below.
However when attempting to do the same to the event_calendar_date, I get this: Failed with: TypeError: Cannot read property 'und' of undefined. I would have assumed that to get to the next object in the array the method would be the same for both, however that does not appear to be the case.
JSON response from the server:
[
{
"revision_uid":"1",
"body":{
"und":[
{
"value":"Blah Blah.",
"summary":"",
"format":null,
"safe_value":"Blah Blah.",
"safe_summary":""
}
]
},
"event_calendar_date":{
"und":[
{
"value":"2015-07-20 14:00:00",
"value2":"2015-07-20 20:00:00",
"timezone":"America/New_York",
"timezone_db":"America/New_York",
"date_type":"datetime"
}
]
}
}
]
My Code:
Parse.Cloud.httpRequest({
method: "GET",
url: 'http://www.scolago.com/001/articles/views/articles',
success: function(httpResponse) {
var data = JSON.parse(httpResponse.text);
var articles = new Array();
for (var i = 0; i < data.length; i++) {
var Articles = Parse.Object.extend("Articles"),
article = new Articles(),
content = data[i];
article.set("body", content.body.und[0].value);
article.set("vid", content.vid);
article.set("title", content.title);
article.set("events", content.event_calendar_date.und[0].value);
articles.push(article);
};
// function save(articles);
Parse.Object.saveAll(articles, {
success: function(objs) {
promise.resolve();
},
error: function(error) {
console.log(error);
promise.reject(error.message);
}
});
},
error: function(error) {
console.log(error);
promise.reject(error.message);
}
});
I am afraid you didn't give us all code, or you are using not the code you posted in this question, because it should run fine, as you can see in this demo:
for (var i = 0; i < data.length; i++) {
var content = data[i];
console.log(content.event_calendar_date.und[0].value);
};
EDIT and solution
As I expected, JSON you are getting doesn't have field event_calendar_date for 2nd, and 3rd object. I checked in your full code on GitHub.
First object has correct event_calendar_date field, but next records don't have. See how is JSON you are getting formatted - http://www.jsoneditoronline.org/?id=b46878adcffe92f53f689978873a3474.
You need to check first if content.event_calendar_date is present in record in your current loop iteration or add event_calendar_date to ALL records in JSON response.

Make array jquery/js

I want to make an array like this. (on alert it gives object)
var playlist = [{"title":"Kalimba","mp3":"http://www.jplayer.org/audio/mp3/TSP-01-Cro_magnon_man.mp3"}];
From:
var playlist = [];
$.ajax({
url: 'url.php',
data: {
album_name: album_name
},
type: 'POST',
success: function( data ) {
var data_array = JSON.parse(data);
for( var i=0; i<data_array.length; i++ ) {
var value = data_array[i].split('::');
playlist.push('{"title":"Kalimba","mp3":"http://www.jplayer.org/audio/mp3/TSP-01-Cro_magnon_man.mp3"},'); // putting the same thing just for testing.
}
alert(playlist);
}
});
Now the new array playlist didn't seem to be working for me. i guess there is something wrong the way i am creating an array like above.
you need to push object instead of object string:
playlist.push({"title":"Kalimba","mp3":"http://www.jplayer.org/audio/mp3/TSP-01-Cro_magnon_man.mp3"});
//------------^---remove the single quote.
Try this one
var playlist =[{"title":"Kalimba","mp3":"http://www.jplayer.org/audio/mp3/TSP-01-Cro_magnon_man.mp3"}];
alert(JSON.stringify(playlist));
Use jQuery.map() for making array.
playlist = $.map(data_array, function(val, i){
splitArr = val.split('::')
return {
'title':splitArr[0],
'mp3':splitArr[1]
}
})
As #Jai said you need to push an object: playlist.push({"title":"Kalimba","mp3":"http://www.jplayer.org/audio/mp3/TSP-01-Cro_magnon_man.mp3"});
Arrays in JavaScript are objects.
You'd be better using the console to log or debug your javascript.
In this fiddle you can see
that the array is created and the object pushed to it but its
still logged as an object.
And since you are using jQuery it has a method isArray() to determine if
something is an array or not.
or you can try like this
var playlist = [];
$.ajax({
url: 'url.php',
data: {
album_name: album_name
},
type: 'POST',
success: function( data ) {
var data_array = JSON.parse(data);
for( var i=0; i<data_array.length; i++ ) {
var value = data_array[i].split('::');
var ArrObj = '{"title":"Kalimba","mp3":"http://www.jplayer.org/audio/mp3/TSP-01-Cro_magnon_man.mp3"},';
playlist.push(ArrObj);
}
alert(playlist);
}
});

Send an app request dialog to specific array of id's

I;m trying to send a request dialog to my friends on facebook but to a few selected ones, i have created an array and i need to send invitation only to the id's on that array, i have this code built but it's not working.
It looks like it stops all my page's performance
//function to load friends
function loadFriends()
{
//get array of friends
FB.api('/me/friends?fields=name,first_name,gender', function(response) {
console.log(response);
var divContainer=$('.facebook-friends');
var testdiv = document.getElementById("test");
for(var i=0; i<response.data.length; i++){
if(response.data[i].gender == 'male'){
testdiv.innerHTML += response.data[i].first_name + response.data[i].id + '<br />';
}
}
var arr = []; // Creates an empty array literal.
for(var i=0; i<response.data.length; i++){
arr.push(response.data[i].id);
}
newInvite(arr); // Call your function and pass the friends array
});
}
function newInvite(arr){
FB.ui({ method: 'apprequests',
message: 'Penelope for WAS',
filters: ['app_non_users'],
to:arr.join(',')
});
}
You should use comma separated list as to parameter, not an array.
FB.ui({
method: 'apprequests',
message: 'Penelope for WAS',
filters: ['app_non_users'],
to:arr.join(',')
});
Your code is also have mistake while dealing with JavaScript variable scope.
newInvite is a function which missing arr variable definition (and arr not in global scope, you should pass it to newInvite so it'll be available to your function internals.
function newInvite(arr){
FB.ui({
method: 'apprequests',
message: 'Penelope for WAS',
filters: ['app_non_users'],
to:arr.join(',')
});
)
And for sure you should pass array of friends ids to the function:
FB.api('/me/friends', {fields:'name,first_name,gender'}, function(response) {
var arr = []; // Creates an empty array literal.
for(var i=0; i<response.data.length; i++){
arr.push(response.data[i].id);
}
newInvite(arr); // Call your function and pass the friends array
});

Categories