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");
}
});
}
});
});
Related
I'm making a script that when a user clicks a button a popup box displays with a text box of the tweet and a button for the user to retweet what's in the text box. In the script it's suppose to tell the user if it has retweeted successfully. The thing is that it tells the user it's successfully retweeted before the user has clicked the retweet button in the pop up box.
Seems as though just by clicking the button that activates the pop up box display is when the code activates a successful retweet message though nothing has been retweeted on the users end.
I'm not very familiar with javascript, my guess it's not the php code that's making the faulty logic but the javascript code. Here is what I have below.
(function($) {
$(document).ready(function() {
$.getScript("http://platform.twitter.com/widgets.js", function(){
twttr.events.bind('tweet', function(event) {
var targetUrl = event.target.src;
var query = getQueryParams(targetUrl);
click_callback(query.url);
});
});
});
})(jQuery);
function getQueryParams(qs) {
qs = qs.split("+").join(" ");
var params = {}, tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])]
= decodeURIComponent(tokens[2]);
}
return params;
}
function click_callback(id){
var user = "<? echo $data->id;?>";
document.getElementById("Hint").style.display='block';
$("#Hint").html('Confirming Tweet...');
$.ajax({
type: "POST",
url: "plugins/rt/complete.php",
data: "id="+ id + "&user=" + user,
success: function(msg){
$("#Hint").html('Tweeted! Success!');
removeElement('boxes', id);
}
});
}
function removeElement(parentDiv, childDiv){
if (document.getElementById(childDiv)) {
var child = document.getElementById(childDiv);
var parent = document.getElementById(parentDiv);
parent.removeChild(child);
}
}
I think this is what's causing it within the code:
function click_callback(id){
var user = "<? echo $data->id;?>";
document.getElementById("Hint").style.display='block';
$("#Hint").html('Confirming Tweet...');
$.ajax({
type: "POST",
url: "plugins/rt/complete.php",
data: "id="+ id + "&user=" + user,
success: function(msg){
$("#Hint").html('Tweeted! Success!');
removeElement('boxes', id);
}
});
}
I have an AJAX function that works just fine when I'm on my PC. But when I switch to Safari (mobile), only the radio-boxes will trigger the AJAX. How come?
HTML:
<input type="radio" id="q1r1" name="q1" value="Awesome" onchange="GrabData(this)">
<input type="radio" id="q1r3" name="q1" value="Awful" onchange="GrabData(this)">
<div class="comment"><textarea name='q1comment' id='comment' maxlength="400" placeholder="Add a comment (max 400 characters)" onchange="GrabC(this)"></textarea>
AJAX
//AJAX question 1.
function GrabData(Passeddata){
var radioValue = Passeddata.value;
var URL = "question1.php?q1=" + radioValue + "&teamid=" + <?php echo $teamid; ?>;
$.ajax( {
url : URL,
type : "GET",
dataType: 'json',
success : function(data) {
if (data == "") {
alert("data is empty");
} else {
console.log('got your data back sir');
}
}
});
};
//AJAX for comment question 1.
function GrabC(PassedComment){
var radioValue = PassedComment.value;
var URL = "question1.php?comment1=" + radioValue + "&teamid=" + <?php echo $teamid; ?>;
$.ajax( {
url : URL,
type : "GET",
dataType: 'json',
success : function(data) {
if (data == "") {
alert("data is empty");
} else {
console.log('got your data back sir');
}
}
});
};
Again, works fine on my PC, the textarea onchange does not seems to work on Safari on the mobile. Can't figure out why!
Try keyup event along with change; change triggers when you blur, focus (not sure of this) on the element, but keyup actually listens for changes while the user is typing/tapping the keys.
$('input[type="text"]').on('change keyup', function(){
$('#console').text($('#console').text()+ "\r\n"+ this.value);
});
$('textarea').on('change keyup', function(){
$('#console').text($('#console').text()+ "\r\n"+ this.value);
/** Send to AJAX
GrabC(this);
GrabData(this);
**/
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="text"/>
<textarea row="4"></textarea>
<pre id="console"></pre>
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")
}
});
}
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.
I am trying to do this:
Have the user click some action. The action checks whether the user is logged in or not. If not, open a login dialog box, and if the user logs in correctly, update the original page.
I got almost all this working except the part of after successful login. The problem is that the code seems to not have access to the item_id which I was trying to update. Instead, when I try to set the item id (problem_id in this case) in the login form of the popup box, the id is the number of the id that is the last one on the page, and not the one that was clicked.
Here is what I am trying to do in the jQuery:
<script type="text/javascript">
$(document).ready(function()
{
var $dialog = $('#loginpopup')
.dialog({
autoOpen: false,
title: 'Login Dialog'
});
var $problemId = $('#theProblemId', '#loginpopup');
$("#newprofile").click(function ()
{
$("#login_div").hide();
$("#newprofileform").show();
});
// Called right away after someone clicks on the vote up link
$('.vote_up').click(function()
{
var problem_id = $(this).attr("data-problem_id");
//alert ("In vote up click, problem_id: " + problem_id );
voteUp(problem_id);
//Return false to prevent page navigation
return false;
});
var voteUp = function(problem_id)
{
alert ("In vote up function, problem_id: " + problem_id );
var dataString = 'problem_id=' + problem_id + '&vote=+';
$.ajax({
type: "POST",
url: "/problems/vote.php",
dataType: "json",
data: dataString,
success: function(data)
{
alert ("vote success, data: " + data);
// ? :)
},
error : function(data)
{
alert ("vote error");
errorMessage = data.responseText;
if ( errorMessage == "not_logged_in" )
{
//set the current problem id to the one within the dialog
$problemId.val(problem_id);
// Try to create the popup that asks user to log in.
$dialog.dialog('open');
alert ("after dialog was open");
// prevent the default action, e.g., following a link
return false;
}
else
{
alert ("not");
}
//alert(JSON.stringify(data));
} // Closing error case
}); // Closing AJAX call.
};
$('.vote_down').click(function()
{
alert("down");
problem_id = $(this).attr("data-problem_id");
var dataString = 'problem_id='+ problem_id + '&vote=-';
//Return false to prevent page navigation
return false;
});
$('#loginButton', '#loginpopup').click(function()
{
alert("in login button fnction");
$.ajax({
url:'url to do the login',
success:function() {
//now call cote up
voteUp($problemId.val());
}
});
});
});
</script>
and here is the login form:
<div id="login_div">
<form id="login_form" method="post" action="">
<p>
<label for="name"><span>Your Email:</span></label> <input type="text" name="email" id="email" />
</p>
<p>
<label for="name"><span>Your Password:</span></label> <input type="password" name="user_pass" id="user_pass">
</p>
<input type="hidden" id="problem_id" name="problem_id" value="<?php echo $problem_id; ?>" />
<span class="no_such_user" style="color: red; display:none">The login and password does not match our records.</span>
<span class="password_error" style="color: red; display:none">The password much be 5 characters or more.</span>
<span class="login_success" style="color: green; display:none">You successfully logged in.</span>
<p>
<input type="submit" value="Log In" />
</p>
</form>
</div>
But the problem_id which is being set in this form isn't the one being clicked on, even though I am trying to save it in my jQuery.
Also, here is the code that gets executed for login:
$(function()
{
$("#login_div input[type=submit]").click(function()
{
var email = $("#email").val();
var password = $("#user_pass").val();
//alert("Email: " + email);
//alert("password: " + password);
var dataString = 'email='+ email + '&password=' + password;
if( !email )
{
alert ("1");
$('.login_success_email_empty').fadeOut(200).hide();
$('.login_error_email_empty').fadeOut(200).show();
}
else
if( !password || password.length < 5)
{alert ("2");
$('.password_success').fadeOut(200).hide();
$('.password_error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "../auth/login_ajax.php",
dataType: "json",
data: dataString,
success: function(json)
{
$('.password_error').fadeOut(200).hide();
$('.no_such_user').fadeOut(200).hide();
$('.login_success_email_empty').fadeOut(200).hide();
$('.login_success').fadeIn(200).show();
// Closing the dialog bosx
$('#loginpopup').dialog('close');
// Swapping out the header div
$('#header_logged_out').hide();
$('#header_logged_in').show();
// Now also need to retrieve the problem_id
problem_id = $("#problem_id").val();
//$problemId = $('#theProblemId', '#loginpopup').val();
var $problemId = $('#theProblemId', '#loginpopup');
alert ("After login, problem_id: " + problem_id + " and problemId was: " + $problemId);
},
error : function(json)
{
alert ("error");
// Output the result.
errorMessage = json.responseText;
alert ("ErrorMessage: " + errorMessage );
if ( errorMessage == 'no_such_user' )
{
$('.no_such_user').fadeOut(200).hide();
$('.no_such_user').fadeOut(200).show();
}
}
});
}
return false;
});
});
and I am just not sure how to get that problem_id which was set in the original jQuery code to be recognized in the jQuery code that executes after login.
Because what I really need to do is update that particular problem depending on whether the user was logged in.
And how do I know in the original code that processes the votes, whether the login in the dialog box was successful or not?
By the way, I am working on this page: http://www.problemio.com
It seems that you might be better served using the jquery forms /ajax submit plugin:
http://be.twixt.us/jquery/formSubmission.php
$('loginDiv > form').submit(function() {
var options = {
url = "../auth/login_ajax.php",
[...]
};
$(this).ajaxSubmit(options);
return false; //this line is required to make sure that the page doesn't get redirection to /auth/login_ajax.php
});
This way it won't reload any of the javascript, preserving any variables that have already been set. You can therefore set the problem ID before the login, and then do stuff with it afterward.