Ajax event only working once - javascript

when i enter the wrong details and run it. it pops up with the error message, but if i then enter the correct details and click run it again. the sign in button changes to "Connecting..." as it should but then nothing else happens
$(document).ready(function() {
var width = ( $(".main").width() - 5);
if (width < 300) {
$(".logo-img").css({"width":width});
};
$("#error").hide();
$(function() {
$('#login').on('click', function(e){
e.preventDefault();
var token = $('#token').val();
var username = $('#username').val();
var password = $('#password').val();
var remember = $('#remember:checked').val();
$.ajax({
url: 'core/functions/ajaxLogin.php',
method: 'POST',
data: { 'username' : username,
'password' : password,
'remember' : remember,
'token' : token },
dataType: 'html',
cache: false,
beforeSend: function() { $('#login').val('Connecting...') },
success: function( data ) {
if (data == 'success') {
setTimeout( "window.location.href='backorderbook';", 500 );
} else if( data == 'userorpass' ) {
$('#error').fadeIn();
$('#error_message')
.html('username or password were entered incorrectly');
$('#error').delay(3500).fadeOut();
$('#login').val('Sign In');
};
}
});
});
});
});

Reason behind working once.
when your ajax fired, first thing to do is show connecting.. then when you get response which is data your statement says
if data == success //redirects
elseif data == userpass //show you have invalid username/password and clear html
So what if your data is not succes / userpass
it will just run your ajax beforeSend() and not will remove connecting that seems to you running once.
I recommend that your data should be an object and check if there's an error with the message on it , in short have it on your backend and just jquery show that message

There is a token generated when the login page is loaded and sent with the Ajax. But my PHP token system doesn't like the same token being sent over and over and blocks the request.

run your function with Fiddler .. and/or add the error parameter to your ajax... odds are your web request isn't a success.

Related

ASP.NET MVC 500 (Internal Server Error) with ajax post method

I'm newbie in asp.net mvc, I try to create a post data using ajax, when in the development is run well, but when I try to publish web in server I get the error when post data, the error like this POST https://example.com/login-testing 500 (Internal Server Error). I try to look for many examples but fail all.
this is my code, may be you can find any problem in my code:
JS script in index.cshtml
function login() {
var email = $('#input-email').val();
var password = $('#input-password').val();
if (email && password) {
$.ajax({
url: '#Url.Action("LoginTesting", "Auth")',
type: 'POST',
data: JSON.stringify({
email: email,
password: password
}),
dataType: 'json',
contentType: 'application/json',
success: function (data){
console.log(data);
if (data == 1) {
window.location.href = '#Url.Action("Index", "Home")';
} else {
$('#login-warning').show();
}
},
error: function (data) {
$('#login-warning').show();
}
});
} else if (!email) {
$('#text-danger-email').show();
} else if (!password) {
$('#text-danger-password').show();
}
}
controller
[Route("login-testing")]
public JsonResult LoginTesting(LoginViewModel smodel)
{
var email = smodel.email;
var password = smodel.password;
DBHandle sdb = new DBHandle();
var account = sdb.GetLoginVerify(email);
if (account.password != null)
{
if (BCrypt.Net.BCrypt.Verify(password, account.password ))
{
var detail = sdb.GetUserDetail(account.id);
if (detail != null)
{
Session["is_login"] = true;
Session["id"] = detail.id;
Session["fullname"] = detail.fullname;
Session["id_levels"] = detail.id_levels;
Session["levels"] = detail.levels;
return Json(1);
}
else
{
return Json(2);
}
}
else
{
return Json(3);
}
}
else
{
return Json(4);
}
}
Please anyone help me to solve this problem.
Thanks.
Internal Server Error probably means something is wrong with your program.cs file .The order in which they are placed is important,improper placements could actually give rise to these errors.
500 internal server also means , there is something wrong with your Code,
according to me Go to Chrome Dev Tool and Click on Network Tab, in that Click on XHR tab
there your API call must located with red Highlighted text (Since its 500 internal server error ), Click on it, right side window will be appear then
click on Preview Tab , you might see which line of Code causing the issue
You can also Debug the Code , and step over code line by line, and check what is wrong.

