How to sign up/login a user using phonegap + quickblox? - javascript

I have been been working on an app in phonegap, wanting to make calls to the quickblox backend service.
The app successfully gets the app token and creates an API session but the user.create code fails - here is my code from index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title></title>
<!-- -->
<link rel="stylesheet" href="css/themes/.css" />
<link rel="stylesheet" href="css/themes/jquery.mobile.icons.min.css" />
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.3/jquery.mobile.structure-1.4.3.min.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.3/jquery.mobile-1.4.3.min.js"></script>
<script src="js/config.js"></script>
<script src="js/quickblox.js"></script>
</head>
<body>
<div style="width:100%;">
<h1 style="text-align:center;">The Activity Network</h1>
</div>
<div>
<div data-role="tabs" id="tabs">
<div data-role="navbar">
<ul>
<li>Login</li>
<li>Register</li>
</ul>
</div>
<div id="one">
<h2>Login</h2>
<input type="text" id="new_login" placeholder="Username" />
<input type="password" id="new_password" placeholder="Password" />
<input id="auth" type="submit" value="Submit" onclick="window.location='sportsSelector.html'" />
</div>
<div id="two">
<h2>Register</h2>
<input type="text" id="login" placeholder="Username"/>
<input type="email" id="email" placeholder="E-Mail Address"/>
<input type="email" id="confirmEmail" placeholder="Confirm E-Mail Address"/>
<input type="password" id="password" placeholder="************"/>
<input type="password" value="confirmPassword" placeholder="************"/>
<input id="register" type="submit" value="Submit" />
</div>
</div>
</div>
<!-- Cordova reference, this is added to your app when it's built. -->
<script src="cordova.js"></script>
<script src="scripts/platformOverrides.js"></script>
<script src="scripts/index.js"></script>
<script>
$(document).ready(function () {
QB.init(QBAPP.app_id, QBAPP.auth_key, QBAPP.auth_secret);
//console.log(QBAPP.app_id, QBAPP.auth_key, QBAPP.auth_secret);
QB.createSession(function (err, result) {
console.log(result);
// callback function
});
});
var username;
var password;
var email;
$('#register').click(function () {
console.log("Ready! Getting the user details.");
username = document.getElementById('login').value;
password = document.getElementById('password').value;
email = document.getElementById('email').value;
console.log("Username: ", username);
console.log("Password: ", password);
console.log("E-Mail: ", email);
var params, connection;
params = {
login: username,
password: password,
email: email
};
//console.log("Params: ", params);
create(params);
});
function create(params) {
console.log("Creating new user");
QB.users.create(params, function (err, result) {
console.log("Result: ", result);
// callback function
});
}
</script>
</body>
</html>
If anyone can spot what Im missing then I'd really appreciate it. Currently, it spits out the following in the console:
XHR finished loading: POST "http://localhost:4400/ripple/xhr_proxy?tinyhippos_apikey=ABC&tinyhippos_rurl=https%3A//users.quickblox.com/users.json".
[DEBUG] Add new user: POST https://users.quickblox.com/users.json?user[owner_id]=&user[login]=Username&email[email]=undefined&user[password]=Password&token=undefined index.html:197
Failed to load resource: the server responded with a status of 500 (Internal Server Error) http://localhost:4400/ripple/xhr_proxy?tinyhippos_apikey=ABC&tinyhippos_rurl=https%3A//users.quickblox.com/users.json

I think one of your other scripts (local) might be interfering. Copied your code to jsfiddle, added some dummy credentials and it worked just fine.
$(document).ready(function () {
var QBAPP = {
app_id: replace_with_yours,
auth_key: replace_with_yours,
auth_secret: replace_with_yours
};
QB.init(QBAPP.app_id, QBAPP.auth_key, QBAPP.auth_secret);
QB.createSession(function (err, result) {
console.log(result);
// callback function
});
});
var username;
var password;
var email;
$('#register').click(function () {
console.log("Ready! Getting the user details.");
username = document.getElementById('login').value;
password = document.getElementById('password').value;
email = document.getElementById('email').value;
console.log("Username: ", username);
console.log("Password: ", password);
console.log("E-Mail: ", email);
var params, connection;
params = {
login: username,
password: password,
email: email
};
create(params);
});
function create(params) {
console.log("Creating new user");
QB.users.create(params, function (err, result) {
console.log("Result: ", result);
// callback function
});
}

