jquery callback function not accessing global function - javascript

I have 2 functions declared makeAjaxCall and editOrderDetails
editOrderDetails executes makeAjaxCall to go and get a json object with the results of the call.
function editOrderDetails()
{
makeAjaxCall(
baseurl+'/orderoutbound/editorderdetails',
'orderID='+orderID+'&customerReference='+("#orderReference").val()+'&email='+$("#emailAddress").val(),
function(data){
if(data.success)
{
$("#editOrderDetailsErrorDiv").html(successDiv(data.generalMessage));
$(".customerReferenceSpan").html(data.order.customerReference);
$(".emailSpan").html(data.order.emailAddress);
}else{
$("#editOrderDetailsErrorDiv").html(errorDiv(data.generalMessage));
$("#emailAddressErrorDiv").html(data.errors.emailAddress);
}
},
function(data) {
$("#editOrderDetailsErrorDiv").html(errorDiv("There was an error.."));
}
);
}
now i'm using a jquery dialog to work with
$("#editOrderDetailsDialog").dialog('destroy').dialog({
autoOpen: false,
title: 'Edit Order Details',
closeOnEscape: true,
width: 500,
height: 300,
buttons:{
"Save": function() { editOrderDetails(); },
"Cancel": function() { $(this).dialog("close"); }
}
});
as my save call back function i'm trying to set my editOrderDetails function.
This however doesnt work and i'm guessing it has something to do with the scopeing.
i have tried declaring var editOrderDetails = function(){}; outside of any and all jquery doc ready functions
i have also tried window.editOrderDetails()
also instead of making a function wrapping the function call
i have tried putting the function into a variable var editOrderDetails = function(){};
then "save" : editOrderDetails
i'm at a loss. any ideas would be appreciated ?
PS yes the dialog works correctly. if i place an alert in the callback function it executes when i click save.
<script type="text/javascript">
<!--
var orderID = '<?= $this->orderID; ?>';
var customerID = '<?= $this->customerID; ?>';
//################ PAGE FUNCTIONS ################
//MAKE AN AJAX CALL
function makeAjaxCall(ajaxUrl, data, functionSuccess, functionFailure){
$.ajax(
{
type: "GET",
url: ajaxUrl,
contentType: "application/json; charset=utf-8",
data: data,
dataType: "json",
success: functionSuccess,
error: functionFailure
});
}
//END MAKE AN AJAX CALL
//EDIT ORDER DETAILS
function editOrderDetails()
{
makeAjaxCall(
baseurl+'/orderoutbound/editorderdetails',
'orderID='+orderID+'&customerReference='+("#orderReference").val()+'&email='+$("#emailAddress").val(),
function(data){
if(data.success)
{
$("#editOrderDetailsErrorDiv").html(successDiv(data.generalMessage));
$(".customerReferenceSpan").html(data.order.customerReference);
$(".emailSpan").html(data.order.emailAddress);
}else{
$("#editOrderDetailsErrorDiv").html(errorDiv(data.generalMessage));
$("#emailAddressErrorDiv").html(data.errors.emailAddress);
}
},
function(data) {
$("#editOrderDetailsErrorDiv").html(errorDiv("There was an error.."));
}
);
}
//END EDIT ORDER DETAILS
//################ END PAGE FUNCTIONS ################
$(function() {
// EDIT ORDER DETAILS DIALOG
$("#editOrderDetailsDialog").dialog('destroy').dialog({
autoOpen: false,
title: 'Edit Order Details',
closeOnEscape: true,
width: 500,
height: 300,
buttons:{
"Save": function() { editOrderDetails(); },
"Cancel": function() { $(this).dialog("close"); }
}
});
// END EDIT ORDER DETAILS DIALOG
});
//-->
</script>

You are missing a $ in the call to makeAjaxCall.
'orderID='+orderID+'&customerReference='+("#orderReference").val()+'&email='+$("#emailAddress").val(),
Becomes:
'orderID='+orderID+'&customerReference='+$("#orderReference").val()+'&email='+$("#emailAddress").val(),

This http://jsfiddle.net/jQRyq/8/ works fine for me, could you post a bit more of your code for context? Specifically where the editOrderDetails functions is defined.

Related

jQuery $.ajax and jQuery UI dialog: Uncaught TypeError: Illegal invocation?

I am trying to send an AJAX request when I click a jQuery UI dialog Save button and this is how I am doing it:
$(function () {
var comment_dlg = $('#add_comment_dialog');
var quote_id = $('#comment_quote_id');
$('#order_push').click(function () {
quote_id.val($(this).data('id'));
comment_dlg.dialog('open');
});
comment_dlg.dialog({
title: "Write a comment",
autoOpen: false,
modal: true,
width: 600,
height: 300,
buttons: {
Cancel: function () {
$(this).dialog('close');
},
'Save': function () {
$.ajax({
url: Routing.generate('push_order_xml'),
method: 'GET',
data: { quote_id: quote_id },
cache: false
}).done(function (data, textStatus, jqXHR) {
if (data.success.length) {
alert(data.success);
} else {
alert('Something went wrong!');
}
});
}
}
});
});
But I am getting this error:
Uncaught TypeError: Illegal invocation
I am not sure where the issue is. I have checked jQuery UI Dialog and jQuery $.ajax docs several times and my code seems to be right.
Any ideas?
Ok, finally and thanks to this answer I figure it out where the problem was coming from.
First thing, because of this:
var quote_id = $('#comment_quote_id')
the value of quote_id was the whole HTML on not a value as I expected to be.
Second, I was assigning a value to $('#comment_quote_id') right here:
quote_id.val($(this).data('id'));
which is correct.
Third, again my mistake was to use quote_id here:
data: { quote_id: quote_id }
which is - again - wrong because is the whole HTML and not the value itself.
The solution, use quote_id.val() Ex:
data: { quote_id: quote_id.val() }
I can't use processData: false because I don't want to pass the HTML but the value.

Jquery-ui open dialog from js loop

I'm developing a web site with JQuery
I have encountered the following problem:
Going through an array in a loop, and every value is sent to a function that sends it to the server by Ajax.
On success a message is generated in JQuery- Dialog, in which buttons and button- functions are adjusted by the values returned from the server.
The problem is, that the JQuery-dialog is only triggered at the end of the loop, so I cannot tell which message refers to what value.
The loop func:
$('#List').find('option').map(function () {
semelO= $(this).val();
**getData**("Insert_hashala", "Inserthashala", false, "***setAlert***", false, "inserthasala", ["semelO", semelO], null, "RefershLendGrid", null);
});
The function signature:
function **getData**(procAlias, funcName, empytFields, ***onSuccessEvent***, isAsync, dataGroup, moreValues, onFailure, setDisplay, onFailureEvent)
The Ajax
jQuery.ajax({
type: "POST",
contentType: 'application/json',
dataType: "json",
url: "SvcSifria.asmx/" + funcName,
data: dataJsonString,
success: function (data) {
if (onSuccessEvent != undefined) eval(***onSuccessEvent*** + '(data)');
if (setDisplay != undefined) eval(setDisplay + '(data)');
},
async: isAsync
});
}
The Dialog function:
function ***setAlert***(data, error) {
myJson = jQuery.parseJSON(data.d);
text = data.d;
$("#dialog:ui-dialog").dialog("destroy");
$("#dialog-mess").dialog({
autoOpen: false,
modal: true, appendToBody: true,
buttons: [{
text: textButton,
id: "cancle",
click: function () {
$(this).dialog("close");
},text: textButton,
id: "ok",
click: function () {
getData("Insert_hashala", "Inserthashala", false, "setAlert", isAsync, "inserthasala", [returnValue, "true", "sumHashala", sumHashala, "semelOtek", semelOtek], null, "RefershLendGrid");
$(this).dialog("close");
}
}]
});
$("#ok").focus();
$("#dialog-mess").dialog("open");
}

Jquery delegate/live does not work

