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.
Related
I was working on making a facial recognition system. I used the API called Kairos.The response I got back is the data of the feature of a face or an error message from a nonface image. How can I change the response and display them on the screen, such as "success! It's a face" or "There's no face". I tried to if/else statement, but it seems that there's no response from it. How should I do it?
<script>
$("#testDetect").click(function () {
var file = $('#imageFile')[0].files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onloadend = function () {
var imageData = parseImageData(reader.result);
var data = {};
data.image = imageData;
$.ajax({
url : "http://localhost/Karios/simple-detect/form-post.php",
type : "POST",
data : data,
dataType : 'text'
}).done(function(response) {
console.log(response);
if (!response) { // Something unexpected happened. The message body is empty.
alert('Hmm, unexpected response from Kairos');
} else if (response['Errors'] && response['Errors'].size() > 0) { // If Errors is defined in the response, something went wrong.
if (response['Errors'][0]['ErrCode'] == 5002) { // This appears to be the error when no faces are found.
alert(response['Errors'][0]['Message']);
} else {
alert('Some other error occurred:\n' + response['Errors']['ErrorCode'] + ': ' + response['Errors']['Message']);
}
} else { // If there are no errors in the response, can we assume it detected a face? I guess so.
alert('Face(s) detected');
// The response has a ton of information about what it saw, including gender, age, ethnicity
// and more.
}
})
}
});
Based on the response that you receive, you can write what you want to be displayed:
if(response === true){
alert('success!');
}
else{
alert('fail!');
}
EDIT
To redirect to another page, use: window.location = http://mywebsite.com;
To make a button unclickable, you will need to set the disabled attribute: document.querySelector('button').setAttribute('disabled',true);
EDIT
If this is your response: {"Errors":[{"Message":"no faces found in the image","ErrCode":5002}]} then you will have to parse it first because it will most likely be a string. Then in your conditional statement, check to see if it exists.
var obj = '{"Errors":[{"Message":"no faces found in the image","ErrCode":5002}]}';
obj = JSON.parse(obj);
if(obj.Errors){
console.log("errors exist");
}
In addition to .done(), you can call .fail() which will run when the ajax was unsuccessful.
$("#testDetect").click(function() {
var data = {}
$.ajax({
url: "http://localhost/Karios/simple-detect/form-post.php",
type: "POST",
data: data,
dataType: 'text'
}).done(function(response) {
alert(response)
}).fail(function(error) {
alert("Not a face")
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="testDetect">Test</button>
Obviously I am using #Html.ValidationSummary() in my View to display any errors that may have occurred when the user posted to my controller.
However this is my scenario
The user posts to the controller and ModelState.IsValid = false;
#Html.ValidationSummary() displays my error message to the user.
Now the user corrects the error and clicks the submit button. However I want to clear that error message because I may present the user another option (client side script) prior to the post actually occurring.
I've tried various techniques for hiding the Validation Summary section to no avail.
function resetValidation() {
$("form").data("valmsg-summary").hide();
$(".field-validation-error").addClass("field-validation-valid");
$(".input-validation-error").addClass("input-validation-valid");
$(".validation-summary-errors").addClass("validation-summary-valid");
$(".field-validation-error").removeClass("field-validation-error");
$(".input-validation-error").removeClass("input-validation-error");
$(".validation-summary-errors").removeClass("validation-summary-errors");
};
This is the script of my Submit button.
$("#btnSubmit").click(function (e) {
resetValidation(); // Trying to suppress/clear error messages
var doPost = true;
var p1 = $("#Field1").val();
var p2 = $("#Field2").val();
var p3 = $("#Field3").val();
$.ajax({
type: "GET",
url: "/MyController/MyAction",
data: { "param1": p1, "param2": p2, "param3": p3 },
async: false
}).done(function (data) {
if (data > 999)
{
// I then display a new set of fields for the user to answer
doPost = false;
}
}).fail(function (xhr, status, err) {
alert(xhr.responseText);
});
return doPost;
});
Am I going about this the wrong way?Is it possible to clear the modelview errors client side?
Thanks to Stephen Muecke for the solution:
$(".validation-summary-errors").empty();
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.
I currently build mobile application, I'm using PhoneGap (Cordova) as my framework to build my application.
I want to ask, why there's Uncaught ReferenceError on my eclipse console when I try to submit the form (I test it on my android phone, with android version 2.3.6)?
I'm trying compile it on GoogleChrome browser (Also Firefox) on there, I'm not getting error.
Here's my code :
Ajax (I'm using Ajax and also JQuery) :
function updateUser() {
/*get data from ID in updateprofile.html*/
var IDUser = sessionStorage.Uid_user;
var fname = $("#INAwal").val();
var lname = $("#INAkhir").val();
/*end of get data*/
//create form_data for post data on ajax PHP
var file_data = $("#chImage").prop("files")[0];
var form_data = new FormData();
form_data.append("file", file_data);
form_data.append("PHPIDUser", IDUser);
form_data.append("PHPUfname", fname);
form_data.append("PHPUlname", lname);
sessionStorage.statusUpdate = 1;
loadingPage(2000);
$.ajax ({
type: "POST",
url: host+'/tosomewhere/db_userUpdate.php',
data: form_data,
contentType : false,
processData : false,
beforeSend: function() {
loadingPageW(1);
},
success: function(data){
if (data == 'update') {
loadingPage(2000);
alert("Success");
window.location = 'Profile.html';
} else if (data == 'failed') {
alert('Failed');
location.reload();
loadingPage(1000);
window.location = 'UpdateProfil.html';
} else {
alert('Connection Lost');
location.reload();
loadingPage(1000);
window.location = 'UpdateProfil.html';
}
}, //for error message
error: function (xhr, errorStats, errorMsg) {
alert("error: "+xhr.errorStats+" , "+errorMsg);
},
complete: function() {
loadingPageW(2);
}
});
};
Is there any suggest to pass it? Because I need to reach at least this version to the user(s).
FYI, I already search it, and I get the nearest question to this :
JS FormData object not defined for PhoneGap in Android
But on that question, I didn't get any further information / answer (why it not support or what to do).
If the answer is that, so I need detail answer if the phonegap not support the FormData object? (as I already mentioned, I need the 'why' and 'what to do' answer)
Thanks for any help :)
$.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
}