Here is your request:
POST https://users.quickblox.com/users.json?user[owner_id]=1622883&user[login]=Username&email[email]=undefined&user[password]=Password&token=undefined
At least something wrong with email and token:
email[email]=undefined
token=undefined
try to check these parameters carefully

Related

How to submit form data to mongodb atlas

i want a user to input data in a form i created and i want the data to be sent to mongodb atlas.
so i host the form locally and it gives me an error "require is not defined".
my question is do i have to bundle the mongodb module or is there a way to do it without bundleing.
this is the code.
I USE THE VSCODE LIVE EXTENSION TO HOST.
document.querySelector(`input[type="submit"]`).onclick = () =>
{
var x = document.forms["form1"]["username"].value;
var password = document.forms["form1"]["password"].value;
var email ={
name : `${x}`,
password : `${password}`
};
if(document.querySelector(`input[type="checkbox"]`).checked){
var json = JSON.stringify(email);
var MC = require('mongodb').MongoClient;
var url = "mongodb+srv://<username>:<password>#cluster0.xjoqb.mongodb.net/myFirstDatabase?retryWrites=true&w=majority";
MC.connect(url, (err, db) => {
if (err) {
throw err;
}
console.log(`Connected`);
var data = db.db(`mydb`);
data.createCollection(`first`, (err, res) => {
if (err) throw err;
console.log(`collection created`)
});
data.collection(`first`).insertOne(email, (err, res) => {
if(err) throw err;
console.log(`inserted`);
db.close();
});
});
}
}
This is the html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="google-signin-client_id" content="707054985283-cirkm54740d0pm838hrgq7etkp3hu3ej.apps.googleusercontent.com">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<fieldset>
<h1 id="greeting">Welcome Back</h1>
<p id="greeting2">Let's Get Signed In</p>
<form name="form1" class="form" method="POST" autocomplete="off" spellcheck="false">
<div class="g-signin2" data-onsuccess="onSignIn"></div>
<div class="con1">
<input type="text" id="name" name="username" placeholder="Enter Your Email Address">
<img src="https://img.icons8.com/windows/50/000000/name.png" class="nameicon">
</div>
<div class="con2">
<input type="password" id="pass" name="password" placeholder="Enter Your Password">
<img src="https://img.icons8.com/windows/50/000000/password.png" class="passicon">
</div>
</form>
Forgot Password?
<div id="alm">
<input type="checkbox" id="remember" name="remem">
<label for="remem">Remember Me</label>
</div>
<form class="button1">
<input type="submit" name="submit" id="submit1">
</form>
</fieldset>
</body>
<script src="script.js"></script>
</html>
Databases (remote or local) are server side services. You need a back end app that handles the post request from the form located in the front end part and then from the backend trigger any action into Mongo Atlas.
Going with a NodeJS & Express stack could be a good option for you (you will also need to work with mongo in the backend, but in this case you will be storing the data in a remote Mongo Database).

Why socket.io is not working with Ajax properly?

For a while i interest nodejs and socket.io. I know i installed nodejs and socket.io properly. I prepared a form then i got values with javascript then by sensing with ajax to my php file, then i got what a want properly. But time to making amit with socket.io i always revieve this. message
GET http://localhost/socket.io/?EIO=4&transport=polling&t=NNbUs8K 404 (Not Found) polling-xhr.js:203
GET http://localhost/socket.io/?EIO=4&transport=polling&t=NNbUsVI 404 (Not Found) polling-xhr.js:203
.
.
.
Here is my server.js
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
io.on('connection', (socket) => {
//console.log('a user connected'); //this works
socket.on('chat message', (msg) => {
console.log('message: ' + msg);
});
});
http.listen(3000, () => {
console.log('listening on *:3000');
});
Server.js works properly i tested using this console.log('a user connected'); and it works well.
Then i tried to emit real datas.
here is my html file making ajax with
<!DOCTYPE html>
<html lang="en-US">
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-12">
<form method="post" action="">
<div class="form-group">
<label for="email">Email address</label>
<input type="text" class="form-control" id="email" >
</div>
<div class="form-group">
<label for="passwprd">Password</label>
<input type="password" class="form-control" id="password">
</div>
<button type="button" id="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
<script src="node_modules/socket.io/client-dist/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script>
$(function () {
$("#submit").on("click",function(){
var dataString = {
email : $("#email").val(),
password : $("#password").val(),
};
$.post("isle.php",{data:dataString},function(response){
// console.log(response);
var socket = io();
socket.emit('chat message', dataString);
return false;
},"json");
});
});
The last one is isle.php
<?php
$data=$_POST["data"];
$gonderilecek=[
"email_adres"=>$data["email"],
"sifre"=>$data["password"],
"mesaj"=>"mesajımız burada"
];
echo json_encode($gonderilecek);
I could not solve the problem any one can help me

How to send email via real server(SendGrid)

