Jump to content

Faire un appel ajax depuis une url spécifique développement modules prestashop


Recommended Posts

Bonjour,

 

Je suis en train de créer un module au niveau du backoffice qui permet d'ajouter des champs supplémentaires sur la section catalogue > produit

Cependant, je ne sais pas comment générer la bonne URL qui mènent vers le controller à mettre dans le script ajax 

    public function hookDisplayBackOfficeHeader($params)
    {

   $ajax_link = $this->context->link->getAdminLink('AdminModules') . '&configure=' . $this->name . '&tab_module=' . $this->tab . '&module_name=' . $this->name . '&controller=customproduct';


    Media::addJsDef(array(
        "adminAjaxLink" => $ajax_link,
    ));

      $this->context->controller->addJS($this->_path . 'views/js/ajax.js');

    }

 

La partie controlleur: 

customproduct/controllers/admin/CustomproductController.php

 

<?php

class CustomProductController extends ModuleAdminController
{
    public function __construct()
    {
        $this->bootstrap = true;
        parent::__construct();
    }

    public function initContent()
    {
        parent::initContent();
    }

    public function ajaxProcessSaveCustomProduct()
    {
        // Validate and sanitize data
        $templateData = Tools::getValue('template_data');
        // Validate data
        if (empty($productId)) {
            $this->errors[] = $this->l('Product ID is missing.');
        } elseif (empty($typeImage)) {
            $this->errors[] = $this->l('Image type is missing.');
        } elseif (empty($typeGalerie)) {
            $this->errors[] = $this->l('Gallery type is missing.');
        } elseif (empty($templateProductName)) {
            $this->errors[] = $this->l('Template product name is missing.');
        }

        // Save data if no errors
        if (empty($this->errors)) {
            // Save product data (implement your logic here)
            // Update database or perform any other necessary actions

    // Save data to ps_customtemplate table
    $sql = "INSERT INTO `ps_customtemplate` (`id_product`, `type_image`, `type_galerie`, `template_product_name`)
            VALUES ('$productId', '$typeImage', '$templateProductName', '$templateProductName')";
            $idProduct = (int) $this->context->cookie->id_product;

     $sql = 'INSERT INTO ' . _DB_PREFIX_ . 'customtemplate (id_product, type_image, type_galerie, template_product_name) VALUES (' . $idProduct . ', ' . ($templateData['type_image']) . ', "' . (implode(',', $templateData['type_galerie'])) . '", "' . pSQL($templateData['template_product_name']) . '")';

    if (Db::getInstance()->execute($sql)) {
        $this->ajaxDie(json_encode([
            'success' => true,
        ]));
    } else {
        $this->errors[] = $this->l('An error occurred while saving the template.');
        $this->ajaxDie(json_encode([
            'success' => false,
            'errors' => $this->errors,
        ]));
        }
    }
}

Voici le fichier ajax: 

$(document).ready(function () {
    $('#save_template').on('click', function () {
        var templateData = {
            id_product :$('#id_product').val(),
            type_image: $('#type_image').val(),
            type_galerie: [],

            template_product_name: $('#template_product_name').val()
        };

        $('input[name="custom_template_data[type_galerie][]"]:checked').each(function () {
            templateData.type_galerie.push($(this).val());
        });
        $.ajax({
            async: true,
            dataType : "json",
            type: 'POST',
            url: adminAjaxlink,
            data: {
                template_data: templateData
            },
            success: function (response) {
                // Traiter la réponse si nécessaire
                console.log(response);
            },
        });
    });
});

 

Quand je clique sur le bouton #save_template j'ai le message d'erreur 404 page introuvable sur la console.

 

Si vous pouviez me proposer une solution 

Merci.

 

Cordialement.

Link to comment
Share on other sites

  • 2 weeks later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...