DigM DigM - 9 days ago 9
PHP Question

Pass parameter to PHP function through AJAX

I have an ajax call on a WordPress website which looks like the following:

$('.stm-ajax-checkbox-button .button, .stm-ajax-checkbox-instant .stm-option-label input').click(function(e){

if($(this)[0].className == 'button') {
e.preventDefault();
}

var sold = '';

if( $('.soldlistings').length ) {
sold = '(true)';
}

$.ajax({
url: ajaxurl,
dataType: 'json',
context: this,
data: $(this).closest('form').serialize() + '&action=stm_ajax_filter',
beforeSend: function () {
$(this).closest('.stm-accordion-content-wrapper .stm-accordion-inner').addClass('loading');
$('.stm-ajax-row').addClass('stm-loading');
$('.classic-filter-row .filter-sidebar .select2-container--default .select2-selection--single .select2-selection__arrow b').addClass('stm-preloader');
},
success: function (data) {
$(this).closest('.stm-accordion-content-wrapper .stm-accordion-inner').removeClass('loading');
$('.stm-ajax-row').removeClass('stm-loading');
$('.classic-filter-row .filter-sidebar .select2-container--default .select2-selection--single .select2-selection__arrow b').removeClass('stm-preloader');
$('.classic-filter-row .filter-sidebar select').prop("disabled", false);

if(typeof data.html != 'undefined') {
$('.stm-ajax-row .stm-isotope-sorting:not(.stm-isotope-sorting-featured-top)').html(data.html);

var sortVal = $('.stm-select-sorting select').select2('val');

$('.stm-ajax-row').removeClass('stm-loading');
}

stm_after_ajax_same_actions(data, sortVal);
}
})
});


This then links to a PHP function (I won't paste the whole code) like so:

function stm_ajax_filter() {
}


I want to add a parameter to this function which I will then use to help work out where the Ajax call was used. To do this I have added a parameter to my PHP function. How do I set this parameter in the Ajax call?

Answer

Why don't you add another parameter to the AJAX data property?

data: $(this).closest('form').serialize() + '&origin=mainPage&action=stm_ajax_filter',

And then in PHP you can just retrieve the 'origin' key.

$ajaxOrigin = $_GET["origin"];

// and then pass that variable to your function as an argument
stm_ajax_filter($ajaxOrigin);