Scot Ranney • November 09, 2024
The most simple way in existence to send data to an AJAX page or back end (such as json.mvc via module) using jquery.
Step 1: Assign a CSS ID to the thing that is getting clicked on.
CSS ID
<div id="clickme" data-firstname="Scot" data-city="Bellingham"></div> <div id="results"></div>
Step 2: We track the click via the CSS ID and set up data vars based on the data attributes.
The AJAX URL can be a page template in the store. We often make an AJAX handler page and give it the code AJAX.
AJAX
If using a module to get data and such the better way might be to use the json module feature and send the click to json.mvc - this probably handles bot clicks better although it's more complicated and can't be updated without updating the module.
json.mvc
The html(result) is nothing more than whatever the AJAX page or module calls returns. Simple as that.
html(result)
$("#clickme").on('click', function(){ var $el = $(this); var firstname = $el.data('name'); var city = $el.data('city'); $.ajax({ type:'POST', url:'&mvt:ajax_page_uri;', data:{'firstname':firstname,'city':city}, success:function(result){ $('#results').html(result); } }); });
mvkb_ajax