I keep getting HttpGet Again and Again - javascript

My problem is i have a login page, it is very simple, I am getting the username and password. I am controlling it at server side. I am using javascript delivering data View to Controller. But the problem is it always sends me to same page. I am always entering the userName and password, but the data even when its correct, there is not a redirect.
My View Code,
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Yelken Otel Rezervasyon Kontrol Sistemi</title>
<script type="text/javascript">
function Login() {
var userName = document.getElementById("userName").value;
var password = document.getElementById("password").value;
$.ajax({
type: 'POST',
url: '/RezervasyonTalepleri/Giris',
dataType: 'json',
data: {
'userName': userName,
'password': password
},
success: function (msg) {
location.href = '/RezervasyonTalepleri/Denetim';
}
});
};
</script>
</head>
<body>
<div class="login-page">
<div class="form">
<form class="login-form">
<input id="userName" type="text" placeholder="username" />
<input id="password" type="password" placeholder="password" />
<button id="btnLogin" onclick="Login()" >login</button>
</form>
</div>
</div>
</body>
</html>
My Controller Code,
[HttpGet]
public ActionResult Giris()
{
return View();
}
[HttpPost]
public ActionResult Giris(string userName, string password)
{
if(userName=="admin" && password == "123")
{
return Json(new { status = "success" });
}
else
{
return JavaScript("Yanlış Kullanıcı Adı veya Şifre Girdiniz.");
}
}
I expect that when i enter the right userName and password, it should redirect me to /RezervasyonTalepleri/Denetim but it always redirects me to /RezervasyonTalepleri/Giris.

You need jQuery library for example included it as below:
<title>Yelken Otel Rezervasyon Kontrol Sistemi</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script type="text/javascript"> ...

If I understood your problem correctly,
The success function is called when the invocation of the Giris Action was successful and not when you return success as status.
In your example, you need to check if msg.status is equal to success and you are ready to go.
So your success function would be
success: function (msg) {
if (msg.status === 'success')
{
location.href = '/RezervasyonTalepleri/Denetim';
}
}

Related

sending message to telegram bot

i need some help,
am trying to send message to telegram bot
but things are not working out for me,
am just trying to archive what i want to do. am new to jquery and javascript
below is what i tried
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<script>
$(document).ready(function () {
$("#add_button").click(function(event) {
Execute();
});
var fname = document.querySelector('input[name="fname"]').value;
var country = document.querySelector('input[name="country"]').value;
Message: "<html><br>| Fullname: ${fname} <br> | Country: ${country} <br></html>";
function Execute(){
$.ajax({
type: 'POST',
url: 'https://api.telegram.org/bot<token>/sendMessage?chat_id=<id>text=<message>&parse_mode=html',
data: Message,
success: function(res) {
$('#response').text('Message sent');
},
error: function() {
alert("error failed");
}
});
};
});
</script>
<input type="text" id="fname" name="fname" placeholder="fullname">
<input type="text" id="country" name="country" placeholder="country">
<input type="button" id="add_button" value="Submit">
<div id="response"></div>
<body>
</body>
</html>
There are several issues in you script:
Your <body> tag is misplaced
AFAIK, your payload must be form encoded (not as GET params)
Use ` for format strings instead of "
read the input values in the execute method, not outside (otherwise you read them only once on page load).
You cannot use <br> or <html> in the message, see the docs
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="fname" name="fname" placeholder="fullname">
<input type="text" id="country" name="country" placeholder="country">
<input type="button" id="add_button" value="Submit">
<div id="response"></div>
<script>
const token = '<token>';
const chatId = '<chat_id>';
$(document).ready(function () {
$("#add_button").on('click', function (event) {
execute();
});
function execute() {
const fname = document.querySelector('#fname').value;
const country = document.querySelector('#country').value;
const message = `Fullname: ${fname}\nCountry: ${country}`;
$.ajax({
type: 'POST',
url: `https://api.telegram.org/bot${token}/sendMessage`,
data: {
chat_id: chatId,
text: message,
parse_mode: 'html',
},
success: function (res) {
console.debug(res);
$('#response').text('Message sent');
},
error: function (error) {
console.error(error);
alert("error failed");
}
});
}
});
</script>
</body>
</html>
And a security note:
Do NOT use this script in any production! NEVER EVER!
Everyone would be able to read and abuse your bot token.
Use a backend for this.

im using jquery/ajax for login. Sending works and server side returns to log in, but this fails

