LogIn Page Using JQuery - javascript

Before 3 days the code was working fine. But now its not.
please point out my mistake as i am new to JQuery.
I debugged it, and found out that debugger is not entering inside success method of ajax. and not even going to CS file.
Code of Jquery-
<script type="text/javascript">
$(document).ready(function () {
$('#btnSubmit').click(function () {
alert('b');
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "admin.aspx/LogIn",
dataType: "json",
data: "{'name':'" + $('#txtfn').val() + "','password':'" +$('#txtln').val() + "'}",
success: function (data) {
alert(data);
var obj = data.d;
alert(obj);
alert(data.d);
if (obj == 'true') {
$('#txtfn').val('');
$('#txtln').val('');
alert("dasdsad");
window.location = "home.aspx";
alert("success");
}
else if (obj == 'false')
{ alert("errorrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr"); }
},
error: function (result) {
alert(data);
alert("aaaaaaafgdgfdfgsfgfhffghgfhgfhfghfghfhfghfhfghgfhgfhgfhgfhfghfghgfhgfhgf");
alert(result);
}
});
});
});
</script>
</head>
<body>
<div id="login">
<div id="triangle"></div>
<h1>Log in</h1>
<form id="f1" runat="server">
<input type="text" id="txtfn" placeholder="name" />
<input type="text" id="txtln" placeholder="Password" />
<input type="submit" id="btnSubmit" value="Log in" />
</form>
</div>
</body>
Code-
[WebMethod]
public static string LogIn(string name, string password)
{
string retMessage = string.Empty;
string constr = ConfigurationManager.ConnectionStrings["oltest_conString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string Query = "select * from profile where name=#pname and password=#pwd";
using (SqlCommand cmd = new SqlCommand(Query, con))
{
cmd.Parameters.AddWithValue("#pname", name);
cmd.Parameters.AddWithValue("#pwd", password);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
//retMessage = "home.aspx";
retMessage = "true";
}
else
{
retMessage = "false";
}
}
return retMessage;
}
}

You just need to remove
alert('b');``
on your jquery code

try adding a
return false
at the end of the ajax call

Hi change your submit button to button.
<input type="button" id="btnSubmit" value="Log in" />
data: {name: $('#txtfn').val() ,password: $('#txtln').val()},