How to send data to the server via Ajax?

The registration form must be Ajax , to send data to the server via Ajax . When you click the submit appears a spinning gear . If the registration was successful then a message " You have successfully registered " If not occur with the error message " Invalid Email Address " or " username already exists " , etc.
We include the jQuery library page
JQuery add an event that no longer do submit the form
Added an event with jQuery , when making submit to execute ajax
Depending on the message came to Ajax , whether to show success or failure
This is all greatly simplified but on the javascript side, you could do this:
var params = {"email": $("input#email")
$.post(yourserver.php, params, validate, "json")
function validate(response) {
if (response.success) {
console.log("Allgood")
} else {
console.log(response.message)
}
}
and on the php server side, your server.php could look like this:
<?
if ( $_REQUEST["email"] ) {
$response = array("success" => true)
} else {
$response = array("success" => false, "message" => "Missing email");
}
echo json_encode($response);
?>
function success(answer) {
$(".loader").hide(); // Hide loader element
// Back-end side must return 3 numbers, where is
// 1 - success
// 2 - invalid email
// 3 - username already exists
if (answer === 1) { // if returned code "1" then output message of success
console.log("You have successfully registered");
} else if (answer === 2) { // if returned code "2" then output message of invalid email
console.log("Invalid Email Address");
} else if (answer === 3) { // if returned code "3" then output message of username already exists
console.log("Username already exists");
}
function loading() {
$(".loader").show(); // Show loader element
}
$("#submit").on("submit", function() {
$.ajax({
url: ("/handler"), // url address of your handler
type: "POST",
data: ({
email: $("input#email"),
login: $("input#login"),
password: $("input#password")})
beforeSend: loading, // should call loading() without arguments
success: success, // should call success(answer) where answer is result which returned your server
});
});

jQuery AJAX Page Redirection Error

$.ajax({
url: "NewUserRegistrationServlet",
type: "post",
cache: false,
data : "username="+username+"&password="+encodeURIComponent(pswd)+"&email="+encodeURIComponent(email),
dataType:"xml",
timeout: 3000,
success: function(data) {
var xml_node = $('ResultSet',data);
var status = xml_node.find('result').text() ;
var result = xml_node.find('status').text() ;
if( (result > 0) && ( status == 'SUCCESS') ) {
alert("This Statement is getting executed");
//window.location.replace("login.jsp"); // Not Working
//window.location.href = 'http://localhost:8080/MyProj/login.jsp'; // Not Working
window.open = ('login.jsp','_top'); // Not Working
}else{
$("#RegisErr").siblings("p").remove();
$("#RegisErr").after("<p>User Registration failed! Please Try Again.</p>");
}
},
error: function(xhr, status, text) {
$("#RegisErr").siblings("p").remove();
$("#RegisErr").after("<p>User Registration failed! Please Try Again.</p>");
}
});
What i am doing wrong
OnSubmit -> Validation of form // Working Fine
If Valid -> Do Ajax Request // Working Fine
On Success of Ajax -> Redirect to other JSP Page // Not Woking
EDIT
Screenshot Chrome Debugger
Solved
windows.location = "login.jsp"
Thanks Everyone for your help.
To make your method work i.e. one of :-
1. window.location.replace("http://stackoverflow.com");
2. window.location.href = "http://stackoverflow.com";
The browser is still submitting the form after your code runs.
Add return false; to the handler to prevent that.
Otherwise, use just window.location = "http://stackoverflow.com";
Refer to this post ( window.location.href not working ) for further clarification. If you still face a problem, tag me again. I will write a detailed answer for you.
This comment is the code for your solution to work - https://stackoverflow.com/a/6094213/1366216
Please trim all white spaces from result. you should write following line before if block.
if(Number(result)>0 && status.trim()==="success")
{
//do anything you want
}

how can i pass a username once logged in

Im trying to build an api where the user has to be logged in to post reviews.
Ive hidden the reviews button and set it to show once the user logs in.
var loggeduser;
function Login(){
$.ajax({
url: 'http://creative.coventry.ac.uk/~4089797/Games/V2.0/Client4/index.php/users/account/'+$("#loginusername").val(),
headers: {Authorization:window.btoa($("#loginusername").val()+':'+$("#loginpassword").val())},
contentType: "get",
dataType: 'json',
success: function(data) {
Authorisation = window.btoa($("#loginusername").val()+':'+$("#loginpassword").val()); //create a variable to pass to the cookie
createCookie('auth',Authorisation,0); //create our authorisation cookie for the client
alert("Details correct. Please continue.");
loggeduser=username;
$("#login").hide(); //hide the login button
$("#create").hide(); //hide the create an account buttons
$("#logout").show(); //show the logout button
$("#addreview").show(); //show the add a review button
$("#adminpanel").show();//show the admin panel page
$("#loginusername").val(''); //clear the name box
$.mobile.changePage("#home"); //show the menu
},
error: function (response) {
var r = jQuery.parseJSON(response.responseText);
console.log(r);
alert("Error:" + r.error.text);
}
});
}
ive used the above ajax call to log the user in and have tried to pass the username from this get to loggeduser.
function Postreview(){ //Add a review to the site
$.ajax({
type:'post',
url: 'http://creative.coventry.ac.uk/~4089797/Games/V2.0/Client4/index.php/games/review/',
data: {ean:reviewean,
review_title:$("#ReviewTitle").val(),
review:$("#Review").val(),
rating:$("#rating").val(),
username:loggeduser},
dataType: 'json',
success: function(data) {
alert("Review Added. Please continue.");
$("#reviewtitle").val(''); //clear the text boxes
$("#review").val('');
$("#rating").val('');
Getreviews(ean);
},
error: function (response) {
var r = jQuery.parseJSON(response.responseText);
console.log(r);
alert("Error:" + r.error.text);
}
});
}
this is where the user posts the review however when the user submits review the username field is null and therefore hasnt been passed on
In your login ajax response, loggeduser is set to username
loggeduser=username;
... but username does not seem to exist? Perhaps you meant data.username?
Whatever the case, you should probably return from the server the username that has been authenticated, and use data.username to set loggeduser.
Also, storing the password in a cookie is a terrible idea. Are you using PHP sessions?
this is not how AJAX work where A stands for asynchronous
you have two option
1) in your Login() AJAX success do Postreview(username)
2) not recommended : async:false for login ajax

