Parse.com Javascript update value by objectID - javascript

I try to update a value in my Parse.com Core, but it simply does not work.
I have the "objectID" of the item that i want to update
Parse.initialize("xxxx", "xxxx");
var PP = Parse.Object.extend("PP");
var PP = new PP();
var query = new Parse.Query(PP);
query.equalTo("objectId", "3Enwfu0QPQ");
query.first({
success: function (PP) {
PP.save(null, {
success: function (PP) {
PP.set("free", "100");
PP.save();
}
});
}
});
i want to set the value of "free" for object "3Enwfu0QpQ" to 100, but it does not work.

There's several issues with your code:
1.
var PP = Parse.Object.extend("PP");
var PP = new PP();
According to your screenshot, the Class is named "P", not "PP". You are also overriding the PP object.
2.
var query = new Parse.Query(PP);
query.equalTo("objectId", "3Enwfu0QPQ");
query.first({[...]});
query is invalide because PP is no longer the PP object. You should also use query.get instead of equalTo.
3.
PP.save(null, {
success: function (PP) {
PP.set("free", "100");
PP.save();
}
});
You are saving an empty object then editing this same object, then you update it again.
Your code should look like this (untested).
Parse.initialize("xxxx", "xxxx");
var P = Parse.Object.extend("P");
var query = new Parse.Query(P);
query.get('3Enwfu0QPQ', { // we get the object
success: function (instance) {
instance.set("free", "100"); // We update the returned object
instance.save(); // we save it
}
});
You can also save a request by doing so:
Parse.initialize("xxxx", "xxxx");
var P = Parse.Object.extend("P");
var instance = new P();
instance.id = '3Enwfu0QPQ';
instance.set("free", "100");
instance.save();

Related

AJAX values from database to html skipped

