I'm learning javascript and windowsazure mobile services. As a learning lesson I created a "users" table and inserted a test user. I'm actually using icenium to write a demo app for the ipad and andoid tablets, but I can't seem to figure out even the most basic request. So I've setup a jsfiddle here: http://jsfiddle.net/MNubd/5/.
It is a simple input box:
<input id="uFullName" type="text" />
and some javascript code. I'm trying to retrieve the "name" column from the table "users" and display it in the input box:
alert('running');
var client = new WindowsAzure.MobileServiceClient('https://mtdemo.azure-mobile.net/', 'MtxOqGpaBzuPRtnkIifqCKjVDocRPY47');
usersTable = client.getTable('users');
usersTable.where({ userID: 'impretty#blockedheaded.com' }).read({
success: function (results) {
$('#uFullName').val(results);
},
error: function (err) {
$('#uFullName').val('there was and err');
}
});
Thanks for your help!
EDIT: I had no idea the success function could only be used on server scripts. Thanks. Here is the code that ended up working for me:
function signInButton(e) {
var un = $('#username');
uName = un.val();
var client = new WindowsAzure.MobileServiceClient('https://mtdemo.azure-mobile.net/', 'MtxOqGpaBzuPRtnkIifqCKjVDocRPY47');
//alert('lookup: ' + uName);
usersTable = client.getTable('users');
usersTable.where({ userID: uName })
.read()
.done(
function (results) {
try {
xUserName = results[0].name; //using this to trigger an exception if the login credentials don't match.
xUserID = results[0].id; // save this for querying and adding records for this user only.
//alert('found');
app.application.navigate('#view-menu');
}
catch(err) {
//alert('not found');
document.getElementById('errorText').textContent = "Check Email and Password!";
}
}
);//end of the done
The options object with the success and error callback objects is only used in server-side scripts. For the client side, the programming model is based on promises, and you should use the done() (or then()) continuation to get the results:
var client = new WindowsAzure.MobileServiceClient('https://mtdemo.azure-mobile.net/', 'YOUR-KEY');
var usersTable = client.getTable('users');
usersTable.where({ userID: 'impretty#blockheaded.com' }).read().done(function (result) {
$("#uFullName").val(result.name);
}, function (err) {
$("#uFullName").val('There was an error: ' + JSON.stringify(err));
});
Related
I am coding a simple registration form using mongoose.
I have use a javascript file to process the values of the registration form.
Here is my registrationButtonAction.js
window.onload = function() {
var User = require('/models/Mongoose Database/user_database');
// this line is causing the problem
var registerButton = document.getElementById("registerMe");
var firstName = document.getElementById("firstName");
var lastName = document.getElementById("lastName");
var usernameRegister = document.getElementById("usernameRegister");
var passwordRegister = document.getElementById("passwordRegister");
var repasswordRegister = document.getElementById("repasswordRegister");
registerButton.onclick = function () {
if(!firstName.value || !passwordRegister.value || !repasswordRegister.value || !usernameRegister.value){
alert("Enter all required fields");
}else if (passwordRegister.value != repasswordRegister.value){
alert("Passwords must match");
}else {
var newUser = new User({
username : usernameRegister.value,
password : passwordRegister.value
});
User.find({username:usernameRegister.value}, function (error, user) {
if (error) throw error;
if(user){
window.location("/register");
}else {
newUser.save(function (error) {
if(error) throw error;
});
window.location("/login");
}
// user.comparePassword(passwordRegister.value, function (error, isMatch) {
// if (error) throw error;
//
// return 1;
//})
});
}
}
}
When I comment the var User = require('/models/Mongoose Database/user_database');, all the checks are working fine inside the onclick function. But when I uncomment it, it is not recognizing the button click.
I want to know whether this is a correct way of taking values from the registration page and storing them in a mongoose database.
You are mixing server and client code. Mongoose models and Node.js functions are not accessible inside window.onload on your client.
To put it simply, you need to create a REST API to perform database operations on the server. You have all the right tools aready, just need to reorder them.
The flow would be as such :
get the values entered in the browser
call an endpoint on your server (for example /api/createUser)
in the express router, have a route called /api/createUser in which you can access your User model and perform creation/deletion/update, etc.
My suggestion would be for you to go through this tutorial which should remove your confusion and bring you up to speed in no time. Good Luck!
Also, Passport can help you with authentication, but I believe you should first learn how to build a basic API. Authentication is a tricky beast ;)
On our website I want people to be able to report if a video is uploaded on Youtube so we have 3 fields on our website. A Username, password and video Id field. When the user clicks the Html button we have it call a javascript function.
function reportUpload() {
Parse.Cloud.run('report_upload',
{
username: "testUser",
password: "testPassword",
videoId: "VQv9xfOfLOY"
},{
success: function(result) {
//Do Neat Stuff
},
error: function(e) {
//error
}
});
}
That then calls our cloud code function. We need the cloud code function to pull the usernames from the User class and test if any of them match. If any do match they will then need to check if the passwords match. if all of that doesn't fail it will send a push notification to one of the users of the app.
So far in the cloud code funtion I have figured out how to query all the usernames.
Parse.Cloud.define("report_upload", function(request, response) {
console.log(request.params);
var query = new Parse.Query(Parse.User);
query.find({
success: function(results){
var users = [];
//extract out user names from results
for(var i = 0; i < results.length; ++i){
users.push(results[i].get("username"));
}
response.success(users);
console.log(JSON.stringify(users));
}, error: function(error){
response.error("Error");
}
});
});
Thanks
Seems like you want to check if a particular user has made an account already with a particular username.
You will have to query the User class. The user class is secured by default.
In the cloud code, you should write Parse.useMasterKey(); to have a full access (Careful, read note below).
var myquery = new Parse.Query(Parse.User);
myquery.equalTo("username",yourUsernameHere);
myquery.find({
success: function(results){
if(results.length === 0)
{
// User not found
}
else
{
// found
}
});
Note: Using the master key overrides all individual access privileges for your data. Be absolutely sure what you are doing.
Here is a question for parse.com gurus.
I am using Parse Javascript API and trying to execute a query over 2 Pointers and cannot get it to work.
So i have following classes: Posts, Users, Groups. Posts has Pointer to Users. Users has a Pointer to Groups.
I need to get all POSTS, where a USER belongs to GROUP, which name starts with "Admin". Here is my code that doesn't work:
var Posts = Parse.Object.extend("Posts");
var Users = Parse.Object.extend("Users");
var Groups = Parse.Object.extend("Groups");
var query = new Parse.Query(Posts);
var innerQueryUsers = new Parse.Query(Users);
var innerQueryGroups = new Parse.Query(Groups);
innerQueryGroups.startsWith("name", "Admin");
innerQueryUsers.matchesQuery("group", innerQueryGroups);
query.matchesQuery("user", innerQueryUsers);
query.find({
success: function(data) {
},
error: function(error){
// here i get error: {code: 102, message: "bad type for $inQuery"}
}
});
Anybody have an idea how to do it right?
Edit - This can be done in one (untested) query by combining a group query and a post query with the same user query...
function postsInGroup(name) {
var groupQuery = new Parse.Query("Group");
groupQuery.equalTo("name", name);
var userQuery = new Parse.Query(Parse.User);
userQuery.matchesQuery("group", groupQuery);
var postQuery = new Parse.Query("Post");
postQuery.matchesQuery("user", userQuery);
return postQuery.find();
}
Call it like this...
postsInGroup("Admin").then(function(posts) {
console.log(JSON.stringify(posts));
}, function(error) {
console.log(JSON.stringify(error));
});
Its not clear what savings there is between this approach and first querying the group. It's likely that parse.com runs the inner queries much as you would. The difference in readability is a matter of taste.
I am making a newsreader app and using Parse.com background jobs to collect links from RSS feed of the newspaper. I have used xmlreader.js and sax.js to parse the httpResponse and using saveAll and beforeSave, periodically update the classes in data browser.
I have multiple newspapers with multiple categories making a total of more than 30 pairs, (I would have to later include more pair as I would like to include regional newspapers). Till now I was working with one newspaper and one category - The Hindu, sports category; and it is now working fine. Making copies of these two function and create jobs wont be efficient I think.
Therefore, I wanted to ask if I can convert both these jobs and beforeSave into some kind of function so that I can just pass in either newspaper-category pair class name or its url to do the stuff automatically.
Full Code - main.js
job -
Parse.Cloud.job("job_hindu_sports", function (request, response) {
return Parse.Cloud.httpRequest({
url: 'http://www.thehindu.com/sport/?service=rss'
}).then(function(httpResponse) {
var someXml = httpResponse.text;
xmlreader.read(someXml, function (err, res){
if(err) {
response.error("Error " +err);
return console.log(err);
}
var listArray = [];
res.rss.channel.item.each(function (i, item){
var hinduSports = new HinduSports(); //#startswithaj - this part
hinduSports.set("link", item.link.text());
hinduSports.set("title", item.title.text());
hinduSports.set("pubDate", item.pubDate.text());
//console.log("pubDate - "+ item.pubDate.text());
listArray.push(hinduSports);
});
var promises = [];
Parse.Object.saveAll(listArray, {
success: function(objs) {
promises.push(objs);
console.log("SAVED ALL!");
},
error: function(error) {
console.log("ERROR WHILE SAVING - "+error);
}
});
return Parse.Promise.when(promises);
});
}).then(function() {
response.success("Saving completed successfully.");
},function(error) {
response.error("Uh oh, something went wrong.");
});
});
beforeSave -
Parse.Cloud.beforeSave("HinduSports", function(request, response) {
//console.log("in beforeSave");
var query = new Parse.Query(HinduSports);
var linkText = request.object.get("link")
var titleText = request.object.get("title");
query.equalTo("link", linkText);
query.first({
success: function(object) {
//console.log("in query");
if (object) {
//console.log("found");
if(object.get('title')!==titleText){
console.log("title not same");
object.set("title", titleText);
response.success();
}
else{
console.log("title same");
response.error();
}
} else {
console.log("not found");
response.success();
}
},
error: function(error) {
response.error();
}
});
});
In your job code you could query your datastore for all of the URLS you want to process, and then iterate through the results requesting each url and passing the httpresponse to a function that does all the work
So you would have (pseudo code)
function getDataForNewspaper(id, url){
return (function(id) {
Parse.Cloud.httpRequest({
url: url
}).then(function(httpResponse){
processDataForNewspaper(id, httpResponse)
})
})(id) //you need to have this in a closure so you can pass id to processDataFor...
function processDataforNewpaper(id, httpResponse){
someXml = httpResponse.text
//process your xml here
}
Parse.Cloud.job("get_data_for_all_newspapers", function (request, response) {
var query = new Parse.Query("Get all the newspapers").find{
success: function(list){
for each newspaper in list then
getDataForNewspaper(newspaper.id, newspaper.url)
}
}
}
It's not the best explanation but I hope this helps
With the help from #startswithaj I modified my code to save all the articles in one class. The only thing left is to add a beforeSave method. But there is still a problem. saveAll gets completed only sometimes. For eg. I ran the code first time and got this in log :
I2014-04-26T18:18:40.036Z] v93: Ran job job_get_data_for_all_newspapers with:
Input: {}
Result: Saving completed successfully.
I2014-04-26T18:18:40.926Z] Successfully retrieved 2
I2014-04-26T18:18:40.926Z] getData NEW & CAT ID - 1, 5 feedUrl http://www.thehindu.com/sport/?service=rss
I2014-04-26T18:18:40.927Z] getData NEW & CAT ID - 1, 4 feedUrl http://www.thehindu.com/news/national/?service=rss
I2014-04-26T18:18:40.927Z] promisesGetNP [object Object],[object Object]
I2014-04-26T18:18:41.479Z] processData NEW & CAT ID - 1, 5
I2014-04-26T18:18:41.622Z] listArray http://www.thehindu.com/sport/other-sports/mankirat-singh-sets-record/article5951540.ece?utm_source=RSS_Feed&utm_medium=RSS&utm_campaign=RSS_Syndication
I2014-04-26T18:18:41.628Z] promises undefined
I2014-04-26T18:18:41.629Z] promisesGetData
I2014-04-26T18:18:41.629Z] Done getData?
I2014-04-26T18:18:42.082Z] processData NEW & CAT ID - 1, 4
I2014-04-26T18:18:42.311Z] listArray http://www.thehindu.com/news/national/muslim-women-entitled-to-maintenance-even-after-divorce-supreme-court/article5951562.ece?utm_source=RSS_Feed&utm_medium=RSS&utm_campaign=RSS_Syndication
I2014-04-26T18:18:42.324Z] promises undefined
I2014-04-26T18:18:42.324Z] promisesGetData
I2014-04-26T18:18:42.324Z] Done getData?
I2014-04-26T18:18:42.324Z] done job
and second time after deleting a few useless console.log I got this. You can see there is a SAVED ALL! which is called in the success: function of the saveAll -
I2014-04-26T18:20:53.130Z] v94: Ran job job_get_data_for_all_newspapers with:
Input: {}
Result: Saving completed successfully.
I2014-04-26T18:20:53.307Z] Successfully retrieved 2
I2014-04-26T18:20:53.307Z] getData NEW & CAT ID - 1, 5 feedUrl http://www.thehindu.com/sport/?service=rss
I2014-04-26T18:20:53.307Z] getData NEW & CAT ID - 1, 4 feedUrl http://www.thehindu.com/news/national/?service=rss
I2014-04-26T18:20:53.911Z] processData NEW & CAT ID - 1, 5
I2014-04-26T18:20:53.951Z] listArray http://www.thehindu.com/sport/other-sports/mankirat-singh-sets-record/article5951540.ece?utm_source=RSS_Feed&utm_medium=RSS&utm_campaign=RSS_Syndication
I2014-04-26T18:20:53.995Z] Done getData?
I2014-04-26T18:20:54.200Z] SAVED ALL!
I2014-04-26T18:20:54.818Z] processData NEW & CAT ID - 1, 4
I2014-04-26T18:20:55.016Z] listArray http://www.thehindu.com/news/national/muslim-women-entitled-to-maintenance-even-after-divorce-supreme-court/article5951562.ece?utm_source=RSS_Feed&utm_medium=RSS&utm_campaign=RSS_Syndication
I2014-04-26T18:20:55.031Z] Done getData?
I2014-04-26T18:20:55.031Z] done job
My new code can be found here. The new code starts at Line 150.
Whenever I launch my Windows Store application, I get an error that 'alert' is undefined. I'm trying to query a table in Azure Mobile Services and make a list out of the column "type_of_service" from that table.
var typeOfServiceTable = client.getTable('TypeOfService');
// Create a list of type of services
var query = typeOfServiceTable.select("type_of_service").read().done(function (results) {
alert(JSON.stringify(results));
}, function (err) {
alert("Error: " + err);
})
alert() can not be used on Windows Store application.
Instead of using alert(), try the following function:
var msg = new Windows.UI.Popups.MessageDialog("Hello Windows!");
msg.showAsync();