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