Azure mobile services javascript Update from the insert function - javascript

I am creating a mobile application for windows phone 8, iOs android. I'm using windows azure for holding some profile application and some device information. I have very little experience with JavaScript although after banging my head against a brick wall all day its starting to click i think. This being said you'll probably laugh at my code below.
This (below) is the insert statement for a table called Devices.
im trying to do a normal insert if there isn't currently any record for the userId.
If there is already a record then update that record instead.
function insert(item, user, request) {
item.userId = user.userId;
var deviceTable = tables.getTable('Devices');
deviceTable
.where({
userId: user.userId
}).read({
success: function(results) {
if (results.length > 0) {
// Device record was found. Continue normal execution.
deviceTable.where({
userID : user.userId}).update({
//i put this here just because i thought there had to be a response
success: request.respond(statusCodes.OK, 'Text length must be under 10')
}) ;
console.log('updated position ok');
} else {
request.execute();
console.log('Added New Entry',user.userId);
//request.respond(statusCodes.FORBIDDEN, 'You do not have permission to submit orders.');
}
}
});
}

I think you'll want something like this:
function insert(item, user, request) {
item.userId = user.userId;
var deviceTable = tables.getTable('Devices');
deviceTable
.where({
userId: user.userId
}).read({
success: function(results) {
if (results.length > 0) {
//We found a record, update some values in it
results[0].fieldName = X;
//Update it in the DB
deviceTable.update(results[0]);
//Respond to the client
request.respond(200, results[0]);
console.log('updated position ok');
} else {
//Perform the insert in the DB
request.execute();
console.log('Added New Entry',user.userId);
//Reply with 201 (created) and the updated item
request.respond(201, item);
}
}
});
}

Related

How to add the value from an input box to an array and then output its contents?

How can I go about adding the value of an input box into an array and then display the contents of that array?
This is what I've come up with and I'm not sure why it's not working - the console.log doesn't post anything to the console, either.
var user = user;
if (!user) {
user = prompt('Please choose a username:');
if (!user) {
alert('Your name has been set to "Anonymous"');
} else {
alert('Your name has been set to "'+ user +'"');
}
}
var items = [];
function userArray() {
items.push(user);
return false;
console.log(items);
}
socket.on('onlineUsers', function (data) {
$('.dispUser').html(items);
});
The rest of the code in the file is below, just in case it helps... (changed the return statement, as per the first answer)
var user = user;
if (!user) {
user = prompt('Please choose a username:');
if (!user) {
alert('Your name has been set to "Anonymous"');
} else {
alert('Your name has been set to "'+ user +'"');
}
}
var items = [];
function userArray() {
items.push(users);
console.log(items);
return false;
}
socket.on('onlineUsers', function (data) {
$('.dispUser').html(items);
});
//Counts the number of users online
socket.on('count', function (data) {
$('.user-count').html(data);
});
//Receives messages and outputs it to the chat section
socket.on('message', function (data) {
$('.chat').append('<p><strong>' + data.user + '</strong>: ' + data.message + '</p>');
$('.chat').scrollTop($('.chat').height());
});
//SENDING OF THE MESSAGE
//Submit the form through HTTPS
$('form').submit(function (e) {
e.preventDefault();
// Retrieve the message from the user
var message = $(e.target).find('input').val();
// Send the message to the server
socket.emit('message', {
user: user || 'Anonymous',
message: message
});
// Clears the message box after the message has been sent
e.target.reset();
$(e.target).find('input').focus();
});
Answer
Your implementation is fine, but you have a bug which is preventing it from working as you've described.
The call to console.log(items) does not print anything, because that line of code never runs.
When you return from a function, the subsequent lines of code will not be ran. You should return as the last line within your function, or wrap it in a conditional.
For example:
function userArray() {
items.push(user);
console.log(items);
return false;
}
How to debug
Learning the techniques to figure this issue out yourself is an invaluable tool. You can leverage a debugger, such as the Chrome Devtools, to add breakpoints to your code. These will allow you to stop execution on a particular line, view the value of variables, and step through the remaining lines of code.
Doing so would make it clearly visible that the line of code is never running.
Find more details here: https://developers.google.com/web/tools/chrome-devtools/javascript