Using $.post to authenticate user to return custom error / success message

I am having this jQuery to authenticate users into site, how can I make two actions for success/error returned by login.php? Is it possible to refresh the page on success (for example) and post error message if the login info was not successful in login.php. I hope my question is clear. Here is the code. Right now it just paste the data output from login.php and I do not know how to seperate success/error returned server side.
$("#form-login").submit(function(event) {
event.preventDefault();
var $form = $( this ),
log = $form.find( 'input[name="log"]' ).val(),
pwd = $form.find( 'input[name="pwd"]' ).val(),
rememberme = $form.find( 'input[name="rememberme"]' ).val();
$.post( '/ajax/login.php', { log: log, pwd: pwd, rememberme: rememberme },
function(data) {
$(".form-login-status").html(data);
}
);
});
In your server side script, return the status as well as the message, like this:
$result = array();
if (login_is_successful()) {
$result['status'] = true;
$result['message'] = "Logged in";
} else {
$result['status'] = false;
$result['message'] = 'Incorrect password';
}
echo json_encode($result);
This gives you the flexibility to send any response message from the server side without needing to handle it specially in your client side code. Tomorrow, if you want to send messages 'Incorrect Username' and 'Incorrect Password' separately, you can do so without any change to your JS as long as $result['status'] remains false.
Then in the success handler of your $.post, do this:
success : function(resp) {
if (resp.status) {
//user logged in
//refresh page
window.location.reload();
} else {
//failed authentication
alert(resp.message);
}
}
Make sure you set dataType: 'json'
Important Note:
If authentication fails, the erorr handler in your $.post WILL NOT be called, therefore you have to check for failed authentication in your success handler.
The error handler is only called when there is an error in making the POST request.
Sure, it's in the documentation:
$.post("example.php", {}, function() {
alert("success");
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
In your 'success' handler, you'll need to process a flag returned by the requested URI that states whether or not the credentials authenticated the user or not. You'll want to branch your logic based on that logic.

Categories