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>
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);
}
});
}
After saving form data, need to load the div only not whole page refresh but it first goes to Main Page Action Controller and then the DIV Load Partial Action Controller. I am unable to find the reason why it is posting whole page.
I have added the preventDefault() command too.
$("#btnSave").click(function (e) {
e.preventDefault();
var url = "#Url.Action("Save", "Note")";
var id = "1";
var model = {
modelfields.....
};
$.ajax({
type: "POST",
data: JSON.stringify(model),
url: url,
contentType: "application/json",
success: function (data) {
if (data == "True") {
// Load div
var settings = { editUrl: '#Url.Action("Get", "Note", new { ID = "-1" })' };
settings.editUrl = settings.editUrl.replace("-1", id);
$("#divNoteDetails").load(settings.editUrl);
}
else if (data == "False") {
alert('not saved');
}
},
error: function () {
alert('error');
}
});
return false;
});
if your button is inside a form then its default type is submit. see the spec for details
try adding type="button" to the button, or event.preventDefault() on an event handler attached to the form itself.
<script>
$(document).ready(function() {
$("#btnSubmit").live('click',function(){
var sum = '0';
$("[id^=FormData_][id$=_c_data]").each(function(){
var c_data = $(this).val();
var required = $(this).attr("data-required");
var label = $(this).attr("data-label");
if(required == '1'){
if(c_data == ""){
sum += '1';
}
}
});
if(sum == "0"){
$("[id^=FormData_][id$=_c_data]").each(function(){
var c_data = $(this).val();
var admin = $(this).attr("data-admin");
var form = $(this).attr("data-form");
var component = $(this).attr("date-component");
var unic = $(this).attr("data-unic");
var user = $(this).attr("data-user");
var url = "<?php echo Yii::app()->createUrl('formdata/admin&id='.$form_id);?>";
if(c_data == ""){
var site_url = "<?php echo Yii::app()->createUrl('/formdata/deleteDetail' ); ?>";
jQuery.ajax({
type: "POST",
url: site_url,
data: {new_value:c_data,admin:admin,form:form,component:component,unic:unic,user:user},
cache: false,
async: false,
success: function(response){
}
});
} else {
var site_url = "<?php echo Yii::app()->createUrl('/formdata/updateDetailValue' ); ?>";
jQuery.ajax({
type: "POST",
url: site_url,
data: {new_value:c_data,admin:admin,form:form,component:component,unic:unic,user:user},
cache: false,
async: false,
success: function(response){
}
});
}
});
window.location = "http://www.example.com";
}else {
if(sum != ""){
bootbox.dialog({
message: 'Please Fill All Required Field !',
title: 'Alert',
buttons: {
main: {
label: 'OK',
className: 'blue'
}
}
});
return false;
}
}
});
});
</script>
in this script window.location = "http://www.example.com"; is not working.
But I check alert message it is working fine. why its not working in if condition.
I need to redirect page when each function was completed.
please any one help me:-((((((((((((((((((((((((((((
Try this.,
window.location.href = 'http://www.google.com';
This may work for you.
Window.location.href and Window.open () methods in JavaScript
jQuery is not necessary, and window.location.replace(url) will best simulate an HTTP redirect.
still you want to do this with jQuery use this $(location).attr('href', 'url')
If I got your question correct, you want to redirect the user when all your ajax requests, within your each function, are completed. For this, you can create an array that will hold the success status of each ajax request, and depending on this array you may do your redirection task.
Add below few snippets to your existing code:
In your #btnSubmit click function (Though, I recommend you use .on() delegation method)
var ajax_succ_arr = []; // success status container
var this_ajax_succ = false; // flag
In you success function of both ajax calls (within your each function).
if(c_data == ""){
...
jQuery.ajax({
...
success: function(response){
if(response == "1"){
this_ajax_succ = true; // set true if required response is received
}
}
});
ajax_succ_arr.push(this_ajax_succ); // push it to the success array
} else {
...
jQuery.ajax({
...
success: function(response){
if(response == "1"){
this_ajax_succ = true; // set true if required response is received
}
}
});
ajax_succ_arr.push(this_ajax_succ); // push it to the success array
}
And finally your redirection. Put this just after each function ends.
if(ajax_succ_arr.indexOf(false)<0){ // if all statuses are ok
window.location="http://www.example.com";
}
Hope this helps.
I'm using dialog box for add new users to db , I want to close dialog box if validation pass and user successfully saved. please advice
$('.add_user_link a').each(function () {
var $link = $(this);
var $dialog = $('<div id="dialog"></div>')
.load($link.attr('href') + ' #content')
.dialog({
autoOpen: false,
title: $link.attr('title'),
});
$link.click(function () {
$dialog.dialog('open');
$('#add_user').submit(function () {
url = '/user/useradd/';
$.ajax({
type: "POST",
cache: false,
url: $('#add_user').attr('action'),
data: $('#add_user').serializeArray(),
success: function (data) {
var json_obj = $.parseJSON(data);
var result = json_obj['result'];
var lname = json_obj['lname'];
var email = json_obj['email'];
var fname = json_obj['fname'];
if (!result) {
$("#dialog").dialog('close');
}
else {
//
document.getElementById('email-error').innerHTML = email;
var fname_count = $("label[id*='errorfname']").length;
$('input[name=fname]').after('<label id="errorfname"></label>');
document.getElementById('errorfname').innerHTML = fname;
var lname_count = $("label[id*='errorlname']").length;
if (lname_count == 0) {
$('input[name=lname]').after('<label id="errorlname"></label>');
document.getElementById('errorlname').innerHTML = lname;
}
}
}
});
return false;
});
return false;
});
});
I'm getting this error
jquery-1.11.1.min.js:2 Uncaught Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'
Replace:
$("#dialog").dialog('close');
With
$dialog.dialog('close')
You've already set a variable for your dialog in the click function which should be in scope so you don't need to reselect it.
UPDATE:
Element IDs should be unique so you should make the dialog ID unique when adding it for a link if there are multiple links. Otherwise, you will select multiple dialog elements when you do this $('#dialog') when there are mulitiple links.
When you do this:
$dialog = $('<div id="dialog"></div>')
the ID value "dialog" should be something unique, like "dialog1", "dialog2", etc.
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.