Prestashop: Pass data from js file to controller to custom page - ajax

I'm having difficulty passing the value from my personal js to the controller and recovering it on the personal tpl page.
This module will serve to customize product after some selections and fields to fill out.
The selections pass from tabs to tabs.
The problem is that I can't get the value {$ var}
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
$('#send').click(function(){
var ciao = 'cioaa';
var myUrl = prestashop.urls.base_url + 'index.php?fc=module&module=configuratore';
$.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
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));
}
in TPL
{$var}

<?
public function fromAjax()
{
$mVar = Tools::getValue('datas');
$this->context->smarty->assign(array('var'=>$mVar));
$templateFile = 'module:configuratore/views/templates/front/task.tpl';
$html = $this->fetch($templateFile);
die($html); // pass to JS
}
in JS:
.done(function(html) {
console.log(html);
})

Related

I need a dropdown list based on parent using ajax in Laravel 5

Controller Function Code
public function siteadmin_get_subcategory(Request $request)
{
$product_id = $request->input('product');
$sub_category=array(
'product_id'=>$product_id,
);
$return = Category_model::get_subcategory($sub_category);
//return view('siteadmin.get-subcategory',['sub_category' => $sub_category]);
return view('siteadmin.get-subcategory',['sub_category' => $sub_category]);
}
Model Function Code (which gets subcategory on product id)
public static get_subcategory($sub_category)
{
return DB::table('le_product')->where('product_id', '=', $sub_category)->get();
}
View JavaScript Code
This is my Ajax concept for Dropdown list based on parent
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#product_id').change(function(){
var product = $('#product_id').val();
if(product != 0) {
$.ajax({
type:'post',
url:"<?php echo base_url('SiteadminController/siteadmin_getsub_category')?>",
data: { id:product },
cache:false,
success: function(returndata){
$('#subcategory').html(returndata);
}
});
}
})
})
</script>
You need to call the correct URL in your AJAX:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#product_id').change(function(){
var product = $('#product_id').val();
if(product != 0) {
$.ajax({
type:'post',
url:"<?php echo action('SiteadminController#siteadmin_getsub_category')?>",
data: { id:product },
cache:false,
success: function(returndata){
$('#subcategory').html(returndata);
}
});
}
})
})
</script>
Also AJAX is expecting JSON, from what I see, you will return HTML. So you need to make a Controller action to return JSON.
get_subcategory1
public function get_subcategory1()
{
/*$product_id = $request->input('product_id');
$data=array(
'product_id'=>$product_id,
);*/
//$get_subcategory1 = Category_model::get_subcategory1();
return view('siteadmin.get-subcategory1');
}

500 Internal server error in cakePHP 2 while trying to request using ajax

I get 500 internal server error if try get data from another Model(Product) in Cart model. using ajax. But if I only comment out the $this->Product->findBy(id) is working fine.
$('form#add_form').on('submit', function(e){
var thisForm = $(this);
$.ajax({
url: thisForm.attr('action'),
type: 'POST',
//dataType: 'json',
data: thisForm.serialize(),
success: function(count) {
var total_items = $('p#total-items');
total_items.html('Total items: ' + count);
console.log(count);
}
});
e.preventDefault();
});
this is my CartsController
class CartsController extends AppController {
public $uses = array('Product', 'Cart');
public function add() {
$this->autoRender = false;
$itemsInCart = $this->Session->read();
if ($this->request->is('POST')) {
$item = $this->Product->findBy($this->request->data['Cart']['product_id']);
}
echo $this->request->data['Cart']['product_id'];
}
}
there is no findBy method
You must change your controller code like this:
class CartsController extends AppController {
public $uses = array('Product', 'Cart');
public function add() {
$this->autoRender = false;
$itemsInCart = $this->Session->read();
if ($this->request->is('POST')) {
$productID = $this->request->data['Cart']['product_id'];
$item = $this->Product->findById($productID);
}
echo json_encode($this->request->data['Cart']['product_id']);
}
}

how to retrieve data sent by Ajax in Cakephp?