I have these employee information which display if you click on the employee box. But sometimes the value of some fields returns null even if they have a value but when I retry it will return ok. Is this some code problem? here is my code...
First I store the elements into an object
var uamnumber = $(this).find(".box-list-agents-uamnumber").text();
var agentInfo = $(this).find(".box-list-agents-info").text().split("/");
var agentElement = {
txtUam: $("#search-txt-uam-number"),
txtFirstName: $("#search-txt-first-name"),
txtMiddleName: $("#search-txt-middle-name"),
txtLastName: $("#search-txt-last-name"),
txtContactNumber: $("#search-txt-contact-number"),
txtEmailAddress: $("#search-txt-email-address"),
txtClassification: $("#search-txt-classification"),
txtAgentStatus: $("#search-txt-agent-status"),
txtReasonResignation: $("#search-txt-reason-resignation"),
txtCsp: $("#search-txt-csp-name"),
txtProgramId: $("#search-txt-program-name"),
txtSite: $("#search-txt-site-name"),
txtBirthDate: $("#search-txt-birth-date"),
txtLiveDate: $("#search-txt-live-date"),
txtEndDate: $("#search-txt-end-date"),
txtProgram: $("#search-program-name")
};
var agentParam = {
uam: uamnumber,
csp: agentInfo[0],
program: agentInfo[1]
}
Dashboard_GetAgentInfo(agentParam, agentElement);
$("#search-well-tool-access").hide();
$("#search-well-agent-info").fadeIn();
and here is the function that has been called.
function Dashboard_GetAgentInfo(agentInfo,agentElement) {
$.ajax({
type: "POST",
url: "IROA_StoredProcedures.asmx/Dashboard_GetAgentInfo",
data: JSON.stringify(agentInfo),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var uamdetails = response.d;
var appendItem = "";
$.each(uamdetails, function (index, Dashboard_GetAgentInfoInfo) {
var uamnumber = Dashboard_GetAgentInfoInfo.uamnumber;
var firstname = Dashboard_GetAgentInfoInfo.firstname;
var middlename = Dashboard_GetAgentInfoInfo.middlename;
var lastname = Dashboard_GetAgentInfoInfo.lastname;
var contactnumber = Dashboard_GetAgentInfoInfo.contactnumber;
var emailaddress = Dashboard_GetAgentInfoInfo.emailaddress;
var csp = Dashboard_GetAgentInfoInfo.csp;
var cspid = Dashboard_GetAgentInfoInfo.cspid;
var program = Dashboard_GetAgentInfoInfo.program;
var programid = Dashboard_GetAgentInfoInfo.programid;
var site = Dashboard_GetAgentInfoInfo.site;
var siteid = Dashboard_GetAgentInfoInfo.siteid;
var birthdate = Dashboard_GetAgentInfoInfo.birthdate;
var livedate = Dashboard_GetAgentInfoInfo.livedate;
var enddate = Dashboard_GetAgentInfoInfo.enddate;
var classification = Dashboard_GetAgentInfoInfo.classification;
var agentStatus = Dashboard_GetAgentInfoInfo.agentstatus;
var reasonResignation = Dashboard_GetAgentInfoInfo.reasonresignation;
$(agentElement.txtUam).val(uamnumber);
$(agentElement.txtFirstName).val(firstname);
$(agentElement.txtMiddleName).val(middlename);
$(agentElement.txtLastName).val(lastname);
$(agentElement.txtContactNumber).val(contactnumber);
$(agentElement.txtEmailAddress).val(emailaddress);
$(agentElement.txtClassification).val(classification);
$(agentElement.txtAgentStatus).val(agentStatus);
$(agentElement.txtReasonResignation).val(reasonResignation);
$(agentElement.txtCsp).val(cspid)
$(agentElement.txtProgramId).val(programid);
$(agentElement.txtSite).val(siteid);
$(agentElement.txtBirthDate).val(birthdate);
$(agentElement.txtLiveDate).val(livedate);
$(agentElement.txtEndDate).val(enddate);
$(agentElement.txtProgram).text(program);
NumbersOnly();
});
},
error: function (XMLhttpRequest) {
alert("error in Dashboard_GetAgentInfo");
console.log(XMLhttpRequest);
}
});
}
and this is the web service that has been called
public List<Dashboard_GetAgentInfoDetails> Dashboard_GetAgentInfo(string uam, int csp, int program) /*int CSP, int Program*/
{
DataTable table = null;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "[Dashboard_GetAgentInfo]";
cmd.Parameters.AddWithValue("#uam", uam);
cmd.Parameters.AddWithValue("#csp", csp);
cmd.Parameters.AddWithValue("#program", program);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
table = this.dbConn.ExecuteDataTable(cmd);
Dashboard_GetAgentInfo_Details.Clear();
foreach (DataRow row in table.Rows)
{
Dashboard_GetAgentInfoDetails _list = new Dashboard_GetAgentInfoDetails();
_list.uamnumber = row["UAM #"].ToString();
_list.firstname = row["First Name"].ToString();
_list.middlename = row["Middle Name"].ToString();
_list.lastname = row["Last Name"].ToString();
_list.contactnumber = row["Contact Number"].ToString();
_list.emailaddress = row["Email Address"].ToString();
_list.csp = row["CSP"].ToString();
_list.cspid = Convert.ToInt32(row["CSPID"].ToString());
_list.program = row["Program"].ToString();
_list.programid = Convert.ToInt32(row["ProgramID"].ToString());
_list.site = row["Site"].ToString();
_list.siteid = Convert.ToInt32(row["SiteID"].ToString());
_list.birthdate = row["BirthDate"].ToString();
_list.livedate = row["LiveDate"].ToString();
_list.enddate = row["EndDate"].ToString();
_list.classification = Convert.ToInt32(row["Classification"].ToString());
_list.agentstatus = row["Agent Status"].ToString();
_list.reasonresignation = row["Reason Resignation"].ToString();
Dashboard_GetAgentInfo_Details.Add(_list);
}
return Dashboard_GetAgentInfo_Details;
}
does storing elements into an object and passing it as a parameter is a good practice of coding? and what may be the cause of the select having no value even if I when I try to console.log the value and it returns ok?
I think the problem is here:
$(agentElement.txtUam).val(uamnumber);
$(agentElement.txtFirstName).val(firstname);
...
You should do:
agentElement.txtUam.val(uamnumber);
agentElement.txtFirstName.val(firstname);
...
There is no need to use jquery selector $, because agentElement.txtUam is already one, also gathering elements inside an object is a best practice because you can't pass each one as a parameter.
The perfect answer to this is add a call back function so the dropbox have a option first before adding the val. Here is the idea of adding a callback function
function Filtering_GetSite(siteElement, callback) {
if (typeof (callBack) == "function") {
callBack();
}
}
the line checking of the callback parameter is to ensure that it its a function before executing so you can call the function like this Filtering_GetSite(sample) insted of Filtering_GetSite(sample,function(){}) when omiting the callback function

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.

