outside the conventional methods of ajax requests from a prestashop module, I would like to use a ajax method from product.js and retrieve data from an override controller.
my function in product.js :
function attrReference(ref){
$.ajax({
url: baseUri,
async: true,
cache: false,
type:'GET',
dataType : "json",
headers: { "cache-control": "no-cache" },
data: {
controller :'product',
action :'attrReference',
token : token,
ajax: 1,
ref : ref
},
success: function(data){
}
});
}
My override controller product :
class ProductController extends ProductControllerCore{
public function displayAjaxAttrReference(){
echo '<pre style="background:yellow">';
print_r($_GET);
echo '</pre>';
exit;
}
}
From the documentation, i use displayAjax to recover data, unless this is not the right method, I tried many attempts but none are correct.
Do you have any idea?
If you need to retrieve data, or little piece of html i suggest to avoid the displayAjax function since it's called only at the end of the controller routine, and thus you will get everything processed (retrieving of template, database query and so on).
normally the controller function are called with the following list:
init();
setMedia();
// postProcess handles ajaxProcess
postProcess();
initHeader();
initContent();
initFooter();
displayAjax() || display();
as you can see displayAjax should be avoided if you don't want to retrieve the whole page/a template the require all the information of the product page.
To correctly route your request you should override also the postProcess function of your product controller such that:
public function postProcess(){
if(Tools::isSubmit('action') && Tools::getValue('action') == 'attrReference')
$this->AjaxGetReference();
parent::postProcess();
}
and then
public function AjaxGetReference(){
echo '<pre style="background:yellow">';
print_r($_GET);
echo '</pre>';
die();
}
Also, always remember to pass the id_product with your ajax function if you are interacting with the ProductController, else any action will fail becouse of the init function:
public function init()
{
parent::init();
if ($id_product = (int)Tools::getValue('id_product'))
$this->product = new Product($id_product, true, $this->context->language->id, $this->context->shop->id);
if (!Validate::isLoadedObject($this->product))
{
header('HTTP/1.1 404 Not Found');
header('Status: 404 Not Found');
$this->errors[] = Tools::displayError('Product not found');
}
}
Related
Controller path
Route::get('ajax-BodegasFind','AjaxController#ajaxBodegasFind')->name('ajax.bodegasfind');
Function "ajaxBodegasFind"
public function ajaxBodegasFind(Request $Request)
{
$Tienda = new Tienda;
$Bodegas = $Tienda::find($Request)->bodegas();
return $Bodegas->toJson();
}
Ajax script
$(document).ready(function(){
$('#cod_tienda').change(function(e){
e.preventDefault();
var ctienda = $("#cod_tienda").val();
$.ajax({
type: 'get',
url:'{{route('ajax.bodegasfind')}}',
data: {
"ctienda": ctienda,
},
dataType: 'json',
success: function(data){
console.log(data);
$('#cod_bodega').html(data);
}
});
});
});
Model Tienda
public function bodegas(){
return $this->hasMany('genericlothing\Bodega','cod_tienda','cod_tienda');
}
Error:
Failed to load resource: the server responded with a status of 500 (Internal Server Error) /ajax-BodegasFind?ctienda=3:1
Method Illuminate\Database\Eloquent\Collection::bodegas does not exist.
Or Method toJson does not exist, it's very weird.
Pd:
I already tried the csrf token and everything is the same.
you change your code like this:
public function ajaxBodegasFind(Request $Request)
{
$Bodegas = (Tienda::find($Request->id))->bodegas;
return $Bodegas->toJson();
}
you should have bodegas relationship method in your Tienda
And in find method your should send id not Request object .Maybe you change your find methods . its ok if you do it
hope its help
You cannot call a static find method on an instance object and you cannot pass request object in find method. It only takes primary key id. You should change your code the following two ways. You must have badge relation in your model(if you want to get related data) . Otherwise just call the property.
Option 1.
public function ajaxBodegasFind(Request $Request)
{
$Tienda = new Tienda;
$Bodegas = $Tienda->find($Request->id)->bodegas;
return $Bodegas->toJson();
}
Option 2.
public function ajaxBodegasFind(Request $Request)
{
$Bodegas = Tienda::find($Request->id)->bodegas;
return $Bodegas->toJson();
}
My table contains many rows from database. After clicking edit button in a row, I want to redirect it to another page. I am able get the data, but it cannot redirect to the other page.
I'm using bootstrap template, so there are different file to load on view. I do not know how to load view that consist of more than one files.
Ajax
$('#example2').on('click','#edit',function(){
var id_per = $(this).closest('tr').attr('id');
alert("ini"+id_per);
$.ajax({
url:"<?php echo base_url('c_dokter/ubahdt_perawatan/');?>" + id_per,
type:"POST",
data:{
id_perawatan : id_per,
id_pasien : id_pasien
},
dataType:'JSON',
success:function(data) {
},
error:function() {
alert('error ... ');
}
});
Controller
public function ubahdt_perawatan($id_perawatan){
$data['pasien']=$this->m_pasien->spes_Perawatan($id_perawatan);
if ($this->input->is_ajax_request()) {
echo json_encode($data);
exit;
}
$data['pasien']=$this->m_pasien->DataPerPasien($id_pasien)->result();
$data['sidebar']='member/dokter/sidebar_psn';
$data['content']='member/dokter/edit_perawatan';
$this->load->view('member/dokter/main',$data);
}
Edited answer:
public function ubahdt_perawatan($id_perawatan){
$data['pasien']=$this->m_pasien->spes_Perawatan($id_perawatan);
if ($this->input->is_ajax_request())
{
echo json_encode($data);
}
}
public function test()
{
$id_pasien=$this->uri->segment(2);
$data['pasien']=$this->m_pasien->DataPerPasien($id_pasien)->result();
$this->load->view('member/dokter/sidebar_psn');
$this->load->view('member/dokter/edit_perawatan');
$this->load->view('member/dokter/main',$data);
}
set path to test() in routes.php..
$route['test/(:any)']='controller/test';
then in ajax success function
success:function(data){
window.location.href="<?php echo site_url('test/'.data);";
},
try it.
I am trying sent one data from one view to another controller and set the data for another view. Here is ajax code working fine
$.ajax({
url: "<?php echo Router::url(array('controller'=>'users','action'=>'exchange_process'));?>",
type: "POST",
data: {"point_origin": point_origin },
success: function(){
alert("success");
}
});
In controller I have received this data by bellow code
public function exchange_process()
{
if($this->request->is(array('post', 'ajax'))) {
$point_origin=$_POST['point_origin'];
}
$this->set("pointorg",$point_origin);
}
In another view I have tried
<?php echo $pointorg ?>
It's not working.
if I try
public function exchange_process()
{
if($this->request->is(array('post', 'ajax'))) {
// $point_origin=$_POST['point_origin'];
}
$point_origin=123;
$this->set("pointorg",$point_origin);
}
It's working,but if I try
public function exchange_process()
{
if($this->request->is(array('post', 'ajax'))) {
// $point_origin=$_POST['point_origin'];
$point_origin=123;
}
$this->set("pointorg",$point_origin);
}
It's not working.
change your if clause to:
if($this->request->is('post') || $this->request->is('ajax')) {
and it should be working fine
CakePHP 2.3 doesnot support array of type headers, please check
http://book.cakephp.org/2.0/en/appendices/2-4-migration-guide.html#cakerequest
you will need to check individually or use Ajax only if request is to be sent using Ajax only.
The situation, I'm making multiple ajax/json requests on the same page to a controller, which returns a JsonResult.
I know this is a problem with the session state, I've added the [SessionState(SessionStateBehavior.Disabled)] attribute on my controller class, but nothing seems to work, my second ajax request just wont get the return data.
the controller:
[SessionState(SessionStateBehavior.Disabled)]
public class IndexController : Controller
{}
the two json methods:
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetLatestListJSON()
{
Thread.Sleep(5000);
ArticleRepository repo = new ArticleRepository();
IList<ArticleModel> list = repo.GetLatestContent(10);
return Json(list, JsonRequestBehavior.AllowGet);
}
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetCustomerJSON()
{
Thread.Sleep(5000);
CustomerRepository Repo = new CustomerRepository();
IList<Customer> cust= Repo.GetCustomer();
return Json(cust, JsonRequestBehavior.AllowGet);
}
The second ajax call, the other one is very similar, I never get to see the 'succes'-alert.
<script type="text/javascript">
$(document).ready(function () {
alert('before');
$.getJSON("/Index/GetCustomerJSON", null, function (data) {
alert('succes');
$("#loadingGifVideo").hide();
$.each(data, function (index, mod) {
});
});
});
Thanks guys :)
If you put a break-point in your GetCustomerJSON method and run this in Visual Studio does the method ever get called? It does
EDIT
Try switching from getJSON to the ajax method so you can capture any errors. Like so:
$.ajax({
url: "/Index/GetCustomerJSON",
dataType: 'json',
data: null,
success: function (data) { alert('success'); }
error: function (data) { alert('error'); }
});
Do you get an "error" alert?
Assume that I have a public function in IndexController called test():
public function test(){
//some code here
}
In index.phtml view file, I want to use JQUERY AJAX to call test() function but have no idea about this.
Code:
Click me to call test() function()
<script>
callTestFunction = function(){
$.ajax({
type: "POST",
Url: ***//WHAT SHOULD BE HERE***
Success: function(result){
alert('Success');
}
});
}
</script>
I would suggest writing an action for it. If there is logic inside of test() that you need other actions to be able to use, the factor that out.
There are a couple of reasons for having it be its own action:
You can test the results of the action directly instead of having to go through a proxy.
You can take advantage of context switching depending on if you need JSON returned or HTML
It is an action that you are trying to hit via AJAX, so there's no need to hide it.
Remember that not every action has to be its own full fledged page. One thing to make sure you do is disabling the auto-rendering of the view inside this action so it doesn't complain about not being able to find it.
public function ajaxproxyAction(){
if (is_callable($_REQUEST['function_name'])) {
return call_user_func_array($_REQUEST['function_name'], $_REQUEST['function_params'])
}
}
<script>
callTestFunction = function(){
$.ajax({
type: "POST",
Url: '/controller/ajaxproxy/',
data: { function_name: 'echo', function_params: 'test' }
Success: function(result){
alert('Success');
}
});
}
</script>
public function ajaxproxy2Action(){
if (method_exists($this, $_REQUEST['function_name'])) {
$retval = call_user_func_array(array($this, $_REQUEST['function_name']), $_REQUEST['function_params']);
echo json_encode(array('function_name' => $_REQUEST['function_name'], 'retval' => $retval));
die;
}
}
just think about this way ;)