Cannot save object props to parse.com table - javascript

I have a form with a textbox title, dropdown menu year and a button. When I click the button, I want to get the values of title and year as properties to an object Movie. Then save them to a table on parse.com. The code below adds a recording to the table with values undefined.
<script>
function saveValues() { // function is appended as onclick to button
var $titleValue = $('#inputTitle').val();
var $select = $('#select');
var $yearValue = $select.val();
var Movie = Parse.Object.extend("Movie");
var movie = new Movie();
// movie.set('title', $titleValue); // Doesn't work. Returns undefined
// movie.set('year', $yearValue); // Doesn't work. Returns undefined
movie.title = $titleValue; // Works
movie.year = $yearValue; // Works
alert(movie.title); // Returns the value
alert(movie.year); // Returns the value
alert(movie); // Returns [object Object]. I was expecting {title: '<SOMETITLE>', year: '<SOMEYEAR>'}
console.log(movie); // This prints a lot of stuff and title and year are there with the respective values.
movie.save()
.then(function(object) {
alert("yay! it worked");
})
}
</script>
Note that when I try to save only the title to the table, it works fine.

Without seeing your full code, I can't guarantee that this will work, but give this a try:
movie.save({
title : $titleValue,
year : $yearValue,
}, {
success: function(movie) {
alert("movie saved successfully with title: " + movie.get("title") +
", and year: " + movie.get("year"));
},
error: function(error) {
alert("error, movie save failed. error code: " + error.code + ", " error.message);
}
});
At the very least you will have a descriptive error message that will tell you what went wrong. Based on the fact that you said it works when you only save the title and not the year, I suspect it may be because your 'year' field in Parse is stored as a number, but you are passing it in as a string (since it came from an HTML form, I'm assuming).
If that doesn't work, I also suspect it may have something to do with appending this function to your button onload rather than as a click or a submit. But that wouldn't explain why it still works if you just leave out the year.
Finally, I wonder if Parse's SDK is confused by the '$' symbol at the beginning of your variable names, but I don't see why that would be the case.

OK, after some time I found out what the problem was. And it was a silly one. It turns out that the value in option was of type 'string'. By adding parseInt() like so: var $yearValue = parseInt($select.val());. And then movie.save({title: titleValue, year: yearValue})..... This way everything works. Initially, I had tried putting key-value pairs in the save() but the year value wasn't the right type.
So note to anyone out there - check your data types!

Related

Trouble getting a specific field from OpenWeatherMap API's output, via JS / XMLHttpRequest

So I'm building this web forecast app using OpenWeatherMap API, and so far I'm being able to fetch the data from the first iteration of the list's output, however I need to obtain the data of other specific fields aswell. Here's a bit of my code:
ajaxGet("https://api.openweathermap.org/data/2.5/onecall?lat=4.6097&lon=-74.0817&exclude=current,minutely,hourly,alerts&appid=APPID&units=metric", function (response) {
var data = JSON.parse(response);
console.log(data);
var temperature = document.createElement("h6");
temperature.textContent = data.daily[0].temp.max + "°" + " / " + data.daily[0].temp.min + "°";
document.getElementById("temperaturaBogVier").appendChild(temperature);
});
And here's an example of what the API's output looks like (I'm only showing the first iteration in here, but there are at least 6 in total, https://api.openweathermap.org/data/2.5/onecall?lat=4.6097&lon=-74.0817&exclude=current,minutely,hourly,alerts&appid=APPID&units=metric):
{"lat":4.61,"lon":-74.08,"timezone":"America/Bogota","timezone_offset":-18000,"daily":
[
{"dt":1600876800,
"sunrise":1600857917,
"sunset":1600901504,
"temp":{"day":18.14,"min":8.99,"max":18.14,"night":12.08,"eve":15.45,"morn":8.99},
"feels_like":{"day":17,"night":11.02,"eve":14.6,"morn":7.58},
"pressure":1017,"humidity":54,
"dew_point":8.69,
"wind_speed":1.2,
"wind_deg":164,
"weather":[{"id":501,"main":"Rain","description":"moderate rain","icon":"10d"}],
"clouds":82,
"pop":0.94,
"rain":5.85,
"uvi":15.14}
]
}
So as you can see, I'm being able to print into my HTML the data contained into "data.daily[0].temp.", but it only works for the first set of fields and I got no clue how to select a specific iteration. I'm sure I'm missing something into the concat, but nothing I've tried has worked so far.
Any help would be greatly appreciated, and rewarded with an imaginary waffle. THX :D
The temperatures for each day data.daily are defined as an JavaScript array of objects. You can simply access them by their index, which indicates their position in the array.
data.daily[0] // First element
data.daily[1] // Second element
data.daily[2] // Third element
Once you have selected an object within the array, you can then access certain values like data.daily[2].temp.max.
The cool thing about arrays is that you can iterate them with a loop. This will save you a lot of writing, if you want to print out each temperatures for every day:
ajaxGet("https://api.openweathermap.org/data/2.5/onecall?lat=4.6097&lon=-74.0817&exclude=current,minutely,hourly,alerts&appid=YOUR_API_KEY_HERE&units=metric", function (response) {
var data = JSON.parse(response);
console.log(data);
data.daily.forEach(function (date) {
var temperature = document.createElement("h6");
temperature.textContent = date.temp.max + "°" + " / " + date.temp.min + "°";
document.getElementById("temperaturaBogVier").appendChild(temperature);
})
});
Please note: I've removed the appid=XXXXX part of the request URL, because it contains your personal API key for OpenWeather, which you should not share publicly.
If I understand the question correctly, you want to take all daily max/min-values and put them into elements that you want to append to another element.
Here is a way to do that
ajaxGet("https://api.openweathermap.org/data/2.5/onecall?lat=4.6097&lon=-74.0817&exclude=current,minutely,hourly,alerts&units=metric", function (response) {
var data = JSON.parse(response);
console.log(data);
data.daily
.map(datapoint => datapoint.temp) //get the temp value/object from each datapoint
.map(temp => { //create an element and add each max/min value to that element's textContent
const temperature = document.createElement("h6");
temperature.textContent = temp.max + "° / " + temp.min + "°";
return temperature;
})
.forEach(element => { //add each of the elements created in the previous map to the desired element
document.getElementById("temperaturaBogVier").appendChild(element);
});
});
As pointed out in the other answer, I've also removed the app-id query parameter

Previous array data gets printed to string

this is related to the code from my previous question, but this new problem is related to printing array data into a string, which then is passed on to the text on my page
My page "rolls" genetic data, which is presented as gene abbreviations. Under the abbreviations, i want to list the gene names. What happens is that the array values from a previous "roll" gets printed underneath a new roll, meaning that the array that contains the gene names is always one "roll" behind.
i suspect it has to do with the fact that im using $.getJSON, but I'm not sure how to use the current data instead of the previous data.
here is what my code for this part looks like:
$.getJSON('genes.json', function(data){
$.each(data.gCommon, function(i, g) {
if(genoArray.includes(g.rec) || genoArray.includes(g.dom)){
phenoArray.push(g.phen);
}
});
getPheno(phenoArray);
});
function getPheno(phenoArray){
console.log(genoArray);
console.log(phenoArray);
$phenoString = phenoArray.join(", ");
}
$babyGenes = genoArray.join("/");
if(genoArray.length > 1){
$babyPheno = $phenoString.replace(/("[^"]+"|\w+)$/, "and $1");
} else {
$babyPheno = $phenoString;
}
console.log("Baby: " + $babyGenes);
console.log("Pheno: " + $babyPheno);
any advice helps, thanks in advance!!

How can I replace specific objects in parse to objects inputted by the user?

I have objects in Parse called "Post" and within that, I have columns called "title" and "content". I am trying to ask the user for an input value and save this as a variable, also called "content". If the user's input value ("content") matches a "content" value already saved in parse.com, I want to replace the "content" value in parse.com with the variable saved in "newlocation" (also inputted by the user).
The replacing part is not working and I am getting the error "objects.set is not a function". What am I doing incorrectly and what can I change so that if the variable "content" matches a content value in parse.com, it is replaced with the variable saved in "newlocation"? Thank you in advance.
My code is shown below:
function postsSameAs(content){
var Post = Parse.Object.extend("Post");
var query = new Parse.Query(Post);
query.equalTo("content", content);
return query.find();
}
$("#post-form-change").submit(function(event){
event.preventDefault();
var content = $("#post-original").val();
var newlocation = $("#post-new").val();
postsSameAs(content).then(function(objects){
console.log("replacing " + JSON.stringify(objects));
objects.set("newlocation", newlocation); //should replace the "content" value in parse.com to the variable saved in "newlocation"
return objects.save();
window.alert("You have successfully replaced " + content + " to " + newlocation);
}, function(error) {
console.log("error " + JSON.stringify(error));
});
});
The problem with the code is that find() resolves as an array of matching objects. objects.set(... is no good because objects is an array. Do you expect only one Post from the query? In that case, replace query.find() with query.first()
Try objects["newlocation"] = newLocation;

Parsing a JSON object in node.js

{"__v":0,"_id":{"$oid":"55f13d34258687e0bb9e4385"},"admin":true,"email":"emaple1#gmail.com","last_login":"11:25:24 AM","name_surname":"user1","password":"qwerty123"}
{"__v":0,"_id":{"$oid":"55ef49dd5d610eab18719deb"},"admin":true,"email":"emaple2#gmail.com","last_login":"12:25:24 AM","name_surname":"user2","password":"qwerty123"}
{"__v":0,"_id":{"$oid":"55f0173bb3322bf560724fd1"},"admin":true,"email":"emaple3#gmail.com","last_login":"10:25:24 AM","name_surname":"user3","password":"qwerty123"}
Hello, I working in nodeJS file and there I have a collection of JSON objects and I would like to make a search through it. For each user from this list I need to compare the field "last_login" .
I am new to nodeJS can someone help? Thank you!
This is what i have tried:
User.find({}, {last_login: }, function(err, docs) {
if (err) {
return res.json({ success: false, message: 'Failed to display last logins.' });
}
docs.forEach(function(doc, index) {
res.json({success: true, message: 'time of last login', last_login: doc.last_login});
})
//res.json(users);
});
});   
Where last_login is a field in the User object and basically I need to iterate over all users in the db and extract only the last_login and display in in the response.I don’t know what value to put in the find() inside the curly braces
this is the part where I am stuck
I’ve slightly changed the function and it returns a JSON object containing the info about one user that is matched with the search query. The problem is, the console displays the result, as a whole object, although I want to get only a specific key value pair and namely last_login: value
function searchByUserName(name_surname) {
    return list.filter(function(user) {
        return user.name_surname === name_surname;
    });
}
var a = searchByUserName('user1');
for (last_login in a ) {
  if (a.hasOwnProperty(last_login)) {
    console.log("last_login" + "=" + JSON.stringify(a[last_login]))
  }
}
Can you tell me please, what change to make in order to get only the last_login key
here is a sample result from the console.log() that I receive:
last_login={"__v":0,"_id":{"$oid":"55f13d34258687e0bb9e4385"},"admin":true,"email":"emaple1#gmail.com","last_login":"11:25:24 AM","name_surname":"user1","password":"qwerty123"}
although I want last_login = “last_login”: 11:25:24 AM
Assuming it's an array of objects like bellow.
var users = [{"__v":0,"_id":{"$oid":"55f13d34258687e0bb9e4385"},"admin":true,"email":"emaple1#gmail.com","last_login":"11:25:24 AM","name_surname":"user1","password":"qwerty123"},
{"__v":0,"_id":{"$oid":"55ef49dd5d610eab18719deb"},"admin":true,"email":"emaple2#gmail.com","last_login":"12:25:24 AM","name_surname":"user2","password":"qwerty123"},
{"__v":0,"_id":{"$oid":"55f0173bb3322bf560724fd1"},"admin":true,"email":"emaple3#gmail.com","last_login":"10:25:24 AM","name_surname":"user3","password":"qwerty123"}];
you can create a function like bellow
function searchByLastLogin(last_login) {
return users.filter(function(user) {
return user.last_login === last_login;
});
}
console.log(searchByLastLogin("12:25:24 AM"));
console.log(searchByLastLogin("10:25:24 AM"));
console.log(searchByLastLogin("11:25:24 AM"));
It will retrun a array of users whose last_login will match to given parameter last_login.
Update
What I understood from your comment bellow, you want last logins of every user.
For that you can do something like bellow
var last_logins = users.map(function(user){
return user.last_login;
});
console.log(last_logins); //prints [ '11:25:24 AM', '12:25:24 AM', '10:25:24 AM' ]
References
filter | map
I don’t know what value to put in the find() inside the curly braces this is the part where I am stuck
If I understand correctly, you only want to get the last_login field for the user model, and that's what you're struggling with ?
According to the documentation, this should work if you only want to get that field :
User.find({}, {last_login:1, _id:0})

How to encode cookie with javascript/jquery?

I am working on an online shop together with my friend. He set a cookie for me with PHP with the amount of added products to the Cart. The cookie is called "cart", and the variable with the amount of the products is called "items".
And I have to read the cookie and get the value of "cart" back with javascript and print it in the HTML document, but I have no Idea how to use it, can you please help me? I have never worked with cookies or JSON before, but I think it should be done with JSON, can you please explain it to me how it works?
when I do : console.log(document.cookie);
I receive something like this: cart=%7B%22items%22%3A%7B%228%22%3A1%7D%7D;
And I have no idea how to encode it.
Thank you
That is the URL encoded equivalent of {"items":{"8":1}} which is the JSON string you want.
All you have to do is decode it and parse the JSON:
var cart = JSON.parse(decodeURIComponent(document.cookie.cart));
Then logging cart should give you an object with an 'items' property that you can access as needed.
EDIT:
As an example, here's a way to iterate through the items and determine the total number of items and the total of all their quantities.
var items_total = 0,
quantity_total = 0;
for (var prop in cart.items) {
items_total += 1;
quantity_total += cart.items[prop];
}
console.log("Total Items: " + items_total);
console.log("Total Quantities: " + quantity_total);
Looks like you just need to decode it, then you will want to parse/eval it to get a workable object:
var obj, decoded = decodeURIComponent(document.cookie.cart);
if(window.JSON && JSON.parse){
obj = JSON.parse(decoded);
} else {
eval('obj = ' + decoded);
}
// obj == {"items":{"8":1}};

Categories

Resources