How to make a copy of a Parse Object in the Cloud?

I would like to have a copy if an existing Parse Object, and then make some edits and save it as a new Parse Object rather than setting each field manually.
Here is my cloud function :
Parse.Cloud.define("SharePost", function(request, response) {
var ShareUserID=request.params.ShareUserID;
var UserID=request.params.UserID;
var PostID=request.params.PostID;
Parse.Cloud.useMasterKey();
var user = new Parse.User({id:UserID});
var shareuser = new Parse.User({id:ShareUserID});
var query = new Parse.Query("Feed");
query.get(PostID, {
success: function(post) {
var Post = Parse.Object.extend("Feed");
var newpost = new Post()
// here I would like to get the same object and make some edits o, it
post.save( {
success:function () {
response.success("Success");
},
error:function (pointAward, error) {
response.success(error);
}
}
);
},
error: function(error) {
console.error("Got an error " + error.code + " : " + error.message);
}
});
});
There might be a prettier way, but one way that's sure to work without relying on any subtleties would be this:
function pfClone(fromObject, toObject, keys) {
var _ = require('underscore');
_.each(keys, function(key) {
toObject.set(key, fromObject.get(key));
});
}
call it like this:
// after fetching a post called "post"
var Post = Parse.Object.extend("Feed");
var newpost = new Post();
var keys = ["title", "author" /* ...the keys you want to copy unchanged */ ];
pfClone(post, newpost, keys);
// change other properties of newpost here
Even prettier would be a version that introspects on the passed object, and then builds and initializes the clone. The one inelegance for either of these ideas is that (last time I checked) PFObject doesn't let you introspect the keys, so you're stuck passing in an array of keys.

Can't access properties of my Javascript object

I'm using Angular.js to fetch a single record from my API. I'm getting the record back as an object, I can log the object and see it's properties but I cannot access any of the properties. I just get undefined.
var template = Template.get({id: id});
$scope.template = template;
...
console.log(template); // displays object
console.log(template.content); // undefined
UPDATE
var id = $routeParams.templateId;
var template = Template.get({id: id});
$scope.template = template;
/*** Template placeholders ***/
$scope.updatePlaceholders = function () {
var placeholders = [];
var content = template.content;
console.log(template); // dumps the object in the screenshot
console.log("content" in template); // displays false
// get placeholders that match patter
var match = content.match(/{([A-z0-9]+)}/gmi);
...
}
$scope.$on('$viewContentLoaded', function(){
$scope.updatePlaceholders();
});
You need to wait for your HTTP request to complete, then specify what to do in the callback. In this case I've taken it a step further and added a listener to your template object so there's no callback dependency between updatePlaceholders and your resource.
var id = $routeParams.templateId;
var template = Template.get({id: id}, function(res) {
$scope.template = template;
});
/*** Template placeholders ***/
$scope.updatePlaceholders = function () {
var placeholders = [];
var content = $scope.template.content;
console.log($scope.template);
console.log("content" in $scope.template);
// get placeholders that match patter
var match = content.match(/{([A-z0-9]+)}/gmi);
...
}
$scope.$watch('template', function(newValue){
if(newValue) $scope.updatePlaceholders();
});

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