Reputation: 5591
So, I have the following js:
function RHP_AJAX(a, b, c)
{
jQuery.ajax({
type : 'POST',
url : custom.ajax_url,
data : { 'action': a , id: b},
success : function(data){
c;
return false;
}
});
}
Then another var:
jQuery(document).on( 'click', '.show', function(e) {
var c = jQuery('.extra').html(data);
RHP_AJAX('ajax', id, c);
});
The issue is .html(data);
as data
is not yet defined. I know the issue but I am not sure how to describe it (I am sure you guys will understand when you see the code).
How do I address the issue?
Upvotes: 0
Views: 88
Reputation: 318162
The right thing to do here would be to just pass back the Deferred from $.ajax
function RHP_AJAX(a, b) {
return jQuery.ajax({
type : 'POST',
url : custom.ajax_url,
data : { 'action': a , id: b}
});
});
jQuery(document).on( 'click', '.show', function(e) {
RHP_AJAX('ajax', id).then(function(data) {
jQuery('.extra').html(data);
});
});
Upvotes: 2
Reputation: 19709
You are looking for a function parameter:
function RHP_AJAX(a, b, c){
jQuery.ajax({
type : 'POST',
url : custom.ajax_url,
data : { 'action': a , id: b},
success : c
});
}
and you can use it like this:
jQuery(document).on( 'click', '.show', function(e) {
RHP_AJAX('ajax', id, function(data){
jQuery('.extra').html(data);
});
});
Upvotes: 2
Reputation: 520
It seems to me your code should be restructured like so:
jQuery(document).on('click', '.show', function() {
RHP_AJAX('ajax', id);
});
function RHP_AJAX(a, b)
{
jQuery.ajax({
type : 'POST',
url : custom.ajax_url,
data : { 'action': a , id: b },
success : function(data){
jQuery('.extra').html(data);
}
});
}
Upvotes: 1
Reputation: 1183
Try passing the function as a callback function:
function RHP_AJAX(a, b, callback)
{
jQuery.ajax({
type : 'POST',
url : custom.ajax_url,
data : { 'action': a , id: b},
success : function(data){
callback(data);
return false;
}
});
}
jQuery(document).on( 'click', '.show', function(e) {
var callFunction = function(data) { jQuery('.extra').html(data);}
RHP_AJAX('ajax', id, callFunction);
});
Upvotes: 1
Reputation: 13620
I'm assuming that when you click on the .show
element, you want to query the server and then inject that response into the .extra
element. If so, here's my solution:
jQuery(document).on( 'click', '.show', function(e) {
jQuery.ajax({
type: "POST",
url: custom.ajax_url,
data: { "action": a, id: b },
success: function (data) {
jQuery(".extra").html(data);
}
});
});
It's just an issue of asynchronous programming. Have a read here: https://www.google.com/#safe=active&q=javascript%2Basynchronous%2Bprogramming
Upvotes: 1