Magento 2 : Modal Popup using Ajax
-
11-12-2020 - |
Question
How to use model popup using ajax? Can any one help for this. Here below my code. How can i apply in this code model popup? And also post data get in popup. How it possible?
app/code/Vendor/Complany/view/frontend/web/js/example.js
define([
'jquery',
'Magento_Ui/js/modal/modal'
], function ($,example,modal) {
return {
exampleData:function(ajaxurl){
$("#example").click(function(e){
e.preventDefault();
$.ajax({
url:ajaxurl,
type:'POST',
showLoader: true,
dataType:'json',
success:function(){
alert('test');
}
});
});
}
}
}
);
app/cpde/Vendor/Company/view/frontend/templates/example/example.phtml
<div id="events_popup" style="display: none;" class="events_popup">
<script>
require(
['jquery','Vendor_Company/js/example'],
function($,example){
var ajaxurl = '<?php echo //My URL using block function; ?>';
example.exampleData(ajaxurl);
}
);
</script>
Solution
define([
'jquery',
'Magento_Ui/js/modal/modal'
], function ($,example,modal) {
var options = {
type: 'popup',
responsive: true,
innerScroll: true,
buttons: [{
text: $.mage.__('Continue'),
class: 'primary action submit btn btn-default',
click: function () {
this.closeModal();
}
}]
};
return {
exampleData:function(ajaxurl){
$("#example").click(function(e) {
e.preventDefault();
var $form = $('#form-validate');
var data = $('#form-validate').serialize();
if(!$form.valid()) return false;
$.ajax({
url:ajaxurl,
type:'POST',
showLoader: true,
dataType:'json',
data: data,
complete: function(data) {
$('#email_address').val("");
$("#events_popup").html('Thanks.').modal(options).modal('openModal');
},
error: function (xhr, status, errorThrown) {
console.log('Error happens. Try again.');
}
});
});
}
}
}
);
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange