Today I'm trying Web Api 2 Login and Register Actions. I'm using Standard Template from Visual Studio 2015. I created JavaScript Client on web side, but I do not see alerts and registration is not working.
Here is my code:
<div class="form-group">
<div class="input-group">
<input type="email" class="form-control" placeholder="Email" id="email">
</div>
</div>
<div class="form-group">
<div class="input-group">
<input type="password" class="form-control" placeholder="password" id="password">
</div>
</div>
<div class="form-group">
<div class="input-group">
<input type="password" class="form-control" placeholder="Password again" id="confirmpassword">
</div>
</div>
<div class="form-group">
<div class="input-group">
<input type="submit" id="submit" value="Register" class="btn btn-info">
</div>
#section scripts{
#Scripts.Render("~/bundles/jqueryval")
<script>
$(function () {
$('#submit').click(function (e) {
e.preventDefault();
var data = {
Email: $('#email').val(),
Password: $('#password').val(),
ConfirmPassword: $('#confirmpassword').val()
};
$.ajax({
type: 'POST',
url: '/api/Account/Register',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data)
}).success(function (data) {
alert("Registration success");
}).fail(function (data) {
alert("Error message");
});
});
})
</script>
}
Update:
Here is code for login process:
div class="userInfo" style="display:none;">
<p>You are loged in as: <span class="userName"></span></p>
<input type="button" value="Log out" id="logOut" />
</div>
<div class="loginForm">
<h3>Log in</h3>
<label>Enter email</label><br />
<input type="email" id="emailLogin" /> <br /><br />
<label>Password</label><br />
<input type="password" id="passwordLogin" /><br /><br />
<input type="submit" id="submitLogin" value="Log in" />
</div>
#section scripts{
<script type="text/javascript">
$(function () {
//...........................
var tokenKey = "tokenInfo";
$('#submitLogin').click(function (e) {
e.preventDefault();
var loginData = {
grant_type: 'password',
username: $('#emailLogin').val(),
password: $('#passwordLogin').val()
};
$.ajax({
type: 'POST',
url: '/Token',
data: loginData
}).success(function (data) {
$('.userName').text(data.userName);
$('.userInfo').css('display', 'block');
$('.loginForm').css('display', 'none');
// store sessionStorage auth token
sessionStorage.setItem(tokenKey, data.access_token);
console.log(data.access_token);
}).fail(function (data) {
alert('Error on login');
});
});
$('#logOut').click(function (e) {
e.preventDefault();
sessionStorage.removeItem(tokenKey);
});
})
</script>
}
Update 2
On registration here is F12 console code:
(index):88 Uncaught TypeError: $.ajax(...).success is not a function
at HTMLInputElement.<anonymous> ((index):88)
at HTMLInputElement.dispatch (jquery-3.1.1.js:5201)
at HTMLInputElement.elemData.handle (jquery-3.1.1.js:5009)
(anonymous) # (index):88
dispatch # jquery-3.1.1.js:5201
elemData.handle # jquery-3.1.1.js:5009
But registration passes and I have new record in database. Can anyone explain me what does it mean?
do it like this :
$.ajax({
type: 'POST',
url: '/api/Account/Register',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data)
success: function(html){
alert("Registration success");
}
});
Well, I found that I've used submit type button, it's first misstake - if I want operate request using jquery I've use type="button" instead submit.
Another moment is that json properties is not difined in right case:
var data = {
email: $('#email').val(),
password: $('#password').val(),
confirmPassword: $('#confirmpassword').val()
};
this will be correct
Now about error in console: correct is like #Mustapha answered
for example:
$.ajax({
type: "GET",
url: "/api/rooms",
success: function (rooms) {
}
});
Here is fixed ajax code:
$.ajax({
type: 'POST',
url: '/Token',
data: loginData
success: function(data) {
$('.userName').text(data.userName);
$('.userInfo').css('display', 'block');
$('.loginForm').css('display', 'none');
// store sessionStorage auth token
sessionStorage.setItem(tokenKey, data.access_token);
console.log(data.access_token);
},
error: function (data) {
alert('Error on login');
});
});
Here is, but I've done it using angular :)
Thanks.
Related
I want the following ajax request to process form data from form with "#next" id:
$(function () {
$("#next").on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'check_user.php',
dataType: 'json',
data: $('form').serialize(),
success: function (response) {
if(response['found'] === 'true') {
location.href = 'index.php';
} else {
alert('Incorrect username or password');
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
And here's the file that contains the form:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="css/auth_style.css">
<title>Authentication</title>
<script src="https://code.jquery.com/jquery-3.6.1.js"></script>
<script src="js/authentication_ajax.js"></script>
<noscript>JS is disabled. Enable js to continue</noscript>
</head>
<body>
<h1 id="header">Enter your data here</h1>
<form id="#next">
<label for="login">Login</label>
<input type="text" id="login" name="login" placeholder="Enter your login here" required><br>
<label for="password">Password</label>
<input type="password" id="password" name="password" placeholder="Enter your password here" required><br>
<input type="submit" value="Log in">
</form>
<form id="#log_out" action="log_out.php" method="post">
<button type="submit">Log out</button>
</form>
</body>
What's interesting is that when I used just $('form').on('submit', function (e) { it worked just fine.
You have two error the first one is how to use ids, in the id don't use # instead use just the name, and into the selector you can use $('#name').
The second problem is about selector of serialize(), in this case you can use directly e.target like:
$(function() {
$("#next").on('submit', function(e) {
e.preventDefault();
console.log($(e.target).serialize());
/*
$.ajax({
type: 'post',
url: 'check_user.php',
dataType: 'json',
data: $(e.target).serialize(),
success: function (response) {
if(response['found'] === 'true') {
location.href = 'index.php';
} else {
alert('Incorrect username or password');
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
*/
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 id="header">Enter your data here</h1>
<form id="next">
<label for="login">Login</label>
<input type="text" id="login" name="login" placeholder="Enter your login here" required><br>
<label for="password">Password</label>
<input type="password" id="password" name="password" placeholder="Enter your password here" required><br>
<input type="submit" value="Log in">
</form>
<form id="log_out" action="log_out.php" method="post">
<button type="submit">Log out</button>
</form>
It used to work fine, and I don't remember changing anything in these files, but now nothing happens when I click on submit form. What may cause the problem?
Snippet:
// And here's the ajax request file *auth_ajax.js*:
$(function() {
$('form').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'check_user.php',
dataType: 'json',
data: $('form').serialize(),
success: function(response) {
if (response['found'] === 'true') {
location.href = 'index.php';
} else {
alert('Incorrect username or password');
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
<!-- Here's my php file: -->
<h1 id="header">Enter your data here</h1>
<form>
<label for="login">Login</label>
<input type="text" id="login" name="login" placeholder="Enter your login here" required><br>
<label for="password">Password</label>
<input type="password" id="password" name="password" placeholder="Enter your password here" required><br>
<input type="submit" value="Log in">
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
This route work?
url: 'check_user.php',
Try yourDomain/check_user.php, check your directory for a real path
I'm using Formsubmit to send contact us form to my email and so far it's working.
But I would like when user send the form it does not redirect it to the source thank you page instead I'd like to display just thank you text on the same page. I'd like to use my own.
So I followed the documentation and I came up with the following :
Unfortunately when I try validate the form button it does not work
<form id="contactForm" action="https://formsubmit.co/el/myemail" method="POST">
<input type="text" name="name">
<input type="phone" name="phone" inputmode="tel">
<input type="hidden" name="_subject" value="Partenaires">
<input type="email" name="email" >
<input type="text" name="message" >
<button class="btn btn-primary border rounded-0 shadow-lg d-lg-flex justify-content-lg-center"
type="submit" name="sendData">Send</button>
<!-- <input type="hidden" name="_next" value="thanks.html">-->
<script type="text/javascript">
var frm = $('#contactForm');
var msg_res ='';
frm.submit(function (e) {
e.preventDefault();
$.ajax({
type: frm.attr('method'),
method: "POST",
url: "https://formsubmit.co/el/vupawa",
dataType: 'html',
accepts: 'application/json',
data: frm.serialize(),
success: function (response) {
$("#message").html(response);
if(response != msg_res){
msg_res = response; //store new response
alert('New message received');
}
},
error: function (response) {
console.log('An error occurred.');
console.log(response);
}
complete: function(response){
setTimeout(ajax,1000);
}
});
});
});
</script>
Note : that uncommenting this line <input type="hidden" name="_next" value="thanks.html"> will take validate the form and go through another page which is not what I want here.
Any ideas ?
To Prevent Submission You should return false in
frm.submit(function (e) {
return false;
})
Or in form tag
<form onSubmit="return false">
var frm = $('#contactForm');
var msg_res ='';
frm.submit(function (e) {
e.preventDefault();
$.ajax({
type: frm.attr('method'),
method: "POST",
url: "https://formsubmit.co/el/vupawa",
dataType: 'html',
accepts: 'application/json',
data: frm.serialize(),
success: function (response) {
$("#message").html(response);
if(response != msg_res){
msg_res = response; //store new response
alert('New message received');
}
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
}
});
return false; // here a change
});
<form id="contactForm" action="https://formsubmit.co/el/myemail" method="POST">
<input type="text" name="name">
<input type="phone" name="phone" inputmode="tel">
<input type="hidden" name="_subject" value="Partenaires">
<input type="email" name="email" >
<input type="text" name="message" >
<button class="btn btn-primary border rounded-0 shadow-lg d-lg-flex justify-content-lg-center"
type="submit" name="sendData">Send</button>
<!-- <input type="hidden" name="_next" value="thanks.html">-->
I am trying to reach my javascript code when I press the submit button within my form and it is not triggering my javascript code at all.
So I got this form within my Bootstrap Modal using the following code:
<form id="updateUserForm">
<div class="form-group">
<label for="firstName">First name:</label>
<input type="text" class="form-control" id="firstnameModalInput" />
</div>
<div class="form-group">
<label for="middleName">Middle name:</label>
<input type="text" class="form-control" id="middlenameModalInput" />
</div>
<div class="form-group">
<label for="lastName">Last name:</label>
<input type="text" class="form-control" id="lastnameModalInput" />
</div>
<div class="form-group">
<label for="mobileNumber">Mobile number:</label>
<input type="text" class="form-control" id="mobilenumberModalInput" />
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="text" class="form-control" id="emailModalInput" />
</div>
<div class="form-group">
<label for="Enabled">Enabled:</label>
<input type="checkbox" class="form-control" id="enabledModalInput" style="width:34px" />
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-default" data-dismiss="modal" id="submit" value="Apply" />
</div>
</form>
And the javascript code I have:
$('document').ready(function(){
$("#updateUserForm").submit(function (event) {
console.log("Method entered");
event.preventDefault();
var serialize = $("#updateUserForm").serialize();
$.ajax({
type: "POST",
data: serialize,
url: "/Dashboard/UpdateUser",
datatype: JSON,
succes: function (data) {
console.log("succes!");
console.log(data);
},
error: function (data) {
console.log("error");
console.log(data);
}
})
})
})
I have another function in that javascript that is used to populate the input fields and that works fine, so I guess the HTML can reach the javascript file. But it does not reach the javascript submit function (it doesn't do the console.log for example) . Does anyone have an idea what I am doing wrong?
EDIT:
I have been playing around a bit more, and it seems that I can acces the javascript method when I try to reach it from outside of the bootstrap modal, it goes wrong somewhere within the modal.
Use return false instead of prevent default end of the function and change the submit function with on function.
$('document').ready(function(){
$("#updateUserForm").on("submit", function () {
console.log("Method entered");
var serialize = $("#updateUserForm").serialize();
$.ajax({
type: "POST",
data: serialize,
url: "/Dashboard/UpdateUser",
datatype: JSON,
succes: function (data) {
console.log("succes!");
console.log(data);
},
error: function (data) {
console.log("error");
console.log(data);
}
})
return false;
})
})
try this
$("#updateUserForm").on('submit', function (e) {
e.preventDefault();
});
Can you please try below code. and please check post URL"/Dashboard/UpdateUser" is right?
$("#UpdateUserForm").submit(function (e)
{
var isValid = $("#UpdateUserForm").valid();
if (!isValid)
return;
//This is important as it prevents the form being submitted twice
e.preventDefault();
$.ajax({
type: "POST",
url: "/Dashboard/UpdateUser",
data: $("#UpdateUserForm").serialize(),
success: function (response)
{
var status = '';
status = response.Status;
console.log("succes!");
console.log(data);
}
})
.error(function () {
console.log("error");
console.log(data);
});
});
$("#updateUserForm").on('submit', function (e) {
e.preventDefault();
});
Or use action properties in form.
It seems like i cant get to serialize my form. I do get the first alert with lol, but not the second alert with pdata. Does anyone see whats wrong? Im trying to use ajax to send the data in the form. Down below is the script and the html code.
<html>
<head>
<script>
function dologin(event) {
event.preventDefault();
alert("lol");
var pdata = $('#form').serialize();
alert(pdata);
$.ajax({
type: 'POST',
data: pdata,
url: 'LINK',
success: function(data) {
//console.log(data);
alert("YAY");
},
error: function() {
//console.log(data);
alert("NAY");
}
});
};
</script>
</head>
<body>
<h1>Logg inn</h1>
<form id="form" onsubmit="dologin()">
<div class="form-group">
<label for="email">Epost</label>
<input type="email" class="form-control" name="login" value="" placeholder="Epost">
</div>
<div class="form-group">
<label for="password">Passord</label>
<input type="password" class="form-control" name="password" value="" placeholder="Passord">
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="remember_me">
Husk meg
</label>
</div>
<button type="submit" class="btn btn-default">Logg inn</button>
</form>
<div class="login-help">
<p>Glemt passordet? Trykk her for å endre det.</p>
</div>
</body>
</html>
The problem with your code is, you are accessing event argument wheres there is no parameter passed to the function, so its triggering an error and submitting the form as normal form submission.
If you like to keep your implementation u can modify your code like bellow:
function dologin() {
alert("lol");
var pdata = $('#form').serialize();
alert(pdata);
$.ajax({
type: 'POST',
data: pdata,
url: 'LINK',
success: function(data) {
//console.log(data);
alert("YAY");
},
error: function() {
//console.log(data);
alert("NAY");
}
});
return false;
};
and modify this line
<form id="form" onsubmit="dologin()">
to
<form id="form" onsubmit="return dologin()">
or can use the following way
$(document).ready(function() {
$('#form').submit(function(e){
e.preventDefault();
$.ajax({
type: 'POST',
data: $(this).serialize(),
url: 'LINK',
success: function(data) {
//console.log(data);
alert("YAY");
},
error: function() {
//console.log(data);
alert("NAY");
}
});
});
});
And form tag should be then:
<form id="form">