I have created a login system with PHP, however, i also added two factor authentication. I wanted to log in without having to refresh the page so it looks better when asking for the 2FA code
The way i have done this is by sending the username and password via ajax. my php script then checks this and then it would echo login or error
Here's my javascript code
$(document).ready(function() {
$('#login-form').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'inc/auth.php',
data: $(this).serialize(),
dataType: 'text',
success: function(data)
{
alert(data);
if (data === 'login') {
window.location = '/user-page.php';
}
else {
alert('Invalid Credentials');
}
},
});
});
});
This works fine, when i alert the data i get 'login' (without quotes, obviously) however it doesn't send me to user-page.php, instead, it gives me the invalid credentials alert. Despite the php page returning login, javascript is like "nope!"
What am i doing wrong?
Here's my form
<form class="form" id="login-form" name="login-form" method="post" role="form" accept-charset="UTF-8">
<div class="form-group">
<label class="sr-only" for="exampleInputEmail2">Gebruikersnaam</label>
<input type="username" class="form-control" id="gebruikersnaam" name="gebruikersnaam" placeholder="gebruikersnaam" required>
</div>
<div class="form-group">
<label class="sr-only" for="exampleInputPassword2">Wachtwoord</label>
<input type="password" class="form-control" id="wachtwoord" name="wachtwoord" placeholder="Password" required>
<div class="help-block text-right">Forget the password ?</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-block">Sign in</button>
</div>
</form>
I run the javascript from this page via <script src="auth.js"></script>. I also tried putting it directly inside script tags witch failed too.
This is for testing purpose
I believe your dataType should be either html or json
$(document).ready(function() {
$('#login-form').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'inc/auth.php',
data: $(this).serialize(),
dataType: 'html',
success: function(data)
{
alert(data);
if (data == 'login') {
window.location = '/user-page.php';
}
if (data == 'failed') {
alert('Invalid Credentials');
}
},
});
});
});
In absence of your server logic
Your php inc/auth.php FOR Testing purpose
//$gebruikersnaam= $_POST['gebruikersnaam'];
//$wachtwoord= $_POST['wachtwoord'];
$gebruikersnaam= 'nancy';
$wachtwoord= 'nancy123';
if($gebruikersnaam=='nancy' && $wachtwoord=='nancy123')
{
echo "login";
}
else
{
echo "failed";
}
As for CSRF attack mentioned by SO Scholar in the comment. you will need to generate something like md5 token that will be stored in a session. you will now send it with each request eg. in a hidden form input and verify that it matches the one on the server side. if match allow login otherwise trigger impersonation
Updates
$(document).ready(function() {
$('#login-form').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'inc/auth.php',
data: $(this).serialize(),
dataType: 'JSON',
success: function(data)
{
alert(data);
if (data.login == 'success') {
window.location = '/user-page.php';
}
if (data.login == 'failed') {
alert('Invalid Credentials');
}
},
});
});
});
PHP
<?php
error_reporting(0);
$gebruikersnaam= 'nancy';
$wachtwoord= 'nancy123';
if($gebruikersnaam=='nancy' && $wachtwoord=='nancy123')
{
$return_arr = array('login'=>'success');
}
else
{
$return_arr = array('login'=>'failed');
}
echo json_encode($return_arr);

Why method not allowed http exception?

I have a form in laravel.
I want to send the data to server using ajax post request.
The laravel give me error. I dont know why?
My view source url is : http://localhost/lily/public/search
(1/1) MethodNotAllowedHttpException
in RouteCollection.php (line 251)
at RouteCollection->methodNotAllowed(array('GET', 'HEAD'))
in RouteCollection.php (line 238)
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready( function () {
$("#submit").submit( function(){
var name = $("#name").val();
console.log(name);
$.ajax({
type: "POST",
url : "{{url('/search')}}",
data : name ,
success : function(data)
{
console.log(data)
},
error : function(error)
{
console.log(error)
}
});
});
});
</script>
<div class="col-md-6 offset-3">
<form id="submit" method="POST">
<input type="name" name="name" id="name">
<button type="submit" class="btn btn-success">search</button>
</form>
</div>
</body>
</html>
Route::post('/search/{name}', 'HomeController#in');
public function in() {
return json("fdfdfdfdfdf");
}
You defined a a route for /search/parameter, but your action is only '/search'.
Remove the useless {name} part in the route. Or make it optional with {name?}
Pass the CSRF token along with the request, after changing your route definition to either remove {name} or making it optional {name?} then change your data to
$(document).ready(function() {
$("#submit").submit(function() {
e.preventDefault(); // Prevent the Default Form Submission
var name = $("#name").val();
console.log(name);
$.ajax({
type: "POST",
url: "{{ url('/search') }}",
data: {
name: name,
_token: "{{ csrf_token() }}"
},
success: function(data) {
console.log(data)
},
error: function(error) {
console.log(error)
}
});
});
});
The input type should be text instead of name in the form
<input type="text" name="name" id="name">
Because you did not add CSRF token value as a hidden type.
You must add CSRF hidden input to Form.
<input type="hidden" name="_token" value="{{ csrf_token() }}" />