How to get parent and their childs entry from parse server?

I'm using parse open source. I have three tables:
1. ForumPost
2. ForumReply
3. ForumComment
When a user creates a post it will store into ForumPost, when someone adds a reply to the post we are storing post reply on ForumReply table. Now any user can comment on Forum Reply we are storing comments into ForumComment.
What I want: I have an post id, Now I want to get all reply of that post along with their respective comments.
What I have done I am able to get Post Reply but not able to get their comments in the same query. I am calling a Cloud function for every post reply to get comments.
Here is my current code
isRequestLegitimate(request).then(function(result) {
if (result.legitimateRequest) {
var forumQuery = new Parse.Query("ForumPost");
var userPointer = new Parse.User();
userPointer.id = result.activeUserId;
forumQuery.equalTo("objectId", request.params.postId);
forumQuery.include("offer");
forumQuery.include("offer.artist");
forumQuery.include("creator");
forumQuery.include("replies");
forumQuery.include("replies.comments");
forumQuery.include("replies.creator");
forumQuery.select("objectId","offer", "offer.isActive","offer.stopDate", "offer.objectId", "offer.artist.firstname", "offer.artist.lastname",
"offer.title", "offer.picHash", "title", "text", "offer.offer", "creator", "creator.firstname",
"creator.lastname", "replies", "replies.objectId", "replies.text", "replies.creator.firstname", "replies.creator.lastname",
"replies.isRead", "replies.comments.isRead");
forumQuery.first({
useMasterKey: true
}).then(function(forumPost) {
if (forumPost == null) {
response.success("0"); //not found
} else {
response.success(forumPost);
}
}, function(error) {
response.error(error);
});
} else {
response.error("You must be logged in!");
}
});
});```
Could someone please let me know how I can fetch comments?

Google Smartlock: what to do when PromiseStatus: pending via Javascript in console

we are integrating Google Smartlock. Every time we run the JS code to enable Smart lock on 1 screen it does nothing at all. And when we trigger it manually we only see this in console log.
Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}
javascript is like this
<script>
window.onload=function(e){
var debug = true;
var always = function() { console.log('Promise resolved: but dont understand how should process: we want/need to login') }
navigator.credentials.get({password: true, unmediated: true, }).then(function(cred) {
if (cred) {
if (cred.type == 'password') {
var form = new FormData();
cred.additionalData = form;
var url = 'domain.com/login';
fetch(url, {method: 'POST', credentials: cred }).then(function(response) {
if (response.status == 202) {
if (debug) { console.log('Login success; reload stopped'); exit; }
window.location.reload();
}
if (debug) { console.log('Server status: ' + response.status); }
return;
}).catch(function(err) { console.log('Smartlock Ajax error:'+ err);
}).then(always, always);
} // can add federated here
} else if (typeof cred === "undefined") {
// user clicks cancel or no credentials found
var expiry = new Date(); expiry.setDate(expiry.getDate() + (1/3600*30));
document.cookie="dontshowagain=true; expires=" + expiry.toGMTString();
}
});
}
</script>
Question: Does anyone know what is happening here?
I tested with 1 saved passwd, with 2 saved passwd's. We do see the small key icon next to the URL in Chrome. But it doesn't popup or do anything.
Help/advise appreciated
References:
https://support.google.com/accounts/answer/6160273?hl=en
It looks like you're requesting unmediated: true which forces the browser to not show the account selector UI.
When you have more than one credentials stored or one credential that requires user mediation, get(...) returns undefined unless you allow the mediation (unmediated: false which is default).
Note: Your credentials should require mediation when the user signs out of an account (navigator.credentials.requireUserMediation()).

Phonegap: insert query sqlite when login success

I build an mobile app hibrid base with phonegap and jquery mobile. My app has a login system, retrieve data from database in server and insert it to sqlite when login succes, so the app can access to the data even it's offline.
i use plugin from litehelpers. And this my sql connect script in database.js:
document.addEventListener("deviceready", connectDB, false);
var kode = JSON.parse(window.localStorage['konfirmasi']);
//create or open Database
function connectDB(){
db = window.sqlitePlugin.openDatabase("konfirmasi", "1.0", "Data Konfirmasi Pengiriman", "1000");
db.transaction(populateDB,successCB,errorCB);
}
//create table and insert some record
function populateDB(tx) {
tx.executeSql("CREATE TABLE IF NOT EXISTS data_konfirmasi (kode_transaksi text, status text) UNIQUE(kode_transaksi)");
}
//function will be called when an error occurred
function errorCB(err) {
console.log("Error processing SQL: "+err.code);
}
//function will be called when process succeed
function successCB() {
console.log("Connected to database!");
//db.transaction(queryDB,errorCB);
}
function insertDB(tx){
for (var i = kode.length - 1; i >= 0; i--) {
tx.executeSql("INSERT INTO data_konfirmasi VALUES ("+kode[i]+", 'Belum Terkirim');");
};
}
function queryDB(){
db.transaction(insertDB,errorCB,querySuccess);
}
function querySuccess(){
console.log('Insert query success!');
}
function dropDB(){
db.transaction(dropQuery,errorDrop,successDrop);
}
function dropQuery(tx){
tx.executeSql("DROP TABLE IF EXIST data_konfirmasi");
}
function successDrop(){
console.log('Drop table successful');
}
function errorDrop(err){
console.log('Drop table unsuccessful, Error code: '+err.code);
}
function selectData(err){
db.transaction(selectQuery, errorCB, successQuery)
}
function selectQuery(tx){
tx.executeSql('SELECT * FROM data_konfirmasi',[], querySuccess, errorCB);
}
function querySuccess(tx, results) {
console.log("Returned rows = " + results.rows.length);
// this will be true since it was a select statement and so rowsAffected was 0
if (!results.rowsAffected) {
console.log('No rows affected!');
return false;
}
// for an insert statement, this property will return the ID of the last inserted row
console.log("Last inserted row ID = " + results.insertId);
}
Then, when user login for the first time and success it will retrieve data from server with json, and i want my app to insert retrieved data to sqlite. So, how to put the query for login success only? After that i want to make it DROP table and clear localStorage when it's logout.
This is my login and logout script (main.js):
$(document).on('pageinit','#login',function(){
$(document).on('click','#submit',function(){
if($('#username').val().length>0&&$('#password').val().length>0){
var un = $('#username').val();
var pw = $('#password').val();
$.ajax({
url:'http://qrkonfirmasi.16mb.com/delivery/login.php',
data:{ username : un,
password : pw
},
type:'post',
async:'false',
dataType: 'json',
beforeSend:function(){
$.mobile.loading('show',{theme:"a",text:"Please wait...",textonly:true,textVisible:true});
},
complete:function(){
$.mobile.loading('hide');
},
success:function(result){
console.log(result);
if(result.status==true){
user.name=result.message;
window.localStorage.setItem('konfirmasi', JSON.stringify(result.data));
console.log('Kode: ', JSON.parse(window.localStorage['konfirmasi']));
var kode = JSON.parse(window.localStorage['konfirmasi']);
console.log('Array length: '+kode.length);
queryDB();
console.log('Login berhasil');
$.mobile.changePage("#konfirmasi");
window.localStorage.setItem('uname', un);
window.localStorage.setItem('passwd', pw);
console.log(window.localStorage['uname']);
}else{
alert('Login gagal. Username atau password tidak sesuai');
}
},
error:function(request,error){
alert('Koneksi error. Silahkan coba beberapa saat lagi!');
}
});
}else{
alert('Masukkan username dan password!');
}
return false;
});
});
$(document).on('pagebeforeshow','#konfirmasi',function(){
$.mobile.activePage.find('.welcome').html('<h3>Selamat Datang '+user.name+'</h3>' );
});
$(document).off('click').on('click','#logout',function(){
window.localStorage.clear();
dropDB();
$.mobile.changePage("#home");
});
function exitFromApp(){
navigator.app.exitApp();
}
So, am i at the right way for logout script? I didn't know it works or not because i still cannot try it because the login script still error when i try it with insert query.
Can someone help me make it done, please?
Where are u calling this piece of code from?
function insertDB(tx,val){
for (var i = kode.length - 1; i >= 0; i--) {
tx.executeSql('INSERT INTO konfirmasi VALUES ('+a[i]+');',querySuccess,errorCB);
};
}
If you are calling it from a transaction, then the "val" parameter will not be passed to the insertDB function directly. You might try the following thing:
val = [];
db.transaction(function(tx){
insertDB(tx, val);
}, errorCB);
Moreover, make sure that the stements always run within a db.transaction context
Have fun!

How is a plugin like facebook login plugin build up?

How does the plugin communicate with the facebook server without exposing too much information.
I would like to know how I can build myself a plugin that would communicate between the website it's installed on and my website.
My knowledge is limited to HTML5, CSS3, PHP5, Javascript and some Jquery.
I realise that there could be alot of ways, I was just wandering if you could point me in the right direction, or give me an idea. (: thanks in advance!
Take a look at the easyXDM framework, which allows you to do this quite easily, and if you have a chance, read Third Party JavaScript, which explains what you want to do in detail.
Some years ago, I wrote about this topic on scriptjunkie, it's as relevant now as then (although more browsers support postMessage now).
Create an application on developers.facebook.com
Download the facebook SDK for PHP since this is what you know (https://developers.facebook.com/docs/reference/php)
Read their guideline on how to implement login (it is easy and helpful)
https://developers.facebook.com/docs/facebook-login/login-flow-for-web/
This is a sample PHP function that you can build on:
function facebook_login()
{
$user = new user();
// Call Facebook API
if (!class_exists('FacebookApiException')) {
require_once ('facebook.php');
}
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
));
$fbuser = $facebook->getUser();
if ($fbuser) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$me = $facebook->api('/me'); //user
$uid = $facebook->getUser();
}
catch(FacebookApiException $e) {
echo error_log($e);
return;
}
}
// redirect user to facebook login page if empty data or fresh login requires
if (!$fbuser) {
$loginUrl = $facebook - getLoginUrl(array(
'redirect_uri' => $_SERVER["HTTP_REFERER"],
false
));
$logout = $facebook->getLoginUrl();
echo $loginUrl;
return;
}
// user details
$user->name = $me['name'];
$user->email = $me['email'];
$user->fbid = $uid;
// Check user id in your database
$user->selectbyfbid();
if ($user->database->rows > 0) {
// User exist, Show welcome back message
// User is now connected, log him in
}
else {
// User is new, Show connected message and store info in our Database
// Insert user into Database.
$user->insert_fb();
}
$_SESSION["access_token"] = $facebook->getAccessToken();
login_user($user);
}
In your HTML:
<a href="#" onclick="LoadingAnimate();">
<div class="fb-login-button"
onlogin="javascript:CallAfterLogin();"
data-width="600" data-max-rows="1"
data-show-faces="false"
scope="publish_stream,email,publish_actions,offline_access">
JavaScript code:
function CallAfterLogin(){
FB.login(function(response) {
if (response.status === "connected")
{
LoadingAnimate(); //show a waiting gif or whatever
FB.api('/me', function(data) {
if(data.email == null)
{
//Facbeook user email is empty, you can check something like this.
ResetAnimate();
}else{
AjaxResponse();
}
});
}
});
}
function AjaxResponse()
{
var myData = 'connect=1&action=fb_login';
jQuery.ajax({
type: "POST",
url: "/process_user.php",
dataType:"html",
data:myData,
cache: false,
success:function(response){
if(target.length > 1)
window.location.href = target;
else
location.reload();
},
error:function (xhr, ajaxOptions, thrownError){
//$("#results").html('<fieldset style="color:red;">'+thrownError+'</fieldset>'); //Error
}
});
}
I hope this helps you start!

Categories

Resources