简体   繁体   中英

Ajax call a php file in Opencart 2

I want to ajax call a php file which i created system/helper which calls for a method of a model which adds a coupon in the database. the php file contains the following.

<?php
function coupon_for_acumba() {
            $this->load->model('total/coupon');

            echo $this->model_total_coupon->coupon_test();
        }

I created a js file which makes the ajax call when a form is submitted. The script in the file is the following

let acumbaForm = document.querySelector('#form-acm_28955');
                acumbaForm.addEventListener('submit', function () {
                    setTimeout(function () {if (document.querySelector('.succes-alert-form-acm')) {
                        $.ajax({

                                url : '/system/helper/acumba.php',
                                type : 'POST',
                                success : function (result) {
                                console.log (result); // Here, you need to use response by PHP file.
                },
                    error : function () {
                        console.log ('error');
            }

                    });
                }}, 2000)
                    
                })

finally i called this js file in catalog/controller/common/header.php with $this->document->addScript('catalog/view/javascript/test1.js');

The problem is that everytime i submit the form i get an error message from the ajax call. Can you tell me what i am doing wrong please?

OpenCart doesn't allow call PHP files directly from system folder (check .htaccess file in system folder). Try to open https://yoursite/system/helper/acumba.php, You'll get 403 Forbidden. You have to use a route to call a method.

url : '/system/helper/acumba.php', // wrong

You have to modify /catalog/controller/extension/total/coupon.php and put in your method, then call this way in your JS file.

url : 'index.php?route=extension/total/coupon/coupon_for_acumba',

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM