Why socket.io is not working with Ajax properly? - javascript

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

Related

Unable to send form data into MongoDB database using Node.js

So I've been trying to get the data from my form and input it into my database for ages and it just isn't working. There are no errors and nothing is logging.
This is my HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta charset="UTF-8">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="css/bootstrap.min.css">
<title>Signup for NGOs</title>
</head>
<body>
<form class="mt-4 mr-4 ml-4" id="form" method="post">
<div class="form-group">
<label for="name">Name</label>
<input type="name" class="form-control" id="name" aria-describedby="emailHelp" placeholder="Enter name of NGO">
</div>
<div class="form-group">
<label for="address">Address</label>
<input type="text" class="form-control" id="address" placeholder="Address">
</div>
<div class="form-group">
<label for="phone">Contact Information</label>
<input type="number" class="form-control" id="phone" placeholder="Contact Number">
</div>
<div class="form-group">
<label for="requirements">Requirements (Seperate by Commas)</label>
<input type="text" class="form-control" id="requirements" placeholder="Requirements">
</div>
<button type="submit" class="btn btn-primary" id="submitButton">Submit</button>
</form>
<!-- Optional JavaScript -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" src="signup.js"></script>
</body>
</html>
And this is my Node.js code:
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.resolve(__dirname, 'public')));
// I've replaced my original username and password with placeholders
var uri = "mongodb+srv://username:password#helpbook-rlpsi.gcp.mongodb.net/test?retryWrites=true";
var dbConn = MongoClient.connect(uri, { useNewUrlParser: true });
app.post('/signup', function (req, res) {
dbConn.then(function(db) {
delete req.body._id; // for safety reasons
dbConn.db("NGOs").collections("partners").insertOne(req.body);
console.log('test');
});
});
I don't know what's going wrong. My data isn't being uploaded to the database and for some reason none of the console.log() statements are being executed.
The promise probably resolves before the signup handler is called.
Try the following:
var dbConn = MongoClient.connect(uri, { useNewUrlParser: true });
dbConn.then(function(client) {
app.post('/signup', function (req, res) {
delete req.body._id; // for safety reasons
client.db("NGOs").collections("partners").insertOne(req.body);
console.log('test');
});
})
.catch(function(err){
console.log(err)
});
Looking at your question specifically, you are not using any action in your form.
<form class="mt-4 mr-4 ml-4" id="form" method="post" action="/signup">
...
</form>
So it is not getting posted to your route. (That's why I specifically asked if console logging before the dbconn is working or not)

Websocket chat error in node.js socket.io

Welcome all!
I have made a chat with websocket, the best of all is that it includes php, for this I installed this websocket (server side), in a different way.
The problem is the following, when I run the server, and I open the page from localhost/path .. there is an error in the browser,
"Uncaught ReferenceError: io is not defined" at:
"var socket = io();" from index.php, chat1.rar file
The server side appears to work, node chat.js
I've been watching for a week how to fix it,
I leave below the mentioned code.
chat.js (server side)
var express = require( 'express' );
var http = require('http');
var socket = require('socket.io');
var bodyParser = require('body-parser')
var PORT = process.env.PORT || 8080;
var fs= require('fs');
var app = express();
var server = http.createServer( app );
var io = socket.listen( server );
io.on('connection',function(socket){
var channel = 'channel-a';
socket.join(channel);
socket.on('message',function(msj){
io.sockets.in(channel).emit('message',msj,socket.id);
});
socket.on('disconnect',function(){
console.log("Desconectado : %s",socket.id);
});
});
server.listen( 1334, function() {
console.log('lisning to port 1334');
});
And index.php (client side)
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>
</head>
<body>
<div class="container">
<script type="text/javascript">
var socket = io.connect( 'http://localhost:1334' );
var socket = io();
$(function(){
$("form").submit(function(){
var mensaje = $("#msg").val();
if(mensaje=='') return false;
if(mensaje==' ') return false;
socket.emit('message',mensaje);
$("#msg").val('').focus();
return false;
});
});
socket.on('message',function(msg,id){
//output.innerHTML += '<p><strong>' + id + ': </strong>' + msg + '</p>';
$('#message').append($('<p><strong>' + id + ': </strong>' + msg + '</p>'));
//$('#message').append($('<div class="msg new-chat-message">').text(id+': '+msg));
//$('#message').append($('<div class="msg new-chat-message">').html('<span class="member-name">' + id + '</span>: ' + msg));
$('.chat-window').scrollTop($('#message').height());
//$("#message").append($('<li>').text(id+' : ' +msg));
});
socket.on('change channel',function(channel){
$("#message").html('').append($('<li>').text('system : Bienvenido al Canal '+channel+' !'));
});
</script>
<div class="col-md-12">
<div class="chat-window">
<div id="message"></div>
</div>
<div id="controls">
<form action="">
<select name="channel" id="channel">
<option value="channel-a">Channel A</option>
</select>
<div class="col-md-12">
<div class="input-group enter-chat-message">
<input type="text" id="msg" class="form-control" placeholder="Chat Message...">
<input class="input-group-addon submit-chat-message" type="submit" id="btn" value="Enviar">
</div>
</div>
</div></div>
</form>
</div></div></div></div>
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script src="js/bootstrap.js"></script>
<script src="node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js"></script>
</body>
</html>
screenshot:
http://prntscr.com/ie030c
Any Help is Appreciated!
Thanks
Change this:
<script src="node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js">
To:
<script src="/socket.io/socket.io.js">
And see what happens.

Angularjs code not working

I've recently been teaching myself angularjs as well as node.js , from what I've learned I wrote this piece of code , but it isn't functioning , I tried logging something in the controller and it didnt log it so maybe that's a hint on what's wrong index.html code: (sorry in advance if my code is messy or anything )
<!Doctype html>
<html ng-app="Test">
<head>
<title>Test</title>
<link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="angular-route.js"></script>
<script type="text/javascript">
var app= angular.module('Test' , ['ngRoute']);
app.controller('TestController' , function($scope , $http ){
$scope.submitBlog = function(){
$http.post('/blogs' , {blog : $scope.blog}).then(function(){
alert("success");
});
};
});
</script>
</head>
<body ng-app>
<h2>Blog It!</h2>
<br><br>
<div class="test" >
<input type="text" , placeholder="Username">
<br><br>
<input type="password" , placeholder="Password">
<br><br>
<button type="button" > Log In</button>
<br><br>
Not a member ? Sign Up!
</div>
<div class="blogfeed">
<h5>Feed :</h5>
<input ng-model="blog" placeholder="Your thoughts?" >
<button type="button" , ng-click="submitBlog()" , class="btn">Submit</button>
</div>
</body>
</html>
Server code :
var MongoClient = require('mongodb').MongoClient;
var ObjectId = require('mongodb').ObjectId;
var express = require('express');
var bodyParser = require('body-parser');
var bcrypt = require('bcryptjs');
var app = express();
var db = null;
MongoClient.connect("mongodb://localhost:27017/test" , function(err,dbconn){
if(!err){
console.log("We are connected");
db= dbconn;
}
});
app.use(express.static('public'));
app.use(bodyParser.json());
app.post('/blogs' , function(res,req,next){
db.collection('blogs' , function(err , blogsCollection){
var newBlog= {
text: req.body.blog
};
blogsCollection.insert(newBlog , {w:1} , function(err){
return res.send();
});
});
});
app.listen(3000, function(){
console.log('Example app listening on port 3000');
});
You are creating a controller that is never used.
you have to bind your controller to a dom element with the ng-controller directive
you could append it to the body tag like so
<body ng-app ng-controller="TestController" >
Check this. You've created a ng-app i.e Testand a controller TestController. But you've never used it. If you want to use the controller for the whole body i.e one controller for the whole application then use ng-controller="TestController" on the body tag. Similarly do it for other elements if you want the scope of the controller limited to the children of a particular element.
<!Doctype html>
<html ng-app="Test">
<head>
<title>Test</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.5/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('Test', []);
app.controller('TestController', function($scope, $http) {
console.log('In the controller');
$scope.submitBlog = function() {
$http.post('/blogs', {
blog: $scope.blog
}).then(function() {
alert("success");
});
};
});
</script>
</head>
<body ng-controller="TestController">
<h2>Blog It!</h2>
<br>
<br>
<div class="test">
<input type="text" , placeholder="Username">
<br>
<br>
<input type="password" , placeholder="Password">
<br>
<br>
<button type="button">Log In</button>
<br>
<br>
Not a member ? Sign Up!
</div>
<div class="blogfeed">
<h5>Feed :</h5>
<input ng-model="blog" placeholder="Your thoughts?">
<button type="button" , ng-click="submitBlog()" , class="btn">Submit</button>
</div>
</body>
</html>

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

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

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