Jump to content

How to handle ajax request from custom page?


Recommended Posts

I am developing a module for prestashop 1.7 and trying to make an ajax request from the form of my page to backend, it does not really matter for me if it would be to the main php file of the module or a controller of this page. Just I cant get it done whatever I am trying.

I have tried methods described here:

None of them seem to work. I am not a newbie in web development, so I am pretty sure I have followed the instuctions above with proper care, I just can't get it working on this platform. If someone could provide me with a comprehensive way of achieving my goal, I would endlessly appreciate this.

Link to comment
Share on other sites

Hi and welcome to the forum.

From all those links you should get it working, but let me give you you one more example.

I try whenever I can to find solution from core files or modules. So you can check Carrier compare module.

For example in .js file it have on https://github.com/PrestaShop/ps_carriercomparison/blob/master/js/carriercompare.js#L84

call to method getStates. Which is executed in front controller  https://github.com/PrestaShop/ps_carriercomparison/blob/master/controllers/front/carrier_comparison.php#L45

So check your code inspect calls and see where it fails.

 

You can also send me module, if you want,  in Personal message and I will check it out.

Link to comment
Share on other sites

  • 1 month later...
On 10/8/2018 at 12:31 PM, razaro said:

Hi and welcome to the forum.

From all those links you should get it working, but let me give you you one more example.

I try whenever I can to find solution from core files or modules. So you can check Carrier compare module.

For example in .js file it have on https://github.com/PrestaShop/ps_carriercomparison/blob/master/js/carriercompare.js#L84

call to method getStates. Which is executed in front controller  https://github.com/PrestaShop/ps_carriercomparison/blob/master/controllers/front/carrier_comparison.php#L45

So check your code inspect calls and see where it fails.

 

You can also send me module, if you want,  in Personal message and I will check it out.

9

Hi razaro,

I have also tried all the above link but I am unable to make an ajax call. I made a form that has a textarea field and a button in my tpl file that is located under the "module/modulename/views/templates/front/enquiry/answer.tpl" directory. I had my Front controller in My module/modulename/controllers/front/enquiry.php and 
I wrote the following code
require_once(dirname(__FILE__).'/../../../../config/config.inc.php');
require_once(dirname(__FILE__).'/../../../../init.php');

class ProductEnquiryEnquiryModuleFrontController extends ModuleFrontController
{
    public function init()
    {
        parent::init();
    }

    public function displayAjaxDoSomeAction()
    {
        $var1 = Tools::getValue('variable_1');
        print_r($var2);
        die('actions');
    }
}    

in js file I wrote
function abc()
{

var var1 = $('#comment').val();

$.ajax({
    url : ano,
    type : 'POST',
    cache : false,
    data : {
        ajax : true,
        variable_1 : var1
        action : 'doSomeAction',
    },
    success : function (result) {
        // your action code on result
    }
});
}
 
And I my main file I had to define a path of the front controller as follows
        Media::addJsDef(array(
            'ano' =>$this->_path.'controllers/front/enquiry.php'
        ));
 
and in my answer.tpl file I had the following code
<form method="post">
        <div class="container">
            <div class="row">
                <div class="form-group">
                    <textarea rows="6" cols="50" id="comment" name="vendoranswer" placeholder="Answer:" ></textarea>
                </div>
                <div class="form-group">
                    <button type="button" name="submit" class="btn btn-success" onclick="abc()">Submit 
                    </button>  
                </div>
            </div>
        </div>
    </form>   
the problem I am getting nothing is printing in displayAjaxDoSomeAction function and ajax is giving "This request has no responce available".
Can you please help where I doing wrong. Any help will be appreciable. Thanks in advance

Link to comment
Share on other sites

Hi razaro, Thanks for your reply. It's working for me.

😃 😃

Can you please help me to overcome one more problem.

The problem is I am creating a productenquiry module in that module I need to display grid view in the frontend of my Prestashop website for this I made a front controller  under module/modulename/front/enquiry.php and in that following code I have wrote 

class ProductEnquiryEnquiryModuleFrontController extends ModuleFrontController
{
    public $controller_name = 'enquiry';
    public $module_name = 'productenquiry';

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

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

    public function initContent()
    {
            $this->renderList();

        parent::initContent();
    }