I have system that I'm modifying that uses jquery 1.5.1, which means .on doesn't exist.
I have a table and in this table I have multiple links listed in a row, and when the user clicks it opens a pop up window. I have the following code to create a pop up link.
<tr>
<td class="view_detail_label">
</td>
<td>
#Html.ActionLink(
training.Name.Name,
"AddSurvey",
new
{
employeeId = Model.Id,
trainingId = training.Id
},
new
{
#class = "addSurvey"
}
)
<div class="result" style="display:none;"></div>
</td>
</tr>
In the first function below I open a popup window and it works perfectly except when you close the popup you can not reopen it from the link again. To solve this I subscribed my event lively and used delegate and live function. But when tracking it from the console I cannot seen any output from the console statement : console.log($(this).next('.result'));.
$('.addSurvey').click(function () {
$.ajax({
url: this.href,
type: 'GET',
cache: false,
context: this,
success: function (result) {
$(this).next('.result').html(result).dialog({
autoOpen: true,
title: 'Anket',
width: 500,
height: 'auto',
modal: true
}); //end of dialog
//console.log($(this).next('.result'));
} //enf of success function
}); //end of ajax call
return false;
});
$('a.addSurvey').live( 'click', function () {
$.ajax({
url: this.href,
type: 'GET',
cache: false,
context: this,
success: function (result) {
$(this).next('.result').html(result).dialog({
autoOpen: true,
title: 'Anket',
width: 500,
height: 'auto',
modal: true
}); //end of dialog
console.log($(this).next('.result'));
} //enf of success function
}); //end of ajax call
}); //end of live
Why is this the case I used delegate method too and it does not work either. My delegate
function:
$(document).delegate(".addSurvey", "click", function () {
$.ajax({
url: this.href,
type: 'GET',
cache: false,
context: this,
success: function (result) {
$(this).next('.result').html(result).dialog({
autoOpen: true,
title: 'Anket',
width: 500,
height: 'auto',
modal: true
}); //end of dialog
console.log($(this).next('.result'));
} //enf of success function
}); //end of ajax call
});//end of delegate
Thank you for your help.
*EDIT 1 After clesing the popup window when i click it it duplicates the responses somehow it is clicked as twice and when i refresh the page and click on it and then close the responses triples. What might cause this awkward situation? *
**EDIT2 I solved the above problem by using close: function () { console.log("onClose"); $('.surveyTable').load('Home/DetailsSurvey', {id:#Model.Id}); }. By this I reload the the div table and can click on any pop up.
If you are using live then you do not need the first call. Try preventDefault() rather than return false.
$('a.addSurvey').live( 'click', function (e) {
e.preventDefault();
$.ajax({
url: this.href,
type: 'GET',
cache: false,
context: this,
success: function (result) {
$(this).next('.result').html(result).dialog({
autoOpen: true,
title: 'Anket',
width: 500,
height: 'auto',
modal: true
}); //end of dialog
console.log($(this).next('.result'));
} //enf of success function
}); //end of ajax call
}); //end of live
Change to this:
$(".addSurvey").die().live("click", function (event) { event.stopPropagation();
.......rest of code.
Hello everyone I solved my problem as follows: on close action of the popup I reload the page from the server and re render it therefor now it works like a charm. Thanks everyone for your time and attention.
$('a.addSurvey').live('click', function (e) {
var $this = $(this);
e.preventDefault();
$.ajax({
url: this.href,
type: 'GET',
cache: false,
context: this,
success: function (result) {
$(this).next('.result').html(result).dialog({
autoOpen: true,
title: 'Anket',
width: 500,
height: 'auto',
modal: true,
close: function () { console.log("onClose"); $('.surveyTable').load('Home/DetailsSurvey', {id:#Model.Id}); }
}); //end of dialog
console.log($(this).next('.result'));
}, //enf of success function
complete: function () {
console.log("Complete");
},
error: function () {
console.log("Error");
}
}); //end of ajax call
}); //end o
use .on instead of live. live is deprecated..
$('a.addSurvey').on( 'click', function () {
}
on() method is the new replacement for the bind(), live() and delegate() methods. Please use on().

$('#modalBusy').dialog('close') not working on properly with ajax

I am working with JQuery dialog which is opened before an ajax call and on returning from the ajax call the dialog('close') is executed. below statement opens up the busy dialog box as a banner (with no ok or cancel option):
$('.updateActionsTasks').live('click', function ()
{$('#modalBusy').html('<span>Busy...Please Wait.</span>').dialog({ dialogClass: 'no-close', resizable: false, width: 100, height: 100, modal: true, title: 'Busy' });
More code goes here ...
//Ajax function call goes here
However, the close method work correctly only once. Upon executing the click again, the dialog opens up but never gets closed. The line with tag 'COMM' executes but does not close the dialog from second time execution on wards.
function ActionWorklistItem(serviceUrl, worklistActionItems, actionName, ActiveTab) {
$.ajax({
type: "GET",
url: serviceUrl,
dataType: ($.browser.msie) ? "text" : "xml",
success: function (data) {
var xml;
if (typeof data == "string") {
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(data);
} else {
xml = data;
}
var xmlText = $(xml).text();
xmlObj = $.parseXML(xmlText);
if ($(xmlObj).find('IsSuccess').text() == 'true') {
$('#modalBusy').dialog('close'); //COMM: This always executes
__doPostBack($('.upWorklistCtrlID').val(), ActiveTab);
} else {
$('#modalBusy').dialog('close');
//Create error msg dialog }
},
error: function (xhr, ajaxOptions, thrownError) {
$('#modalBusy').dialog('close');
//Create error msg dialog
}
});
Instead of initializing the dialog each click, initialize it once and then just open it when the link is clicked:
$('#modalBusy').html('<span>Busy...Please Wait.</span>').dialog({ autoOpen : false, dialogClass: 'no-close', resizable: false, width: 100, height: 100, modal: true, title: 'Busy' });
$('.updateActionsTasks').live('click', function () {
$('#modalBusy').dialog('open');
The autoOpen : false option will make it so the dialog does not open when it's initialized.
Following line seems to have done the trick.
$('#modalBusy').dialog('destroy').remove();

Why does the Jquery dialog keep crashing on $(this)?

I am having a hell of a time trying to figure out why the code below crashes when the dialog is closed or cancelled. It errors on lines that use ($this) in the dialog button function.
For some reason if I hard code values into addTaskDialog.html(AddTaskForm); it works. I have even hardcoded the returned ajax form and it worked... This problem happens in all browsers.
$(function ()
{
/*
* Initializes AddTask Dialog (only needs to be done once!)
*/
var $dialog = $('<div></div>').dialog(
{
width: 580,
height: 410,
resizable: false,
modal: true,
autoOpen: false,
title: 'Basic Dialog',
buttons:
{
Cancel: function ()
{
$dialog.dialog('close');
},
'Create Task': function ()
{
}
},
close: function ()
{
$dialog.dialog('close');
}
});
/*
* Click handler for dialog
*/
$('#AddTask').click(function ()
{
/* Ajax request to load form into it */
$.ajax({
type: 'Get',
url: '/Planner/Planner/LoadAddTaskForm',
dataType: 'html',
success: function (AddTaskForm)
{
$dialog.html(AddTaskForm);
$dialog.dialog('open');
}
});
});
});
});
Ok I think I know what is going on. On your success callback you are referencing $(this) in AddTaskDialogOptions the problem is that the in this scope $(this) no longer refers to $("#AddTask") so you will need to set a variable to keep a reference to $(this) like so:
var that;
$('#AddTask').click(function ()
{
that = $(this);
/* Ajax request to load form into it */
$.ajax({
type: 'Get',
url: '/Planner/Planner/LoadAddTaskForm',
dataType: 'html',
success: function (AddTaskForm)
{
var addTaskDialog = $('<div></div>');
addTaskDialog.dialog(AddTaskDialogOptions);
addTaskDialog.html(AddTaskForm);
addTaskDialog.dialog('open');
}
});
});
var AddTaskDialogOptions = {
width: 580,
height: 410,
resizable: false,
modal: true,
autoOpen: false,
title: 'Basic Dialog',
buttons:
{
Cancel: function ()
{
that.dialog('close');
},
'Create Task': function ()
{
}
},
close: function ()
{
that.dialog('destroy').remove();
}
}
I figured it out. I'm not sure where I got this code, but it was causing the problems, so I took it out and it all works fine.
close: function ()
{
$dialog.dialog('close');
}

Categories

Resources