I updated my answer:
your ajax call is not executed because form is submitted, this code will prevent submission
$("#f1").submit(function (e) {e.preventDefault();})
place it before $('#btnSubmit').click(function () {
better way will be place your code inside
$("#f1").submit(function (e) {
e.preventDefault();
// here place content of $('#btnSubmit').click(function () {( )}
})

Please ensure JSON data /parameters accepted by your web method and it returning proper true/false without any exception/error.
You can do it by debugging in firebug and Visual Studio.

Related

Maintain the state of checkbox on page Load in MVC

My issue is related to Page load.
I have the following code:
Controller:
public ActionResult Index()
{
BD.isEmailON_OFF= db.Email_ON_OFF_T.Select(x=>x.isEmailON_OFF).FirstOrDefault().GetValueOrDefault();
}
[HttpPost]
public ActionResult CheckEmail(string checkemails)
{
//calling Stored Procedure
if (!string.IsNullOrWhiteSpace(checkemails)|| checkemails=="true" || checkemails=="false")
{
var checkemails1 = new SqlParameter("checkemails", checkemails);
db.Database
.ExecuteSqlCommand("EXEC Sp_Email_on_off #checkemails", checkemails1);
}
return new JsonResult { };
}
I have table IS_Email_on_OFF_T:
I inserted to isemailonoff column as 0
Functionality:
I have turned on the email button and checkbox.
turn on email----->becomes turn off button and checkbox checked.
turn off button----> becomes turn on button and checkbox unchecked.
worked correctly till here.
turn on email----->becomes turn off button and checkbox checked.
page load(loading the page)
clicking on turn off button and not changing to turn on the button(1st attempt)(ISSUE)
clicking on turn off button(2nd tym) and it changes.
What I have tried is:
Views:
#{
if (Model.isEmailON_OFF == 0)
{
<input type="button" value="Turn Email on" class="btn btn-success" id="btnturnemailonoff" />
<input type="checkbox" id="Chkemailonoff" style="float:right;" />
}
else
{
<input type="button" value="Turn Email off" class="btn btn-success" id="btnturnemailonoff" />
<input type="checkbox" id="Chkemailonoff" style="float:right;" checked/>
}
}
AJAX call on button click:
<script type="text/javascript">
$(document).ready(function () {
$('#btnturnemailonoff').on('click', function () {
var checked = !$(this).data('checked');
var message = checked ? 'Turn Email ON' : 'Turn Email OFF';
if (confirm("Do you want to " + message + "? ")) {
$("#Chkemailonoff").prop('checked', checked);
$(this).val(checked ? 'Turn Email Off' : 'Turn Email on')
$(this).data('checked', checked);
debugger;
var url = '#Url.Action("CheckEmail", "BillingDetails")';
$.ajax({
url: url,
type: "POST",
data: { checkemails: checked },
dataType: "json",
// traditional: true,
success: function () {
alert("ajax request to server succeed");
}
});
}//end of if
});
});
</script>
SP:
ALTER procedure [dbo].[Sp_Email_on_off]
#checkemails varchar(10)
As
Begin
if(#checkemails='false')
Update Email_ON_OFF_T set isEmailON_OFF=0
else
Update Email_ON_OFF_T set isEmailON_OFF=1
End
I made changes in AJAX call button click and it worked for me.
$(document).ready(function () {
$('#btnturnemailonoff').on('click', function () {
debugger;
var checked = $("#Chkemailonoff").prop('checked');
var message = checked ? 'Turn Email On' : 'Turn Email Off';
if (confirm("Do you want to " + message + "? ")) {
$("#Chkemailonoff").prop('checked', !checked);
$(this).val(message)
var url = '#Url.Action("CheckEmail", "BillingDetails")';
$.ajax({
url: url,
type: "POST",
data: { checkemails: !checked },
dataType: "json",
success: function () {
//alert("ajax request to server succeed");
}
});
}
});
});

Why I cannot Login the using c# and mysql in ASP.net

I am beginner in developing a website using ASP.Net
Please Help me. so that i can pursue my career. Thanks in Advance
I am creating a login script using c# and I want to call it in javascript.
But it after I Logged in, The Login page will only refreshing.
And there is an exception said Exception thrown: 'System.InvalidOperationException' in System.Web.Extensions.dll
So here is my code :
HTML
<form>
<div class="form-group">
<input type="text" class="form-control material" id="username" placeholder="Username">
</div>
<div class="form-group">
<input type="password" class="form-control material" id="password" placeholder="Password">
</div>
<button type="submit" id="btnLogin" class="btn btn-block btn-info text-uppercase waves">Login</button>
</form>
JAVASCRIPT:
$(document).ready(function () {
$("#btnLogin").click(function () {
var username = $("#username").val();
var password = $("#password").val();
AuthenticateUser(username, password)
});
});
function AuthenticateUser(username, password) {
var value = "{'email':'" + username
+ "','pass':'" + password
+ "'}";
$.ajax({
type: 'POST',
url: '../WebService/csLogin.asmx/loadEmployeeAccount',
dataType: 'json',
data: value,
contentType: 'application/json; charset=utf-8',
success: function (response) {
var cells = eval("(" + response.d + ")");
console.log(cells);
if (cells.length >= 1) {
window.location.href = "index.html";
} else {
alert("Invalid Email/Password");
document.getElementById("username").focus();
}
},
error: function (error) {
alert(JSON.stringify(error))
}
});
}
C#:
[WebMethod]
public string loadEmployeeAccount(string email, string pass)
{
List<Auth> mylist = new List<Auth>();
using (MySqlConnection connection = new MySqlConnection(connectionString()))
{
connection.Open();
MySqlCommand cmd = new MySqlCommand("SELECT * FROM user WHERE username = #email AND password = #pass", connection);
cmd.Parameters.Add("#email", MySqlDbType.VarChar).Value = email;
cmd.Parameters.Add("#pass", MySqlDbType.VarChar).Value = pass;
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = 0;
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
int user = 0;
if (dr["userType"].ToString() == "")
user = 1;
else
user = Convert.ToInt32(dr["userType"].ToString());
mylist.Add(new Auth
{
user_id = dr["user_id"].ToString(),
username = dr["username"].ToString()
});
}
dr.Close();
connection.Close();
}
JavaScriptSerializer jss = new JavaScriptSerializer();
string jsn = jss.Serialize(mylist);
return jsn;
}
And here is the image on the console.
Can someone help me with this?? any help will much be appreciated. Thanks
Okay, in order to achieve your functionality follow these steps:
In your AJAX, do the following to convert your value string as JSON and then send it to your WebMethod:
data: {"json": JSON.stringify(value)}
Then decorate your class with:
[System.Web.Script.Services.ScriptService]
to allow POST requests via AJAX to your WebMethod.
And then in your WebMethod, do the following to parse your JSON string that you received from your AJAX call:
[WebMethod]
public string loadEmployeeAccount(string json)
{
dynamic jsondata = serializer.Deserialize(json, typeof(object));
string username = jsondata["email"];
string password=jsondata["pass"]
//Your code here
}
it seems there is issue in passing value from ajax call please make change in your javascript function to call webmethod
function AuthenticateUser(username, password) {
var value = {'email':username,
'pass':password};
$.ajax({
type: 'POST',
url: '../WebService/csLogin.asmx/loadEmployeeAccount',
dataType: 'json',
data: JSON.stringify(value),
contentType: 'application/json; charset=utf-8',
success: function (response) {
var cells = eval("(" + response.d + ")");
console.log(cells);
if (cells.length >= 1) {
window.location.href = "index.html";
} else {
alert("Invalid Email/Password");
document.getElementById("username").focus();
}
},
error: function (error) {
alert(JSON.stringify(error))
}
});
}
I’m not familiar with pure ASP.NET, as I use MVC, but I guess they’re just the same under the hood, so this is a wild guess.
First thing, within your Ajax function you have to change the type of action from POST to GET, your error webpage is explicitly telling you you’re not supposed to send data through a POST action, after all.
type: ‘GET’
Second thing, i think the way you’re passing data to the web method is wrong: you’re passing a single literal object when your method is expecting two strings. By changing this, things should work as expected:
data: {
email: username,
pass: password
}
also, delete the dataType: ‘JSON’

Pushing array of values from a form into Google Spreadsheet comes through as 'undefined'

I have a form with text fields which the user can "Add New" by clicking a button. These fields share the same name. I'm trying pass the values into Google Spreadsheets, but the values all come through as 'undefined' with the following code, even though console.log prints the answers as strings which look okay to me.
So if the user for example submits 3 separate entries for SUNDAY_NOTES[], all 3 strings should end up in one cell broken up by new lines, but instead I'm just getting "undefined".
<form action="" method="post" id="timesheet">
<input type="text" name="SUNDAY_NOTES[]">
<input type="text" name="SUNDAY_NOTES[]">
<input type="text" name="SUNDAY_NOTES[]"> // the user can create multiples of these ^ for each day of the week
<input type="submit" id="submit" />
</form>
<script>
$(document).ready(function() {
var $form = $('form#timesheet'),
url = 'https://script.google.com/macros/s/AKf45XRaA/exec'
$('#submit').on('click', function(e) {
e.preventDefault();
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "json",
data: $form.serializeArray().map((e) => {
return e.value
}).join('\n')
});
})
});
</script>
Your code works. In the snippet below I am storing the data split by \n in a variable and logging it. You can check the output.
Although your JS is correct, I suspect that you actually want to be using a different HTTP method. Perhaps POST or PUT? I can't be specific as you have not said which API endpoint you are using.
$(document).ready(function() {
var $form = $('form#timesheet'),
url = 'https://script.google.com/macros/s/AKf45XRaA/exec'
$('#submit').on('click', function(e) {
e.preventDefault();
var data = $form.serializeArray().map((e) => {
return e.value
}).join('\n');
console.log(data);
var jqxhr = $.ajax({
url: url,
method: "POST",
dataType: "json",
data: data
}).done(response => {
console.log(response);
}).fail((jqXHR, textStatus) => {
console.log("Request failed: " + textStatus);
});
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" id="timesheet">
<input type="text" name="SUNDAY_NOTES[]">
<input type="text" name="SUNDAY_NOTES[]">
<input type="text" name="SUNDAY_NOTES[]">
<input type="submit" id="submit" />
</form>
remove the [] from your input's name as this is needed if you want to receive an array in the server side, then create a function that groups the values according to the inouts' keys :
function group(arr) {
var tempArr = [];
arr.forEach(function(e) {
var tempObj = tempArr.find(function(a) { return a.name == e.name });
if (!tempObj)
tempArr.push(e)
else
tempArr[tempArr.indexOf(tempObj)].value += ', ' + e.value;
});
return tempArr;
}
and use it like :
$('#submit').on('click', function(e) {
e.preventDefault();
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "json",
data: group($form.serializeArray()),
//... rest of your code
this will keep the original structure that works,
here's a snippet :
var $form = $('form#timesheet');
function group(arr) {
var tempArr = [];
arr.forEach(function(e) {
var tempObj = tempArr.find(function(a) { return a.name == e.name });
if (!tempObj)
tempArr.push(e)
else
tempArr[tempArr.indexOf(tempObj)].value += ', ' + e.value;
});
return tempArr;
}
$form.submit(function(e) {
e.preventDefault();
var grouped = group($form.serializeArray());
console.log(JSON.stringify(grouped))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="timesheet">
<input type="text" name="SUNDAY_NOTES"><br />
<input type="text" name="SUNDAY_NOTES"> // user can click a button to keep adding more SUNDAY_NOTES fields
<input type="text" name="MONDAY_NOTES"> // and so forth
<input type="submit" id="submit" />
</form>

Submit form using ajax and pass the value submitted to new page

i have form that need the previous value inserted....i'm using ajax,but the success: function(data) wont let me moved to the next page...
here is my code
HTML
<form>
<input type="text" name="id_1" id="id_1>
<input type="text" name="id_2" id="id_2>
<input type="text" name="id_3" id="id_3>
<button type="button" onclick="next();">
</form>
<div id="tabelna"></div>
JQuery
var id_1 = $('#id_1').val();
var id_2= $('#id_2').val();
var id_3= $('#id_3').val();
var datana = 'id_1='+id_1+'&id_2='+id_2+'&id_3='+id_3;
var urlna="<?=base_url()?>something/something/something";
$.ajax({
type: 'POST',
url: urlna,
data: datana,
beforeSend:function(data){
},
message:"<center>><h3>Loading Data. . .</h3></center>"
});
},
error: function(data) {
jAlert('Failed');
},
success: function(data) {
load();
}
})
return false;
}
function load()
{
$('#tabelna').load('<?=base_url()?>something/something/something') (This is my mistake)
}
CONTROLLER
function set_value()
{
extract($_POST);
$d['id1'] = $this-db->query('SELECT * FROM TBL1 where id='.$id_1);
$d['id2'] = $this-db->query('SELECT * FROM TBL2 where id='.$id_2);
$d['id3'] = $this-db->query('SELECT * FROM TBL3 where id='.$id_3);
$this->load->view('something/v_add',$d); (this is my mistake)
}
How can i pass the submitted value to the controller and shows new form ?
we can call controller function using window.location
function load()
{
window.location.href = "<?php echo site_url('controller_d/login/admin_link_delete_user');?>";
}

prompt confirmation box, cancel should stop execution

I have a prompt box, which when i click on delete user, should ask to confirm if he wants to delete the user,
HTML
<form name="myform" id="myform" action="/AWSCustomerJavaWebFinal/DeleteUser" method="POST" onSubmit="myFunction()">
Choose User:
<br>
<select name="selectUser" multiple style="width: 200px !important; min-width: 200px; max-width: 200px;">
<c:forEach var="user" items="${listUsers.rows}">
<option value="${user.id}">
<c:out value="${user.userId}" />
</c:forEach>
</select>
<input type="submit" value="Delete User" class="btn btn-primary" />
<input type="reset" value="Reset" class="btn btn-primary" id=button1>
</form>
javascript
function myFunction() {
var confirm = prompt("Do you want to continue", "yes");
if (confirm == yes) {
var form = $('#myform');
form.submit(function() {
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
success: function(data) {
var result2 = data;
alert("deleted")
}
});
return false;
});
$(document).ready(function() {
$(document).ajaxStart(function() {
$("#wait").css("display", "block");
});
$(document).ajaxComplete(function() {
$("#wait").css("display", "none");
});
});
return false;
} else {
alert("User not deleted")
return false;
}
return false;
}
It asks to confirm, and if I press ok after writing yes in the textbox, it goes to the servlet, and does not give the alert("deleted"), and I have returned false, it still refreshes after pressing submit, also, if i press cancel, it still executes and deletes the user. I tried a lot of different approaches but nothing seems to work here. Thanks in advance.
Try using confirm rather than prompt
var r = confirm("Continue delete?");
if (r == true) {
//your logic to delete
} else {
//alert('user dint delete')
}
A nice one-liner :
if( !confirm("Do you want to continue?") ) return alert("User was not deleted.")
return will stop the execution of the function.
You have a form.submit(function() { $.ajax... that will always trigger your ajax call whenever the form is submitted, regardless of any validation mechanism you set up.
Here is a clean, rewritten version of your code :
in HTML : <form onSubmit="confirmSubmission()"> (a bit more explicit than myFunction() ;)
$(document).ready(function() {
var $wait = $("#wait");
$(document).ajaxStart(function() {
$wait.hide();
}).ajaxComplete(function() {
$wait.show();
});
});
function confirmSubmission() {
if ( !confirm("Do you want to continue")) return alert("Submission has been canceled.")
submit();
}
function submit(){
var $form = $('#myform');
$.ajax({
type : $form.attr('method'),
url : $form.attr('action'),
data : $form.serialize(),
success: function(data) {
var result2 = data;
alert("deleted")
}
});
}

Categories

Resources