I have been stuck at this problem for a whole day. What im trying to do is to send 2 values from view to controller using Ajax.
This is my code in hot_products view:
<script>
$(function(){
$('#btnSubmit').click(function() {
var from = $('#from').val();
var to = $('#to').val();
alert(from+" "+to);
$.ajax({
url: "/orders/hot_products",
type: 'POST',
data: {"start_time": from, "end_time": to,
success: function(data){
alert("success");
}
}
});
});
});
and my hot_products controller:
public function hot_products()
{
if( $this->request->is('ajax') ) {
$this->autoRender = false;
//code to get data and process it here
}
}
I dont know how to get 2 values which are start_time and end_time.
Please help me. Thanks in advance.
PS: im using cakephp 2.3
$this->request->data gives you the post data in your controller.
public function hottest_products()
{
if( $this->request->is('ajax') ) {
$this->autoRender = false;
}
if ($this->request->isPost()) {
// get values here
echo $this->request->data['start_time'];
echo $this->request->data['end_time'];
}
}
Update
you've an error in your ajax,
$.ajax({
url: "/orders/hot_products",
type: 'POST',
data: {"start_time": from, "end_time": to },
success: function(data){
alert("success");
}
});
If you method is POST:
if($this->request->is('ajax'){
$this->request->data['start_time'];
$this->layout = 'ajax';
}
OR
public function somefunction(){
$this->request->data['start_time'];
$this->autoRender = false;
ANd if method is GET:
if($this->request->is('ajax'){
$this->request->query('start_time');
$this->layout = 'ajax';
}
OR
public function somefunction(){
$this->request->query('start_time');
$this->autoRender = false;

How to work with $resource in angularjs

I am trying to get data form this url http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo
through $resource below is my resource code
angular.module('myApp.services', ['ngResource']).
value('version', '0.1').factory('recipes1',['$resource', '$http', '$log', function ($resource, $http, $log) {
return $resource('http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo',{ },{ locate: {method: 'GET', isArray: true, transformResponse: $http.defaults.transformResponse.concat(function(data, headersGetter) {
// probably be better if you examined the results in here
alert(data);
})}
});
}]);
but i am not getting response. i am getting out put from my controller as
function Resource(value){
"use strict";
copy(value || {}, this);
}
Use $http with promise factory:
See working Demo in fiddle
JS
var fessmodule = angular.module('myModule', ['ngResource']);
fessmodule.controller('fessCntrl', function ($scope, Data) {
$scope.runMe = function () {
Data.query($scope.url)
.then(function (result) {
$scope.data = result;
}, function (result) {
alert("Error: No data returned");
});
}
});
fessmodule.$inject = ['$scope', 'Data'];
fessmodule.factory('Data', ['$http','$q', function($http, $q) {
var data = $http({method: 'GET', url: 'http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo'});
var factory = {
query: function (address) {
var deferred = $q.defer();
deferred.resolve(data);
return deferred.promise;
}
}
return factory;
}]);

Acessing ViewData in javascript?

I want to access view data In Java script in following code
public virtual ActionResult Edit(MyModel _MyModel)
{
//some Code
if (true..)
{
ViewData["Messages"] = "Data Updated Sucessfully";
}
else
{
ViewData["Messages"] = "you cannot Updated data";
}
return View();
}
In javascript
function SaveData() {
$("#btnSave").click(function () {
// $('#divLoadImage').show();
// $('#divOverlay').show();
// debugger;
$.ajax({
type: "POST",
url: "Admin/Edit/",
data: "",
complete: function () {
alert(ViewData["Messages"]);
}
});
});
}
it give me no value in alert..
You need to encode it using for example the JavaScriptSerializer class:
function SaveData() {
$("#btnSave").click(function () {
$.ajax({
type: "POST",
url: "Admin/Edit/",
data: "",
complete: function () {
alert(#Html.Raw(new JavaScriptSerializer().Serialize(ViewData["Messages"])));
}
});
});
}
or use simple quotes but be careful as this might break if the message contains quote so I wouldn't recommend you this:
alert('#ViewData["Messages"]');

Resources