Проблемы с ajax запросом

Автор Vlad mazur, 10 апреля 2015, 14:07:57

« назад - далее »

Vlad mazur

Создаю свой модуль. Почему-то получаю пустой ответ аякс запроса.
Уже кучу способов перепробовал. Может, кто-то подскажет в чем проблема.

main.js

jQuery(document).ready(function(){
    $('#cheaper form').submit(function(){
        var url = $("#cheaper .url").val();
        var email = $("#cheaper .email").val();
        $.ajax({
            url: baseDir+'modules/cheaperproduct/cheaperproduct.php',
            method:"post",
            data:{
                ajax : true,
                action : 'UpdateList '
            },
            success: function(data){
                alert(data);
            }
        })
        return false;
    })
})


а в cheaperproduct.php есть метод

public function ajaxProcessUpdateList(){
    echo "string";
    }

mistral


mAgency

Включите режим отладки (или вывод в консоль ff) и проверьте вызов cheaperproduct.php и передачу данных в cheaper form.
Интернет-магазин под ключ.
Какой выбрать движок для интернет магазина ?
Какой движок лучше ?
Magento или Prestashop ?
Решение всех Ваших вопросов в создании Интернет-магазина.

Vlad mazur

#3
Цитата: mAgency от 10 апреля 2015, 15:08:03
Включите режим отладки (или вывод в консоль ff) и проверьте вызов cheaperproduct.php и передачу данных в cheaper form.

Данные передаются. Но пустой ответ.
Возможно, какой-то параметр нужно определить в  конструкторе.

вот весь код cheaperpoduct.php

<?php

if (!defined('_PS_VERSION_'))
exit;

class
CheaperProduct extends Module
{

public function __construct()
{

$this->name = 'CheaperProduct';
$this->tab = 'other';
$this->version = '0.0.1';
$this->author = 'Влад Мазур';
$this->need_instance = 0;
$this->ps_versions_compliancy = array('min' => '1.6', 'max' => _PS_VERSION_);
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('CheaperProduct');
$this->description = $this->l('');
$this->confirmUninstall = $this->l('Are you sure you want to uninstall?');

}

public function install()
{
$sql = "CREATE TABLE  "._DB_PREFIX_.$this->name."(
`id_email` int(5) NOT NULL AUTO_INCREMENT,
`email` varchar(30),
PRIMARY KEY (id_email))
ENGINE ="
._MYSQL_ENGINE_." default CHARSET=utf8";
if (Shop::isFeatureActive())
Shop::setContext(Shop::CONTEXT_ALL);

if (!parent::install()
   || !Db::getInstance()->Execute($sql)
   || !$this->registerHook ('displayHeader')
   || !$this->registerHook ('DisplayShowForm')
   || !$this->registerHook ('DisplayGetPost')
   || !$this->registerHook ('AjaxUpdateList')
   || !Configuration::updateValue('MYMODULE_NAME','')
)

   return false;

return true;
}

public function uninstall()
{
$sql = "DROP TABLE "._DB_PREFIX_.$this->name;
   if (!parent::uninstall()
    || !Db::getInstance()->Execute($sql)
    || !$this->unregisterHook ('displayHeader')
    || !$this->unregisterHook ('DisplayShowForm')
    || !$this->unregisterHook ('DisplayGetPost')
    || !$this->unregisterHook ('AjaxUpdateList')
    || !Configuration::deleteByName('MYMODULE_NAME')
   )
    return false;
   return true;
}


public function getContent()
{
   $output = null;
   if (Tools::isSubmit('submit'.$this->name))
   {
   
       $my_module_name = strval(Tools::getValue('MYMODULE_NAME'));
       if (!$my_module_name
         || empty(
$my_module_name)
         || !Validate::isGenericName($my_module_name))
           $output .= $this->displayError($this->l('Invalid Configuration value'));
       else
       {
        $insert = "INSERT INTO "._DB_PREFIX_.$this->name."(`email`) VALUES('".$my_module_name."')";
           Configuration::updateValue('MYMODULE_NAME', $my_module_name);
           $output .= $this->displayConfirmation($this->l('Settings updated'));
           if(!Db::getInstance()->Execute($insert))die;
       }
   }
  // $this->_html .= $this->display (__FILE__, 'views/templates/admin/list_settings.tpl');
   return $this->displayForm().$this->displayList();
}

public function displayForm()
{
   // Get default language
   $default_lang = (int)Configuration::get('PS_LANG_DEFAULT');
   
   // Init Fields form array
   $fields_form[0]['form'] = array(
       'legend' => array(
           'title' => $this->l('Settings'),
       ),
       'input' => array(
           array(
               'type' => 'text',
               'label' => $this->l('Add email'),
               'name' => 'MYMODULE_NAME',
               'size' => 20,
               'required' => true
           )
       ),
       'submit' => array(
           'title' => $this->l('Save'),
           'class' => 'button'
       )
   );
   
   $helper = new HelperForm();
   
   // Module, token and currentIndex
   $helper->module = $this;
   $helper->name_controller = $this->name;
   $helper->token = Tools::getAdminTokenLite('AdminModules');
   $helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name;
   
   // Language
   $helper->default_form_language = $default_lang;
   $helper->allow_employee_form_lang = $default_lang;
   
   // Title and toolbar
   $helper->title = $this->displayName;
   $helper->show_toolbar = true;        // false -> remove toolbar
   $helper->toolbar_scroll = true;      // yes - > Toolbar is always visible on the top of the screen.
   $helper->submit_action = 'submit'.$this->name;
   $helper->toolbar_btn = array(
       'save' =>
       array(
           'desc' => $this->l('Save'),
           'href' => AdminController::$currentIndex.'&configure='.$this->name.'&save'.$this->name.
           '&token='.Tools::getAdminTokenLite('AdminModules'),
       ),
       'back' => array(
           'href' => AdminController::$currentIndex.'&token='.Tools::getAdminTokenLite('AdminModules'),
           'desc' => $this->l('Back to list')
       )
   );
   
   // Load current value
   $helper->fields_value['MYMODULE_NAME'] = Configuration::get('MYMODULE_NAME');
 
   return $helper->generateForm($fields_form);
}

public function displayList()
{

$sql = "SELECT * FROM "._DB_PREFIX_.$this->name;
$results = Db::getInstance()->ExecuteS($sql);
$fields_list = array(
       'id_email' => array(
           'title' => $this->l('id_email'),
           'width' => 140,
           'type' => 'int',
       ),
       'email' => array(
           'title' => $this->l('email'),
           'width' => 140,
           'type' => 'text',
       ),
 
);
       
   $helper = new HelperList();
   
   $helper->shopLinkType = '';
   
   $helper->simple_header = true;
   
   /*
     $helper->actions = array('edit', 'delete');

   $helper->bulk_actions = array(
    'delete' => array(
        'text' => $this->l ('Delete selected'),
        'confirm' => $this->l ('Delete selected items?'),
      )
    );
   */
   $helper->identifier = 'id_email';
   $helper->show_toolbar = true;
   $helper->title = 'HelperList';
   $helper->table =_DB_PREFIX_.$this->name;

   $helper->token = Tools::getAdminTokenLite('AdminModules');
   $helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name;
   return $helper->generateList($results,$fields_list);
}

   public function
hookDisplayHeader()
   {
   
//print_r($this->_path.'views/style.css');die;
   
Tools::addCSS($this->_path.'css/style.css', 'all');
   
Tools::addjs($this->_path.'js/main.js', 'all');
   }

   public function
hookDisplayShowForm(){
   
return $this->display (__FILE__, 'views/product_data.tpl');
   }

   public function
ajaxProcessUpdateList(){
   
echo "string";
   }
}


Vlad mazur

Цитата: mistral от 10 апреля 2015, 14:43:36
Это читал?
http://doc.prestashop.com/display/PS16/Using+jQuery+and+Ajax

конечно.
Пробовал и в data отправлять метод, а метод переименовывал по примеру.

DarinSr

А контроллер какой в модуле?

Vlad mazur

Цитата: DarinSr от 10 апреля 2015, 15:31:18
А контроллер какой в модуле?

Я читал, что контроллер необязателен

DarinSr

Без контроллера,
1. Добавить Ajax Handler в класс модуля. Нужно чтобы в названии метода был перфикс ajaxProcess.
public function ajaxProcessMyMethod(){
     ....
}


2. Добавить в шаблон
<input type="text" id="id_data" value="My data"/>
<button id="cheaper">Get Ajax Data</button>


3. Добавить js функцию, можно в отдельный файл

$(function() {
    $('#cheaper').click(function() {
        var query = $.ajax({
            type: 'POST',
            url: baseUri+'module/mymodyle/mymodule.php',
            data: 'method=myMethod&id_data=' + $('#id_data').val(),
            dataType: 'json',
            success: function(json) {
                console.log(json);
                alert(json.result);
            }
        });
    });
});

Vlad mazur

Цитата: DarinSr от 10 апреля 2015, 16:14:20
Без контроллера,
1. Добавить Ajax Handler в класс модуля. Нужно чтобы в названии метода был перфикс ajaxProcess.
public function ajaxProcessMyMethod(){
     ....
}


2. Добавить в шаблон
<input type="text" id="id_data" value="My data"/>
<button id="cheaper">Get Ajax Data</button>


3. Добавить js функцию, можно в отдельный файл

$(function() {
    $('#cheaper').click(function() {
        var query = $.ajax({
            type: 'POST',
            url: baseUri+'module/mymodyle/mymodule.php',
            data: 'method=myMethod&id_data=' + $('#id_data').val(),
            dataType: 'json',
            success: function(json) {
                console.log(json);
                alert(json.result);
            }
        });
    });
});


получаю null  :( :( :(

PrestaMan

Если не хотите создавать контроллер, то создайте файл ajax.php
// /modules/mymodule/ajax.php
//
// вот эти 2 строчки обязательны
require_once(dirname(__FILE__).'../../../config/config.inc.php');
require_once(dirname(__FILE__).'../../../init.php');
// end
.....

и замените
url: baseUri+'module/mymodyle/ajax.php',
Эксперт Prestashop - решения всех проблем, написание модулей, создание тем для интернет-магазинов под Prestashop.
Эксперт Magento - создам сайт на Magento, программирование кастомных модулей для Magento, кастомизация тем Magento.
Лучшие цены!!!

beagler