Home  >  Q&A  >  body text

Opencart 2: Call php files using Ajax

I want to ajax call a system/helper php file I created that calls a method on the model that adds the coupon in the database. php file contains the following content.

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

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

I created a js file that makes an ajax call when the form is submitted. The script in the file is as follows

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 used $this->document->addScript('catalog/view/javascript/test1.js'); to call this js file in catalog/controller/common/header.php;

The problem is that every time I submit the form, I get an error message from the ajax call. Can you tell me what I'm doing wrong?

P粉153503989P粉153503989225 days ago426

reply all(1)I'll reply

  • P粉299174094

    P粉2991740942024-04-01 13:11:46

    OpenCart does not allow calling PHP files directly from the system folder (check the .htaccess file in the system folder). Try opening https://yoursite/system/helper/acumba.php and you will get 403 Forbidden. You have to use routing to call the method.

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

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

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

    reply
    0
  • Cancelreply