    public function renderList()
    {

            $this->table_header = array(
                array(
                    'label' => $this->module->l('ID', 'enquiry'),
                    'align' => 'right',
                    'class' => '',
                    'width' => '60'
                ),
                array(
                    'label' => $this->module->l('First Name', 'enquiry'),
                    'align' => 'left',
                    'class' => '',
                ),
                array(
                    'label' => $this->module->l('Last Name', 'enquiry'),
                    'align' => 'left',
                    'class' => '',
                    'width' => '120',
                ),
                array(
                    'label' => $this->module->l('Email', 'enquiry'),
                    'align' => 'left',
                ),
                array(
                    'label' => $this->module->l('Mobile', 'enquiry'),
                    'align' => 'left',
                    'class' => '',
                ),
                array(
                    'label' => $this->module->l('ID_Product', 'enquiry'),
                    'align' => 'right',
                    'class' => '',
                    'width' => '90',
                ),
                array(
                    'label' => $this->module->l('Query', 'enquiry'),
                    'align' => 'left',
                    'width' => '80',
                )
            );

            $orderby = null;
            if (Tools::getIsset('orderby') && Tools::getValue('orderby') != '') {
                $orderby = Tools::getValue('orderby');
            }

            $orderway = null;
            if (Tools::getIsset('orderway') && Tools::getValue('orderway') != '') {
                $orderway = Tools::getValue('orderway');
            }

            $product_enquiry = Db::getInstance()->executeS(
                    'SELECT * FROM '._DB_PREFIX_.'product_enquiry'
                );
                

            foreach ($product_enquiry as $val) {
                $this->table_content[$val['id_product_enquiry']] = array(
                    array('value' => $val['id_product_enquiry']),
                    array('value' => $val['firstname']),
                    array('value' => $val['lastname']),
                    array('value' => $val['email']),
                    array('value' => $val['mobile']),
                    array('value' => $val['product']),
                    array('value' => $val['question']),
                );
            }
        $this->context->smarty->assign(array(
            'new_product_link' => $this->context->link->getModuleLink(
                $this->module_name,
                $this->controller_name,
                array('render_type' => 'form'),
                (bool)Configuration::get('PS_SSL_ENABLED')
            )
        ));

        $this->setTemplate('module:productenquiry/views/templates/front/enquiry/abaa.tpl');
    }

 
}

and in my abaa.tpl file the following code I had wrote

{extends file='page.tpl'}
{block name="content"}
<div class="kb-content">
    <div class="kb-content-header">
        <h1>{l s='Enquiry' mod='productenquiry'}</h1>

    </div>
    
</div>
{/block}

and the final output that I am getting is.  image1.png.0c3a7007d28cd837e7df822716531919.png

and I want the output to be like

image2.png.ef87ac5b9f7f4b2b367b531cb5ce7a26.png

Thanks in advance. please help I am really stuck in this.

 

 

Link to comment
Share on other sites

Hi Ruman

Not sure if you are passing any value to tpl file. You have assigned $this->table_header and later

$this->table_content  but I do not think that is passed to tpl file.

Also I do not see you defined table_header and table_content as class variables.

Try to add 

class ProductEnquiryEnquiryModuleFrontController extends ModuleFrontController
{
    public $controller_name = 'enquiry';
    public $module_name = 'productenquiry';
	
	public $table_header;
	public $table_content;

Than before $this->setTemplate pass values

$this->context->smarty->assign(array(
            'new_product_link' => $this->context->link->getModuleLink(
                $this->module_name,
                $this->controller_name,
                array('render_type' => 'form'),
                (bool)Configuration::get('PS_SSL_ENABLED')
            ),
			'table_header' => $this->table_header,
			'table_content' => $this->table_content,
       ));

Then in abaa.tpl try to see if those values are passed and if they are then make changes and read them in for  loop

{extends file='page.tpl'}
{block name="content"}
<div class="kb-content">
    <div class="kb-content-header">
        <h1>{l s='Enquiry' mod='productenquiry'}</h1>
		{$page_header|var_dump}
    </div>
    {$page_content|var_dump}
</div>
{/block}

 

Link to comment
Share on other sites

21 hours ago, razaro said:

Hi Ruman

Not sure if you are passing any value to tpl file. You have assigned $this->table_header and later

$this->table_content  but I do not think that is passed to tpl file.

Also I do not see you defined table_header and table_content as class variables.

Try to add 


class ProductEnquiryEnquiryModuleFrontController extends ModuleFrontController
{
    public $controller_name = 'enquiry';
    public $module_name = 'productenquiry';
	
	public $table_header;
	public $table_content;

Than before $this->setTemplate pass values


$this->context->smarty->assign(array(
            'new_product_link' => $this->context->link->getModuleLink(
                $this->module_name,
                $this->controller_name,
                array('render_type' => 'form'),
                (bool)Configuration::get('PS_SSL_ENABLED')
            ),
			'table_header' => $this->table_header,
			'table_content' => $this->table_content,
       ));

Then in abaa.tpl try to see if those values are passed and if they are then make changes and read them in for  loop


{extends file='page.tpl'}
{block name="content"}
<div class="kb-content">
    <div class="kb-content-header">
        <h1>{l s='Enquiry' mod='productenquiry'}</h1>
		{$page_header|var_dump}
    </div>
    {$page_content|var_dump}
</div>
{/block}

 

6

Hi  razaro,

Thank you for your reply. Your effort is appreciated but I would like to know some more details about it. This is not working for me. First defined the variable  public $table_header; 

public $table_content;  and then passed values like this 

$this->context->smarty->assign(array(
            'new_product_link' => $this->context->link->getModuleLink(
                $this->module_name,
                $this->controller_name,
                array('render_type' => 'form'),
                (bool)Configuration::get('PS_SSL_ENABLED')
            ),
            'page_header' => $this->table_header,
            'page_content' => $this->table_content,
        ));

Then in abaa.tpl i am accessing like this

{extends file='page.tpl'}
{block name="content"}
<div class="kb-content">
    <div class="kb-content-header">
        <h1>{l s='Enquiry' mod='productenquiry'}</h1>
             {$page_header|@var_dump}   
    </div>
    {$page_content|var_dump}    
</div>
{/block}

but this gives an error image3.thumb.png.b5598c70c673f4683b9eed15460c9054.png

 

but when I am removing     { $page_con tent|var_dump} line in my tpl file it gives the output as follows

image4.thumb.png.6d3983c7ef29d343dc9bc80f98b141f2.png

 

 Thanks in advance

 

 

Edited by Ruman (see edit history)
Link to comment
Share on other sites

  • 4 months later...
On 11/19/2018 at 3:08 PM, razaro said:

var ano = prestashop.urls.base_url + 'index.php?fc=module&module=modulename&controller=enquiry';

 

Try to use this as url, you should see some response. Notice modulename is your module name and use enquiry as controller.

Hi Razaro,
I try your response to Ruman but I don't see the value in in view...
I have:
- JS in root->modules->modulename->views->js->namejsfile.js
- CONTROLLER in root->modules->modulename->controllers->front->controllername.php
- VIEW in root->modules->modulename->views->templates->front->filename.tpl

in js file
 

$('#send').click(function(){
			var ciao = 'cioaa';
			var myUrl = prestashop.urls.base_url + 'index.php?fc=module&module=configuratore&controller=task';
			$.ajax({
		        type: 'get',
		        cache:false,
		        url: myUrl,
		        data: {
		          	ajax: true,
		          	datas:ciao,
		          	action: 'fromAjax',
		        },
	      })
	      .done(function() {
	        console.log('Success!');
	      })
	      .fail(function() {
	        console.log('error');
	      });
});

in php file
 

class ConfiguratoreTaskModuleFrontController extends ModuleFrontController
{
	public function __construct()
	{
		parent::__construct();
	}

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

	public function initContent()
	{


		parent::initContent();
		$this->setTemplate('module:configuratore/views/templates/front/task.tpl');
	}
	$this->fromAjax();
}

public function fromAjax()
{
	$mVar = Tools::getValue('datas');
	return	 $this->context->smarty->assign(array('var'=>$mVar));
}

and in tpl

{$var}

in console log I receive success as a answer but I can't see in view?
What I'm doing wrong?
 

Link to comment
Share on other sites

  • 3 years later...

Hi Razaro,

I need help on ajax request from custom page.

in view.tpl
<form action="" method="post">
  <label for="fname">First name:</label>
  <input type="text" id="fname" name="fname"><br><br>
  <label for="lname">Last name:</label>
  <input type="text" id="lname" name="lname"><br><br>
  <input type="file" name="videoUpload" id="videoUpload" tabindex="7" class="videoUpload">
  <input type="submit" value="Submit" id="submit_form">
</form>


in formsubmit.php file(php file in override module)

Note : file exists in root/override/modules/modulename/formsubmit.php (In original module folder its exists in same path modulename/formsubmit.php)
class formsubmitOverride extends formsubmit{

}

public function displayAjaxinsertvideo(){
        $this->ajax = true;
        
    
}


in js


var url = prestashop.urls.base_url + 'formsubmit.php?fc=module&module=mymodule&controller=formsubmit';
$("#submit_form").click(function() {
        //url:'formsubmit.php'
        $.ajax({
        url : url,
        type : 'POST',
        cache : false,
        data : {
            ajax : true,
            variable_1 : 'test',
            variable_2 : 'tst',
            action : insertvideo,
        },
        success : function (result) {
            alert('AJAX call was successful!'+result);
                    //alert('Data from the server' + response);
                },
                error: function() {        
                    alert('There was some error performing the AJAX call!');
                }
        });
    });

 

 

I tried many ways but still didn't get any solution,getting error that insertvideo not found.

 

please have a look and let me know the solution

Thanks

Edited by sg_sg
override module file path updated (see edit history)
Link to comment
Share on other sites

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...