Parse Cloud code query.withinKilometers - javascript

(Edit 1)
I'm trying to work with the cloud code and GeoPoint. With the function "query.withinKilometers" I have a pointer to the Location Class but when I try to call the function I get the error "invalid key name". What is the right way to do this? I could not find anything in the documentation, here is a file of the cloud function.
Error: "code":105,"message":"Invalid key name: [object Object]"
here de documentation: http://parseplatform.org/Parse-SDK-JS/api/v1.11.1/Parse.html
Parse.Cloud.define("getCloseFindings", function(request, response){
var query = new Parse.Query("findings");
var locQuery = query.include("location");
var LocQuery = locQuery.get("geoLocation");
var Loc_Lat = request.params.Latitude;
var Loc_Long = request.params.Longitude;
var UserLocation = new Parse.GeoPoint(Loc_Lat,Loc_Long);
var RadiusLocation = request.params.Radius;
query.equalTo("isDeleted", false);
query.withinKilometers(locQuery, UserLocation, 100);
query.find({
success: function(results){
if(results === undefined){
var response_jsonArr = {
code : 404,
message : "Not Found"
};
response.success(response_jsonArr);
}else{
var jsonArr = [];
for ( var i = 0; i < results.length; ++i ) {
var finding_location = results[i].get("location");
jsonArr.push({
name: results
});
}
response.success(jsonArr);
}
}, error: function(error){
response.error(error);
}
});

You are passing an object to query.withinKilometers as the first parameter when you should be passing a String. Try using the key from your query.include call instead, like this:
query.withinKilometers("location", userLocation, 100);

Related

Parse : Retrieving properties from an object that is related

So I am doing a query to bring back a list of records, these records have a link to the user that created the record. The link is to the object.
My query gets me the object but I cant then access the fields of that object (except of course ID)
query.equalTo("search", search);
query.include("user");
query.find({
success: function(Report) {
for (var i = 0; i < Report.length; i++) {
var test = Report[i].id;
query.get(test, {
success: function(result) {
var reportDescription = result.get("reportDescription");
var reportPicture = result.get("reportPicture");
var reportPosition = result.get("reportPosition");
var reportType = result.get("reportType");
var reportDate = result.get("createdAt").toLocaleString();
var reportSearchId = result.get("search").id;
var user = result.get("user")
console.log(user)
var reportSearchBy = user.username;
},
error: function(result, error) {
alert(error.message);
}
});
};
},
error: function(error) {
alert(error.message);
}
});
What am I doing wrong?
i tried to run similar code to what you did. when i tried to access with dot notation i get undefined but when i tried to get it with .get("fieldName") it works..
here is my code:
var FileTest = Parse.Object.extend("FileTest");
var query = new Parse.Query(FileTest);
query.include("user");
query.find().then(function(results){
var lastItem = results[results.length - 1];
if (lastItem){
var user = lastItem.get("user");
console.log(user.get("username"));
}
},function(error){
});
please notice that i also use Promise for better coding and in order to get the username i did lastItem.get("username")
so please try to replace user.username with user.get("username")
and see if it works.

Object handling in Chrome/FF?

I have this code:
$('.gBook').click(function(){
var values = [];
var getDiff = $('#totalPrice').attr("data-value");
var i = 0;
$('td[data-check="true"]').each(function(){
var valueToPush = { };
valueToPush["price"] = $(this).attr("data-price");
valueToPush["id"] = $(this).attr("data-id");
valueToPush["diff"] = getDiff;
values.push(valueToPush);
i++;
});
var arrayToSend = {values};
$.post( '<?php echo PATH;?>ajax/updateRoom.php',arrayToSend, function(data){
if(data != "ERROR"){
$('#all-content').html(data).css("overflow-y","auto");
}else{
alert("ERROR");
}
});
});
In Chrome, this line gives an error var arrayToSend = {values}; (Uncaught SyntaxError: Unexpected token }) In Firefox everything is fine.
I guess it's because of the rather "loose" error handling of FF, but how am I doing it correctly?
I tried to initialize the object with var arrayToSend = new Object(); before the $.each, but that gives an empty array after POST.
Where is my mistake?
try this
var arrayToSend = {optionsChosen:values};
Then in php or whatever you use for data handling look for the POST variable optionsChosen.
What you did was try to make an Object with parameter array = nothing
You basically did this in your code. It doesn't take an expert to see whats wrong with this statement.
arrayToSend = new function() {
this.(new Array(1,2,3)); // This is cringeworthy if you see it like this.
}
In the example I gave it translates to this:
arrayToSend = new function() {
this.optionsChosen = new Array(1,2,3);
}

Keep getting error: "Failed with: Uncaught SyntaxError: Unexpected token T in <unknown file>:1" (PARSE CLOUD CODE)

If someone could help me with this it would be a life saver!!
(I'm using PARSE)
Basically what this parse job attempts to do is
1) queries all objects of a class called channel
2) loop through each object in the "Results" array which is returned from the query
3) make a call to a Google API which returns a JSON string
4) parse the JSON and save new instances of an Object called Videos
The problem is i keep getting the errors:
Failed with: Uncaught SyntaxError: Unexpected token T in :1
Failed with: Uncaught SyntaxError: Unexpected end of input in :0
Parse.Cloud.job("TestFunction", function(request, status) {
var query = new Parse.Query("Channel");
query.find ({
success: function (results) {
var httpRaw;
for (var i = 0; i < results.length; i++) {
var channel_id = results[i].get("channel_id");
Parse.Cloud.httpRequest({
url: 'https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCKy1dAqELo0zrOtPkf0eTMw&maxResults=50&order=viewCount&type=video&key=AIzaSyCLGCJOPU8VVj7daoh5HwXZASnmGoc4ylo',
success: function (httpResponse) {
httpRaw = httpResponse.text;
},
error: function (httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
}
});
var json = JSON.parse(httpRaw);
for (var z = 0; z < json.items.length ; z++){
var video = new Parse.Object("Video");
video.set("video_id", json.items[z].id.videoId.toString());
video.set("video_title", json.items[z].snippet.title.toString());
video.set("video_description", json.items[z].snippet.description.toString());
video.set("video_thumbnail", json.items[z].snippet.thumbnails.medium.url.toString());
video.set("date_published", json.items[z].snippet.publishedAt.toString());
var relation = video.relation("parent_channel");
relation.add(results[i]);
video.save();
}
}
},
error: function() {
}
});
});
I'm guessing the cause is JSON.parse(). HTTP requests are non-blocking in cloud code (and generally everywhere in JavaScript) so the JSON.parse() is evaluated before httpRaw has been set.
At a minimum, you need to move the parse() call and the following loop into the success handler of your HTTP request so they wait until you have a valid response. I'd suggest using Promises instead of the success/error callbacks as well.
Here's how I would go about it (warning: untested code follows ...)
Parse.Cloud.job("TestFunction", function(request, status) {
var query = new Parse.Query("Channel");
query.find().then(function(results) {
var requests = [];
for (var i = 0; i < results.length; i++) {
var channel_id = results[i].get("channel_id");
requests.push(Parse.Cloud.httpRequest({
url: 'https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCKy1dAqELo0zrOtPkf0eTMw&maxResults=50&order=viewCount&type=video&key=AIzaSyCLGCJOPU8VVj7daoh5HwXZASnmGoc4ylo'
}));
}
return Parse.Promise.when(requests);
}).then(function(results) {
var videos = [];
for(var i = 0; i < results.length; i++) {
var httpRaw = results[i].text;
var json = JSON.parse(httpRaw);
for (var z = 0; z < json.items.length ; z++){
var video = new Parse.Object("Video");
video.set("video_id", json.items[z].id.videoId.toString());
video.set("video_title", json.items[z].snippet.title.toString());
video.set("video_description", json.items[z].snippet.description.toString());
video.set("video_thumbnail", json.items[z].snippet.thumbnails.medium.url.toString());
video.set("date_published", json.items[z].snippet.publishedAt.toString());
var relation = video.relation("parent_channel");
relation.add(results[i]);
videos.push(video);
}
}
return Parse.Object.saveAll(videos);
});
});

Promise doesn't work in Javascript, Returns undefined

I want to fetch data from Parse.com and trigger a event after all Data has been loaded.
The methods getEinstellerData,getObjektData and getVermieterData contain the asynchronous query to the parse.com database. The Object within the queries are retreived correctly.
I wrote that code accordring to: http://www.html5rocks.com/en/tutorials/async/deferred/
My problem now is, that the parameter of var combinedPromise = $.when(getVermieterData(vermieterId), getEinstellerData(einstellerId)); which i actually wrote in the first promise to global variables, seem to be undefined.
I've got the following function to fetch Data:
getData = function() {
var promise = getObjektData();
promise.done(
function(){
var combinedPromise = $.when(getVermieterData(vermieterId), getEinstellerData(einstellerId));
combinedPromise.done(function(){
console.log(einstellerData);
console.log(vermieterData);
$(that).trigger("setWohnungsDetails");
});
});
},
these are the 3 Functions which contain the queries:
getEinstellerData = function(){
einstellerData = [];
var queryEinsteller = new Parse.Query(erstellerDataObject);
queryEinsteller.equalTo("ID", parseInt(einstellerId));
queryEinsteller.first({
success: function(einsteller) {
var vorname = einsteller.get("Vorname");
var nachname = einsteller.get("Nachname");
var strasse = einsteller.get("Strasse");
var hausnummer = einsteller.get("Hausnummer");
var plz = einsteller.get("PLZ");
var ort = einsteller.get("Ort");
var email = einsteller.get("Email");
var telefon = einsteller.get("Telefon");
einstellerData.push({ vorname: vorname, nachname: nachname, strasse: strasse, hausnummer: hausnummer, plz: plz, ort: ort, email: email, telefon: telefon });
console.log(einstellerData);
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
},
getVermieterData = function(){
vermieterData = [];
var queryVermieter = new Parse.Query(vermieterDataObject);
queryVermieter.equalTo("ID", parseInt(vermieterId));
queryVermieter.first({
success: function(vermieter) {
var vorname = vermieter.get("Vorname");
var nachname = vermieter.get("Nachname");
var strasse = vermieter.get("Strasse");
var hausnummer = vermieter.get("Hausnummer");
var plz = vermieter.get("PLZ");
var ort = vermieter.get("Ort");
var email = vermieter.get("Email");
var telefon = vermieter.get("Telefon");
vermieterData.push({ vorname: vorname, nachname: nachname, strasse: strasse, hausnummer: hausnummer, plz: plz, ort: ort, email: email, telefon: telefon });
console.log(vermieterData);
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
},
getObjektData = function() {
objectId = localStorage.getItem("currentWohnung");
objektData = [];
var queryObjekt = new Parse.Query(objektDataObject);
queryObjekt.get(objectId, {
success: function(wohnung) {
var vermieter_id = wohnung.get("Vermieter_id");
var einsteller_id = wohnung.get("Einsteller_id");
var strasse = wohnung.get("Strasse");
var hausnummer = wohnung.get("Hausnummer");
var plz = wohnung.get("PLZ");
var ort = localStorage.getItem("selectedStadt");
var bild = wohnung.get("Bild");
var flaeche = wohnung.get("Flaeche");
var freitext = wohnung.get("Freitext");
var gesamtmiete = wohnung.get("Gesamtmiete");
var kaution = wohnung.get("Kaution");
var miete = wohnung.get("Miete");
var nebenkosten = wohnung.get("Nebenkosten");
var raucher = wohnung.get("Raucher");
var zimmer = wohnung.get("Zimmer");
objektData.push({ vermieter_id: vermieter_id, einsteller_id: einsteller_id, strasse: strasse, hausnummer: hausnummer, plz: plz, ort: ort, bild: bild, flaeche: flaeche, freitext: freitext, gesamtmiete: gesamtmiete, kaution: kaution, nebenkosten:nebenkosten, raucher: raucher, zimmer: zimmer });
console.log(objektData);
einstellerId = einsteller_id;
vermieterId = vermieter_id;
},
error: function(object, error) {
console.log("error" + error);
}
});
And here my console output:
DetailStart init DetailStart.js:3
DetailController init DetailController.js:10
init Detail.js Detail.js:17
Uncaught TypeError: Cannot call method 'done' of undefined Detail.js:34
DetailStart.Detail.getData Detail.js:34
DetailStart.Detail.init Detail.js:21
DetailStart.DetailController.init DetailController.js:13
DetailStart.init DetailStart.js:4
(anonymous function) detail.html:115
[Object]
0: Object
length: 1
__proto__: Array[0]
Any idea what I might have gotten wrong here!?
Thanks in advance ;)
I am not familiar with the libraries you are using but it looks like you are mixing callbacks and promises which can be used together but you have to be careful. For example,
queryEinsteller.first({
...
});
will return immediately causing the combinedPromise to be resolved before success or error members are called. What you need to do is create a promise that is resolved when success or error is called. You can then return that promise from getEinstellerData. You need to do the same thing in getVermieterData.
For an example of how to do this you should study the example in the section entitled "Putting it together with $.Deferred" in the web page you referenced.
The call to queryObject.get(..) will return a promise, if you want to allow chaining then you need to return that value from your functions, i.e.
getObjektData = function() {
// .. other code ..
return queryObjekt.get(objectId, {
success: /* .. your success handler .. */
error: /* .. your errror handler .. */
});
};
Basically just add that return statement to your call, do the same in your other functions.
The question is do you want the first query to finish before you start the second, and same for third vs second (i.e. following queries require data from prior queries), or do you want all three to be started and just do something when they're all done?
I'll update this question with samples once you answer that question for me.

Uncaught TypeError: Object has no method ... Javascript

I'm having an issue where I get an error that says...
"Uncaught TypeError: Object f771b328ab06 has no method 'addLocation'"
I'm really not sure what's causing this. The 'f771b328ab06' is a user ID in the error. I can add a new user and prevent users from being duplicated, but when I try to add their location to the list, I get this error.
Does anybody see what's going wrong? The error occurs in the else statement of the initialize function as well (if the user ID exists, just append the location and do not create a new user). I have some notes in the code, and I'm pretty sure that this is partly due to how I have modified an example provided by another user.
function User(id) {
this.id = id;
this.locations = [];
this.getId = function() {
return this.id;
};
this.addLocation = function(latitude, longitude) {
this.locations[this.locations.length] = new google.maps.LatLng(latitude, longitude);
alert("User ID:" );
};
this.lastLocation = function() {
return this.locations[this.locations.length - 1];
};
this.removeLastLocation = function() {
return this.locations.pop();
};
}
function Users() {
this.users = {};
//this.generateId = function() { //I have omitted this section since I send
//return Math.random(); //an ID from the Android app. This is part of
//}; //the problem.
this.createUser = function(id) {
this.users[id] = new User(id);
return this.users[id];
};
this.getUser = function(id) {
return this.users[id];
};
this.removeUser = function(id) {
var user = this.getUser(id);
delete this.users[id];
return user;
};
}
var users = new Users();
function initialize() {
alert("Start");
$.ajax({
url: 'api.php',
dataType: 'json',
success: function(data){
var user_id = data[0];
var latitude = data[1];
var longitude = data[2];
if (typeof users.users[user_id] === 'undefined') {
users.createUser(user_id);
users.users[user_id] = "1";
user_id.addLocation(latitude, longitude); // this is where the error occurs
}
else {
user_id.addLocation(latitude, longitude); //here too
alert(latitude);
}
}
})
}
setInterval(initialize, 1000);
Since I get the ID from the phone and do not need to generate it here (only receive it), I commented out the part that creates the random ID. In doing this, I had to add a parameter to the createUser method within Users() so that I can pass the ID as an argument from Initialize(). See the changes to createUser below:
Before, with the generated ID (the part where the number is generated is in the above code block with comments):
this.createUser = function() {
var id = this.generateId();
this.users[id] = new User(id);
return this.users[id];
};
After, with the ID passed as an argument:
this.createUser = function(id) {
this.users[id] = new User(id);
return this.users[id];
};
If anyone has any suggestions I would really appreciate it. Thanks!
Here you're getting user_id by :
var user_id = data[0];
So it's a part of the json answer : maybe a string or another dictionnary, this can't be a user object. You should try to update your code in your success function inside the "if" block by :
user = users.createUser(user_id);
//The following line is a non sense for me you put an int inside
//an internal structure of your class that should contain object
//users.users[user_id] = "1";
user.addLocation(latitude, longitude);

Categories

Resources