Closing a dialog box if ajax sucess - javascript

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.

Related

Confirming Retweet

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);
}
});
}

jQuery unobtrusive validation not firing on dynamic content load

I am trying to parse a dynamically inserted form to add the jQuery unobtrusive validation.
I have the following AJAX function which is executed when the user is searching:
function search(el)
{
var $this = $(el);
var $form = $this.closest("form");
var url = $form.attr("action");
$results = $("#pnlSearchResults");
$.ajax({
type: "POST",
url: url,
data: $form.serialize()
})
.done(function(data){
$results.html('');
$results.html(data);
var $editForm = $results.find("form.edit-form");
$editForm.removeData("validator");
$editForm.removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse($editForm);
});
}
This inserts an editable form for the returned entity into a <div> on the page which looks like this. I have two fields which are required, but when I remove the values from those fields the "Required" validation does not fire. It only seems to occur when:
I delete the values.
Take the cursor away from the field.
Enter a new value.
Take the cursor away.
Then delete the new value.
How can I solve this so that the validation occurs when I delete the value the first time?
I found this question, which led me to an answer on this page.
(function ($) {
$.validator.unobtrusive.parseDynamicContent = function (selector) {
//use the normal unobstrusive.parse method
$.validator.unobtrusive.parse(selector);
//get the relevant form
var form = $(selector).first().closest('form');
//get the collections of unobstrusive validators, and jquery validators
//and compare the two
var unobtrusiveValidation = form.data('unobtrusiveValidation');
var validator = form.validate();
$.each(unobtrusiveValidation.options.rules, function (elname, elrules) {
if (validator.settings.rules[elname] == undefined) {
var args = {};
$.extend(args, elrules);
args.messages = unobtrusiveValidation.options.messages[elname];
//edit:use quoted strings for the name selector
$("[name='" + elname + "']").rules("add", args);
} else {
$.each(elrules, function (rulename, data) {
if (validator.settings.rules[elname][rulename] == undefined) {
var args = {};
args[rulename] = data;
args.messages = unobtrusiveValidation.options.messages[elname][rulename];
//edit:use quoted strings for the name selector
$("[name='" + elname + "']").rules("add", args);
}
});
}
});
}
})($);
Usage:
var html = "<input data-val='true' "+
"data-val-required='This field is required' " +
"name='inputFieldName' id='inputFieldId' type='text'/>";
$("form").append(html);
$.validator.unobtrusive.parseDynamicContent('form input:last');

How to call an AJAX function on anchor tag?