For my website, I am trying to send email to the users. I used sendgrid provider for sending the mail with nodeJS. I am new to nodeJS, I have sent the mail via the command prompt as per their instructions on their page. But I don't how to implement it on the real server. For sending emails via sendgrid I installed their package. And I want to send an email to a particular event.
function goMail()
{
const sgMail = require('#sendgrid/mail');
sgMail.setApiKey(MY_API_KEY);
const msg = {
to: '********1234#gmail.com',
from: '12345***#gmail.com',
subject: 'Sending with SendGrid is Fun',
text: 'and easy to do anywhere, even with Node.js',
html: '<strong>and easy to do anywhere, even with Node.js</strong>',
};
sgMail.send(msg);
}
HTML :
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="index.js"></script>
</head>
<body>
<div class="container">
<h2>Vertical (basic) form</h2>
<form>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter email" name="email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pwd">
</div>
<div class="checkbox">
<label><input type="checkbox" name="remember"> Remember me</label>
</div>
<button type="submit" class="btn btn-default" onclick="goMail();">Submit</button>
</form>
</div>
</body>
</html>
Please explain to brief how do they work on the real server.
You cannot directly include index.js file in HTML and invoke the Nodejs function. instead you should be using Express framework at Nodejs and use jQuery to post the form data. Please follow the instructions provided in the below link:
https://www.tutorialspoint.com/nodejs/nodejs_express_framework.htm
Hope this answer points you to the right direction and resolve your issue.
If you have implemented your server code then just add the following route in app.js file for creating an API for sending an email to the users
app.get('/sendEmail', (req, res) => {
let sendgrid = require('sendgrid');
let SG = sendgrid('your sendgridKey');
let request = SG.emptyRequest();
request.method = 'POST';
request.path = '/v3/mail/send';
request.body = (new sendgrid.mail.Mail(
new sendgrid.mail.Email(req.body.from),
req.body.subject, // subject
new sendgrid.mail.Email(req.body.to),
new sendgrid.mail.Content('text/html', 'your html')
)).toJSON();
SG.API(request, (err, response)=> {
if (response.statusCode >= 200 && response.statusCode < 300) {
res.send(response);
});
});
or you can define this function outside of the router so that you can call this function as middleware in any route.

HTML auto refreshing despite jQuery intercept

I'm developing a website through Parse.com JavaScript. I'm working on the login page and I found this nice template: http://designscrazed.org/css-html-login-form-templates/
However, when I try to modify the submit part of this page to be processed through Parse.com, the page auto-refreshes before the Parse.com transaction could be made. I know the JavaScript file is properly referenced though.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Prindle Login</title>
<!-- PARSE-->
<link href="dist/css/login-style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<script src="dist/js/parse/login-js.js"></script>
</head>
<body>
<div class="login-card">
<h1>Prindle Login</h1><br>
<form id="form">
<input id="prindle_log_on_username" type="text" name="user" placeholder="Username">
<input id="prindle_log_on_password" type="password" name="pass" placeholder="Password">
<input id="prindle_log_on" type="submit" class="login login-submit" value="Log In">
</form>
<div class="login-help">
Register • Forgot Password
</div>
</div>
</body>
</html>
JS:
// dynamically adding to a document: http://www.sanwebe.com/2013/03/addremove-input-fields-dynamically-with-jquery/comment-page-1
$(document).ready(function() {
alert('hello');
Parse.$ = jQuery;
Parse.initialize("APP ID", "JS ID")
});
// called when the user clicks the log in button
$('#prindle_log_on').on("click",function(e) {
e.preventDefault();
alert("form has been submitted.");
// perform onclick
// get the values of the input fields for username and password
var username = $('#prindle_log_on_username').val();
var password = $('#prindle_log_on_password').val();
// try to log in
Parse.User.logIn(username, password,
{
success: function(user) {
// Do stuff after successful login.
alert('user found');
},
error: function(user, error)
{
// The login failed. Check error to see why.
alert('log in failed');
}
});
});
I never get the balloon saying "form has been submitted." Help?
EDIT: (thanks to moogs)
<div class="login-card">
<h1>Prindle Login</h1>
<br>
<form id="form">
<input id="prindle_log_on_username" type="text" name="user" placeholder="Username">
<input id="prindle_log_on_password" type="password" name="pass" placeholder="Password">
<input id="prindle_log_on" type="submit" class="login login-submit" value="Log In">
</form>
<div class="login-help"> Register • Forgot Password
</div>
</div>
$(document).ready(function () {
$('#prindle_log_on').on("click", function (e) {
e.preventDefault();
alert("form has been submitted.");
});
});
Place the click handler inside $(document).ready because $('#prindle_log_on') will not be found until the body has rendered.
http://jsfiddle.net/moogs/L62z4k5o/1/

Get error in browser console when usimg python server

I get this error while running an html file which contains a form. It is supposed to move to another screen after login.
GET http://mdsad.com/p.js?v=1373144857354
I cannot understand where I am going wrong in the code. It doesn't even enter the function that is called.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="http://static.stackmob.com/js/stackmob-js-0.9.1-bundled-min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Pocket Docket</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function nextpage() {
alert("function");
StackMob.init({
publicKey: "my_key",
apiVersion: 0
});
var u = document.getElementById('username').value;
var p = document.getElementById('password').value;
alert(u);
alert(p);
var user = new StackMob.User({
username: u,
password: p
});
user.login(false, {
success: function(model, result, options) {
alert("Success");
alert("Success");
window.open('newp1.html');
StackMob.isUserLoggedIn(u, {
yes: function() {
alert("Logged In!");
},
no: function() {
alert("Login Error!");
}
});
},
error: function(model, result, options) {
console.log(result);
alert("Login Error!");
}
});
};
</script>
</head>
<body>
<div id="topPan">
<div id="topHeaderPan"></div>
<div id="toprightPan"></div>
</div>
<div id="bodyPan">
<div id="bodyleftPan">
<h2>Pocket Docket</h2>
<p class="greentext">For Every Salesman</p>
<p>Pocket Docket is a means to simplify the working of the sales
department in a company.</p>
<p>For every salesperson, it is like a manager, assigning tasks and
recording progress, updating it on their profiles. Easier to manage,
higher the productivity.</p>
</div>
<div id="bodyrightPan">
<div id="loginPan">
<h2>Pocket Docket <span>login</span></h2>
<form action="" method="post">
<label>Login ID</label><input id="email" name="email" type=
"text"> <label>Password</label><input id="pass" name="pass"
type="password"> <input class="button" name="Input" onclick=
"nextpage()" type="submit" value="Login">
</form>
<ul>
<li class="nonregister">Forgot Password ?</li>
<li class="register">
Click Here
</li>
</ul>
</div>
<div id="loginBottomPan">
</div>
</div>
</div>
</body>
</html>
The error is in download.js (some file i don't know in the browser console).
Please tell me where is the error.
I figure out what was wrong with your code:
var u = document.getElementById('username').value;
var p = document.getElementById('password').value;
where your input Id's are 'email' and 'pass'
so change the above lines to :
var u = document.getElementById('email').value;
var p = document.getElementById('pass').value;
also
it's better to close "input" markup
Hope it works now.

Categories

Resources