Magento Asked on December 9, 2021
I am finding a tutorial for AJAX in magento 2. How can I use javascript to trigger a PHP function in Magento 2. In WordPress, we have this:
https://codex.wordpress.org/AJAX_in_Plugins
I don’t know if it is the same for Magento or in Magento world, we use different thing.
I have also written a small module for you, this is what is does:
Display a button click me on every page of the site. When clicking the button, a post ajax call is performed, the response is a simple json message
No gimmick in the module, if you need get
rather than post
, I am sure you'd be finding your way but if not, please let me know
the url is: https://bitbucket.org/magstaging/ajaxcall/src
UPDATE:
In this script below,
<script type="text/x-magento-init">
{
"*": {
"Mbs_AjaxCall/js/clickme": {
"ajaxUrl": "<?php echo $block->getUrl('mbsajaxdummy'); ?>"
}
}
}
</script>
the json
{
"ajaxUrl": "<?php echo $block->getUrl('mbsajaxdummy'); ?>"
}
is the config for the javascript file. Magento parsing picks up this json and makes it available to the clickme.js javascript file
hence, the javascript file:
define([
"jquery"
], function ($) {
'use strict';
return function(config, element) {
console.log('config', config); // this will show you what is in the console
Answered by Herve Tribouilloy on December 9, 2021
I created a module that let’s you easily implement custom ajax requests in Magento 2. You might find the module useful or you can use the code to develop your own.
Answered by paj on December 9, 2021
In Magento 2, your can install a module and assign it a URL route where you can send ajax call.
In this module controller execute() function you will put your php code. at end of this function put echo "somthing" as response.
Here is an example plugin which you can install in magento2. https://github.com/sanaullahAhmad/Magento2_cat_subcat_ajax_select_dropdowns
check this file for rout endpoint
Pulsestorm/HelloWorldMVVM/etc/frontend/routes.xml
it is "hello_mvvm"
If you wan to send ajax call to Pulsestorm/HelloWorldMVVM/Controller/Hello/World.php
you should put this in URL field of your ajax call
"http:example.com/index.php/hello_mvvm/hello/world" This will lead to
public function execute(){
//your code here
echo "some response here";
}
Answered by Sanaullah Ahmad on December 9, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP