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.
Related
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");
}
});
}
});
});
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);
}
});
}
So I got this js code for a form submission, and everything is working fine, however, I don't know where and what to write in the code so the email gets a validation check. What and where should I write to validation check the email?
$(document).ready(function() {
$("#submit").click(function() {
var name = $("#fullname2").val();
var email = $("#fullemail2").val();
var state = $("#selectstate").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'FullName=' + name + '&email=' + email + '&SovereignState=' + state;
if (name == '' || email == '' || state == '') {
$('#required_fields').show();
} else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "demo.php",
data: dataString,
cache: false,
success: function(phpSays) {
if (phpSays == "OK") {
$('#email_error').show();
$('#required_fields').hide();
} else {
$('#sinatra2').hide();
$('#thanks').fadeIn(1000);
$('#spreading_message').delay(1800).fadeIn(1500);
$('#by_social').delay(3000).fadeIn(1500);
$('#email_error').hide();
$('#required_fields').hide();
}
}
});
}
return false;
});
});
Looking at your code I can suggest the below approach to say where you can do email validation
if(name==''||email==''||state=='')
{
$('#required_fields').show();
}//this is fine
else if(!valid(email))//call a function which validates email and returns true or false
{
//Display the message either with same $('#required_fields') changing the text or
//Add one more field to display invalid email message
}
else
{
//Your ajax call here
}
Now your valid function will look like
function valid(email)
{
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return emailReg.test(email); //this will either return true or false based on validation
}
$(document).ready(function(){
$("#submit").click(function(){
var name = $("#fullname2").val();
var email = $("#fullemail2").val();
var state = $("#selectstate").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'FullName='+ name + '&email='+ email + '&SovereignState='+ state;
if(name==''||email==''||state=='')
{
$('#required_fields').show();
}
else
{
// AJAX Code To Submit Form.
// <-- email address should be here
...........
}
return false;
});
});
Better place to validate is where you have 'fullemail2' input field. Even in the javascript file, you should do it before create the dataString. In that way you could validate before submit.
I have a bit of a dillema :)
I have a link for users to vote on an item. A click on a link generated a jQuery AJAX call checking if the person is logged in. If not, the dialog box displays a form to login.
But the problem is that the jQuery call to log in and the whole bit with the popup box is in a different place.
What I need to do is check if user got logged in successfully, and update the vote count.
I am doing it on this site: http://www.problemio.com
Here is my jQuery code so far:
<script type="text/javascript">
$(document).ready(function()
{
var $dialog = $('#loginpopup')
.dialog({
autoOpen: false,
title: 'Login Dialog'
});
$("#newprofile").click(function () {
$("#login_div").hide();
$("#newprofileform").show();
});
$('.vote_up').click(function()
{
problem_id = $(this).attr("data-problem_id");
var dataString = 'problem_id='+ problem_id + '&vote=+';
$.ajax({
type: "POST",
url: "/problems/vote.php",
dataType: "json",
data: dataString,
success: function(data)
{
// ? :)
alert (data);
},
error : function(data)
{
errorMessage = data.responseText;
if ( errorMessage == "not_logged_in" )
{
// Try to create the popup that asks user to log in.
$dialog.dialog('open');
// prevent the default action, e.g., following a link
return false;
}
else
{
alert ("not");
}
//alert(JSON.stringify(data));
}
});
//Return false to prevent page navigation
return false;
});
$('.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;
});
});
</script>
It all works except right after the line $dialog.dialog('open'); - I don't know how to
Get a signal back for success of fail, and don't know exactly how to
Update the very item that was voted on since it is just one of many items that can be voted on in the page.
How can I do these two things?
Try this approach:
Have a hidden input within the div that is your login dialog.
Set that with the problem_id before you do the .dialog('open')
On the success callback of the Login button click, retrieve problem_id from the hidden input and perform vote-up or vote-down.
Hope that helps
EDIT: (Trying to code a workable example after OP's second comment)
<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();
});
$('.vote_up').click(function() {
var problem_id = $(this).attr("data-problem_id");
voteUp(problem_id);
//Return false to prevent page navigation
return false;
});
var voteUp = function(problem_id) {
var dataString = 'problem_id=' + problem_id + '&vote=+';
$.ajax({
type: "POST",
url: "/problems/vote.php",
dataType: "json",
data: dataString,
success: function(data) {
// ? :)
alert(data);
},
error : function(data) {
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');
// prevent the default action, e.g., following a link
return false;
}
else {
alert("not");
}
//alert(JSON.stringify(data));
}
});
};
$('.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() {
$.ajax({
url:'url to do the login',
success:function() {
//now call cote up
voteUp($problemId.val());
}
});
});
});
</script>
So I have a form as such:
<form action="URL" name=myform method=post onsubmit="return validateFormOnSubmit(this)" autocomplete=off>
When the form is submitted, it checks for validation.
Earlier though, I have code like this:
<script type="text/javascript">
$(function() {
$("#submitbutton").click(function() {
var fname = $("input#first_name").val();
var lname = $("input#last_name").val();
var email = $("input#email").val();
var leadsource = $("input#leadsource").val();
var country = $("input#country").val();
var phone = $("input#phone").val();
var oid = $("input#oid").val();
var retURL = $("input#retURL").val();
var crazy
= $("input#00N40000001mCkP").val();
var dataString = '&email=' + email + '&phone=' + phone + '&oid=' + oid + '&retURL=' + retURL + '&leadsource=' + leadsource + '&country=' + country; //alert (dataString);return false; $.ajax({
type: "POST",
url: "MYURL.php?first_name="
+ fname + "&last_name=" + lname,
data: dataString,
success: function(response) { $(myform).submit(); }
});
return false; });
}); </script>
Essentially whats happening is, the form data is initially sent to a different url through an AJAX submit prior to completing the real form. On success of the ajax push - the form is submitted, and then the form is validated.
I need the form validation to have right when #submitbutton is clicked though - prior to the ajax request. Any ideas?
That code should work just fine. If you want to add it to a onclick= property on the element (I wouldn't, but if you insist), you can use this syntax to reference the form:
<input type="submit" onclick="return validateFormOnSubmit(this.parentNode)" />
And you'd have to do an e.preventDefault() and return false (maybe just one?) from the validateFormOnSubmit() function.
Take a look at preventDefault . Also, you can call validateFormOnSubmit in the anon function above and return false if it validation doesn't pass.
you should put some " " around your form tags attributes, and give it an id!
just call your validate function as the first line in your button click handler :)
$("#submitbutton").click(function(e) {
if( validateFormOnSubmit($('#myform'))){
//do all the posting stuff
}
else{
e.preventDefault();
return false;
}