I want to get my textbox values from HTML document and post those when submit button is pressed using Json file in node JS

This is my JS file:-
$(document).ready(function(){
$('form').on('submit', function(){
var email = $("form input[type=text][name=emails]").val();
var todo = {email: email.val(),
pass:dat.val()};
$.ajax({
type: 'POST',
url: '/project',
data: todo,
success: function(data){
//do something with the data via front-end framework
location.reload();
}
});
return false;
});
});
This is my html document:-
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script src="/assests/todo-list.js"></script>
<body>
<form>
<div class="container">
<label><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="emails" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<button type="submit" class="signupbtn">Sign Up</button>
</div>
</div>
</form>
</body>
</head>
</html>
I want that when i click submit button value from both text boxes gets saved in my database(using Mlab),for that i am using a json file to fire post request to the server.
My main post request handler:-
app.post('/project',parser,function(req,res)
{
var register=Todo(req.body).save(function(err,data)
{
if(err) throw err
res.json(data);
});
});
EDIT:-
I removed my Javascript file and now i am directly posting the form using and i am able to save my email address but not the password.
This is my main code now :-
app.post('/views/register',parser,function(req,res)
{
var data={
email:req.body.emails,
password:req.body.passcode
};
var send=Todo(data).save(function(err)
{
if(err) throw err
res.render('login')
})
});
If I understand your question right, you're missing the contentType param.
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
...
then try again.
I was not following the correct schema for the database when creating the object
var data={
email:req.body.emails,
password:req.body.passcode
};
The property name was pass and i was using password that's why it was not inserting the password.
var data={
email:req.body.emails,
pass:req.body.passcode
};

How to verify recaptcha in server call?

SITUATION:
I used to check my recaptcha with a simple form submit with POST to "/login".
I need to change my implementation for security reasons and would like to do something like:
1) Jquery form submit.
2) Make call to server to call verify recaptcha on the server.
3) Receive response without reloading page.
4) Accept login request or not based on response.
QUESTION:
It looks like I could make an AJAX request ? But I don't know how.
CLIENT CODE:
<div class ="containerMargins">
<h1 class = "authTitle">Login</h1>
<form id="loginForm">
<div class="form-group">
<label>Email</label>
<input type="email" class="form-control" name="email" id="loginEmail" placeholder="You can't forget it :)" required>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" name="password" id="loginPassword" placeholder="We hope you didn't forget it ^^" required minlength="12">
</div>
<div class="g-recaptcha" data-sitekey="6LcRrxMUAAAAANx-AXSdRLAo4Pyqfqg-1vuPSJ5c"></div>
<button class="btn btn-default" id="loginButton">Submit</button> <span class="userLinks">
<a class="logLinks" href="/users/register">Register</a>Password?</span>
</form>
</div>
</div>
<% include ../partials/indexScripts %>
<script>
$("#loginForm").submit(function(e) {
e.preventDefault();
var email = $("#loginEmail").val();
var password = $("#loginPassword").val();
// WOULD LIKE TO MAKE SERVER CALL HERE TO CHECK RECAPTCHA BUT I DONT KNOW HOW
$this = $(this);
$.ajax({
type: "POST",
url: "users/register",
data: $this.serialize()
}).done(function(data) {
if (successfulRecaptcha) {
firebase.auth().signInWithEmailAndPassword(email, password ).then( authData => {
}
else {
console.log("You are a robot!");
}
SERVER CODE:
router.post('/login', function(req, res, next) {
verifyRecaptcha(req.body["g-recaptcha-response"], function(success) {
if (success) {
} else {
}
});
});
I found the solution :
FRONT END:
$this = $(this);
$.ajax({
type: "POST",
url: "login",
data: $this.serialize()
}).done(function(data) {
if (data == true) {
BACKEND:
router.post('/login', function(req, res, next) {
verifyRecaptcha(req.body["g-recaptcha-response"], function(success) {
if (success) {
res.send(true);
} else {
res.send(false);
}
});
});

Categories

Resources