I'm using PHP, jQuery, AJAX, Smarty for my website. I'm having following line of code from smarty template. I wan to call the jQuery AJAX function on the onclick of that hyperlink but I'm not able to call it. Can you help me in giving call to the jQuery AJAX function?
Following is my code.
Code from Smarty template:
<a class="edit_user_transaction_status" href="{$control_url}{$query_path}?op=edit_user_transaction&page={$page}&txn_no={$user_transaction_details.transaction_no}&transaction_data_assign={$user_transaction_details.transaction_data_assign}&user_id={$user_id}{if $user_name!=''}&user_name={$user_name}{/if}{if $user_email_id!=''}&user_email_id={$user_email_id}{/if}{if $user_group!=''}&user_group={$user_group}&{/if}{if $user_sub_group!=''}&user_sub_group={$user_sub_group}{/if}{if $from_date!=''}&from_date={$from_date}{/if}{if $to_date!=''}&to_date={$to_date}{/if}{if $transaction_status!=''}&transaction_status={$transaction_status}{/if}{if $transaction_no!=''}&transaction_no={$transaction_no}{/if}">Update</a>
jQuery AJAX function is as follows:
$(".edit_user_transaction_status").click(function(e) {
e.preventDefault();
//for confirmation that status change
var ans=confirm("Are you sure to change status?");
if(!ans) {
return false;
}
var post_url = $(this).attr('href');
var transaction_status_update = $('#transaction_status_update').val();
$.ajax({
type: "POST",
url: post_url+"&transaction_status_update="+transaction_status_update,
data:$('#transaction_form').serialize(),
dataType: 'json',
success: function(data) {
var error = data.login_error;
$(".ui-widget-content").dialog("close");
//This variables use for display title and success massage of transaction update
var dialog_title = data.title;
var dialog_message = data.success_massage;
//This get link where want to rerdirect
var redirect_link = data.href;
var $dialog = $("<div class='ui-state-success'></div>")
.html("<p class='ui-state-error-success'>"+dialog_message+"</p>")
.dialog({
autoOpen: false,
modal:true,
title: dialog_title,
width: 500,
height: 80,
close: function(){
document.location.href =redirect_link;
}
});
$dialog.dialog('open');
}
});
});
});
If I try to print the alert at the beginning of function it's not getting printed. Can you help me in achieving this? Thanks in advance.
Corrected Code:
$(".edit_user_transaction_status").click(function(e) {
e.preventDefault();
//for confirmation that status change
var ans=confirm("Are you sure to change status?");
if(!ans) {
return false;
}
var post_url = $(this).attr('href');
var transaction_status_update = $('#transaction_status_update').val();
$.ajax({
type: "POST",
url: post_url+"&transaction_status_update="+transaction_status_update,
data:$('#transaction_form').serialize(),
dataType: 'json',
success: function(data) {
var error = data.login_error;
$(".ui-widget-content").dialog("close");
//This variables use for display title and success massage of transaction update
var dialog_title = data.title;
var dialog_message = data.success_massage;
//This get link where want to rerdirect
var redirect_link = data.href;
var $dialog = $("<div class='ui-state-success'></div>")
.html("<p class='ui-state-error-success'>"+dialog_message+"</p>")
.dialog({
autoOpen: false,
modal:true,
title: dialog_title,
width: 500,
height: 80,
close: function(){
document.location.href =redirect_link;
}
});
$dialog.dialog('open');
}
});
});
Note: Remove }); from the last line.

How to keep track of actions called by a jQuery dialog box?

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>

Update row in WebGrid with JQuery

FOUND THE PROBLEM:
Just needed to replace row.replaceWith with row.parent().parent().replaceWith().
I'm trying to update a WebGrid row with JQuery after I've clicked a submit button in a modal dialog, but the updated data just append the last column, not the whole row as I want.
Let's say I want the table to look like this after the update:
ID - Name - Phone number
But with my code it looks like this after the update:
ID - Name - ID - Name - Phone number
as it just replaces the last column with a new table within the last column with the updated data.
I'm getting the correct data as output, but in the wrong place in the row.
Please help! :)
Here is the Javascript code:
$(function () {
$("#edit-event-dialog").dialog({
resizable: false,
height: 300,
modal: true,
autoOpen: false,
open: function (event, ui) {
var objectid = $(this).data('id');
$('#edit-event-dialog').load("/Events/CreateEditPartial", { id: objectid });
},
buttons: {
"Save": function () {
var ai = {
EventID: $(this).data('id'),
Name: $("#Name").val(),
Phone: $("#Phone").val()
};
var json = $.toJSON(ai);
var row = $(this).data('row');
$.ajax({
url: $(this).data('url'),
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
var grid = $(".pretty-table");
row.replaceWith('<tr><td>' + data.ev.EventID + '</td><td>' +
data.ev.Name + '</td><td>' + data.ev.Phone + '</td></tr>');
},
error: function (data) {
var data = data;
alert("Error");
}
});
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
}
});
$("#event-edit-btn").live("click", function () {
var url = $(this).attr('controller');
var row = $(this);
var id = $(this).attr('objectid');
$("#edit-event-dialog")
.data('id', id)
.data('url', url)
.data('row', row)
.dialog('open');
event.stopPropagation();
return true;
});
You have set row to $(this) which is your case represents $("#event-edit-btn") ( btw i suggest using classes as identifiers, but it's not a problem ). Later on you replace your actual button with the new <tr> set but what you actually need to do is traverse to the tr parent of that button and replace it.
Change your live handler to:
$("#event-edit-btn").live("click", function () {
var url = $(this).attr('controller');
var row = $(this).closest('tr'); //or use some #id or .class assigned to that element
var id = $(this).attr('objectid');
$("#edit-event-dialog")
.data('id', id)
.data('url', url)
.data('row', row )
.dialog('open');
event.stopPropagation();
return true;
});

Categories

Resources