jQuery newbie question here... I have a jQuery dialog that displays a warning with a "OK" or "Cancel" and based on what they click the result needs to then execute the server side ASP onClick event.
I've attempted to write it along these lines:
"OK": function () {
$(this).dialog("close");
return true;
},
Cancel: function () {
$(this).dialog("close");
return false;
But it never posts back to the asp server side method.
Am I off base in what I am trying to accomplish here, and is there standard 'best practice' type of way of implementing this type of functionality?
You have to call __doPostBack() method with appropriate eventTarget and eventArgument to call its sever click handler.
"OK": function () {
$(this).dialog("close");
__doPostBack('serverElementId', 'arguments');
}
You can take a look at the below link to understand how ASP.Net postback mechanism works.
http://wiki.asp.net/page.aspx/1082/dopostback-function/
Assuming you want to execute the POST on "OK", you'd need to add something like:
"OK": function () {
$.post('someurl.asp', {data}, function() {
// what to do after the post
}
$(this).dialog("close");
return true;
}
As it currently stands, your code just closes the dialog either way.
I don't have experience with asp.net but you can use an AJAX request to post data to your server-side script:
"OK": function () {
$(this).dialog("close");
$.ajax({
url : 'myscript.asp',
type : 'get',
dataType : 'json',
data : { state : 'OK' },
success : function (serverResponse) {
//you can now access the serverResponse
},
error : (jqXHR, errorText, errorThrown) {
//always make sure to handle your errors
}
});
return true;
},
Cancel: function () {
$(this).dialog("close");
$.ajax({
url : 'myscript.asp',
type : 'get',
dataType : 'json',
data : { state : 'Cancel' },
success : function (serverResponse) {
//you can now access the serverResponse
},
error : (jqXHR, errorText, errorThrown) {
//always make sure to handle your errors
}
});
return false;
}
Docs for $.ajax(): http://api.jquery.com/jquery.ajax
Related
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.
I'm trying to load different templates through $.ajax based on what buttons a user clicks. I know how to do it with one template file, but can't seem to find a way to adjust the code to load different template based on click (without repeating the code).
Here's the relevant part of the ajax call:
var $this = $('#my-data');
$('#button-foo').click(function() {
$.ajax({
url: myAjax.ajax_url,
data: {
action: 'my_ajax_action'
},
cache: true,
beforeSend: function(){
$this.empty();
$this.addClass('loading');
},
complete: function(){
$this.removeClass('loading');
},
success: function(data) {
$this.append(data);
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
});
And here's my Wordpress function:
function my_ajax_action() {
include(locate_template( 'part-template-foo.php' ));
die();
}
add_action('wp_ajax_nopriv_my_ajax_action', 'my_ajax_action');
add_action('wp_ajax_my_ajax_action', 'my_ajax_action');
Now what I need would be to include 4 different templates (part-template-bar.php, part-template-foobar.php, etc) based on user click. Something like:
function my_ajax_action() {
if ($_REQUEST['template'] == 'foo') {
include(locate_template( 'part-foo.php' ));
die();
}
if ($_REQUEST['template'] == 'bar') {
include(locate_template( 'part-bar.php' ));
die();
}
...
}
Any hint on how could I do this without having to repeat the js code and wp function four times? Thank you.
I have the following jQuery:
$.ajax('/contacts_imported', {
dataType : 'json',
data : {
email : cfg.email
},
success : function(data) {
if (data[0].processed) {
alert('Processed is TRUE!');
} else {
alert('Not yet Processed');
}
}
});
What I'm trying to do is, have this ajax request run every second until processed is equal to True. Once True, run a separate functions and kill the timer/loop.
How can I best handle this in an elegant way?
Do NOT use an interval, as your AJAX request may take longer than 1 second every now and then. So wrap your ajax in a function and call it like this:
(function makeRequest() {
$.ajax('/contacts_imported', {
dataType : 'json',
data : {
email : cfg.email
},
success : function(data) {
if (data[0].processed) {
alert('Processed is TRUE!');
} else {
setTimeout(makeRequest, 800);
}
}
});
}());
I'm trying to return true or false to a function depending on the response of an AJAX function inside of it but I'm not sure how should I do it.
(function($) {
$('#example').ajaxForm({
beforeSubmit : function(arr, $form, options) {
var jsonStuff = JSON.stringify({ stuff: 'test' });
$.post('/echo/json/', { json: jsonStuff }, function(resp) {
if (resp.stuff !== $('#test').val()) {
// Cancel form submittion
alert('Need to type "test"');
return false; // This doesn't work
}
}, 'json');
},
success : function() {
alert('Form sent!');
}
});
})(jQuery);
I made a fiddle to illustrate this better:
http://jsfiddle.net/vengiss/3W5qe/
I'm using jQuery and the Malsup's Ajax Form plugin but I believe this behavior is independent of the plugin, I just need to return false to the beforeSubmit function depending on the POST request so the form doesn't get submitted every time. Could anyone point me in the right direction?
Thanks in advance!
This is not possible to do when dealing with async functions. The function which calls post will return immediately while the ajax call back will return at some point in the future. It's not possible to return a future result from the present.
Instead what you need to do is pass a callback to the original function. This function will eventually be called with the result of the ajax call
var makePostCall = function(callback) {
$.post('/echo/json/', { json: jsonStuff }, function(resp) {
if (resp.stuff !== $('#test').val()) {
// Cancel form submittion
alert('Need to type "test"');
callback(false);
} else {
callback(true);
}}, 'json');
};
Then switch the code which expected a prompt response from makePostCall to using a callback instead.
// Synchronous version
if (makePostCall()) {
// True code
} else {
// false code
}
// Async version
makePostCall(function (result) {
if (result) {
// True code
} else {
// False code
}
});
you can put async:false parameter to ajax request then you can control future responce and send back the result to parent. see following main lines enclosed within ***
add: function (e, data) {
//before upload file check server has that file already uploaded
***var flag=false;***
$.ajax(
{
type: "POST",
dataType:'json',
url:"xyz.jsp",
***async:false,***
data:{
filename : upload_filename,
docname : upload_docname,
userid : upload_userid,
},
success:function(data)
{
***flag=true;***
},
error:function(request,errorType,errorMessage)
{
alert ('error - '+errorType+'with message - '+errorMessage);
}
});
***return flag;***
}
Okay, I do use firebug to determine when a function is not defined in Dev. What I would like to do in production is show a modal window saying an error has been received which would then redirect them to another page upon click. Not so easy.
Please understand that this function does work and the component that is called works. I am going to misspell the function call on purpose to demonstrate the error I am not receiving thru the jquery ajax function.
I am using .ajaxSetup to set up the default options for several ajax functions that will be running asynch:
$.ajaxSetup({
type: "POST",
dataType: "json",
url: "DMF.cfc",
data: {
qID: 1,
returnFormat: "json"
},
beforeSend: function() {
$('#loadingmessage').fadeIn(); // show the loading message.
},
complete: function() {
$('#loadingmessage').fadeOut(); // show the loading message.
}
}); //end AjaxSetup
The actual ajax call is:
$.ajax({
data: {
method: 'getCurrentIssues'
},
success: function(response) {
nsNewDebtshowDebtIssues(response);
},//end success function
error: function(jqXHR, exception) {
alert("Error running nsNewDebt.showDebtIssues");
}
}) //end getCurrentIssues Ajax Call
The error I forced is that the method run in the success function should actually be nsNewDebt.showDebtIssues. Firebug correctly displays in console the error nsNewDebtshowDebtIssues is not defined but the actual error message for the ajax call does not run, so if an enduser was running the page it would appear the page was hung.
So, In summary I want to know how to track when such an error occurs, preferrable to place in the error section of the .ajaxSsetup but if neccessary in each .ajax call.
It is not an ajax error, so you cannot handle it from the ajaxError method.
You should do a try/catch in the success method.
success: function(response) {
try {
nsNewDebtshowDebtIssues(response);
} catch (ex) {
//exception occured
//alert("Error running nsNewDebt.showDebtIssues");
alert( ex.message + '\n\tin file : ' + ex.fileName + '\n\t at line : ' + ex.lineNumber);
}
}
Before making the call, you can do:
if(typeof nsNewDebtshowDebtIssues == 'function') {
// .. call it ..
}
Well, the error actually occurs after the AJAX call has succeeded (since it comes from your success handler), so the error handler indeed won't be called.
If you want to use the same handler for actual AJAX request errors and for further errors originating from your success handler, you can define a named function and use it both as your error handler and from a try/catch block in your success handler:
function handleError(jqXHR, status, exception)
{
alert("Error running request.");
// Or print something from 'jqXHR', 'status' and 'exception'...
}
$.ajax({
data: {
method: "getCurrentIssues"
},
success: function(response, status, jqXHR) {
try {
nsNewDebtshowDebtIssues(response);
} catch (x) {
handleError(jqXHR, status, x);
}
},
error: handleError
});