Joomla component: controller not returning json - joomla

Why is my controller not returning my data in JSON format? Note that I am developing my component on Joomla 3.1.1.
/hmi.php
//Requries the joomla's base controller
jimport('joomla.application.component.controller');
//Create the controller
$controller = JControllerLegacy::getInstance('HMI');
//Perform the Request task
$controller ->execute(JRequest::setVar('view', 'hmimain'));
//Redirects if set by the controller
$controller->redirect();
/controller.php
class HMIController extends JControllerLegacy
{
function __construct()
{
//Registering Views
$this->registerTask('hmimain', 'hmiMain');
parent::__construct();
}
function hmiMain()
{
$view =& $this->getView('hmimain','html');
$view->setModel($this->getModel('hmimain'), true);
$view->display();
}
public function saveHMI()
{
echo 'Testing';
$this->display();
}
}//End of class HMIController
/controllers/properties.json.php
class HMIControllerProperties extends JController
{
function __construct()
{
$this->registerTask(' taskm', 'taskM');
parent::__construct();
}
function taskM()
{
$document =& JFactory::getDocument();
// Set the MIME type for JSON output.
$document->setMimeEncoding('application/json');
// Change the suggested filename.
JResponse::setHeader('Content-Disposition','attachment;filename="json.json"');
echo json_encode('Hello World');
// Exit the application.
Jexit();
}
}
JQuery function calling the joomla task
var request = $.ajax({
dataType:"json",
url:"index.php?option=com_hmi&task=properties.taskm&format=json",
type:"POST",
data:{propPage: "ABC"},
beforeSend: function (){
$("#loading_Bar").css("display","block");
}
});// dot ajax
When I use the above ajax settings the request fails. However if I change the datatype property to text, and remove the format=json from the url, I get html instead of json.
Can some one point out what I'm doing wrong?

Further investigation to my problem i concluded that the componenet was not triggering the desired task becuse of the following code in my /hmi.php
$controller ->execute(JRequest::setVar('view', 'hmimain'));
So I modified my /hmi.php as follows
//Requries the joomla's base controller
jimport('joomla.application.component.controller');
// Create the controller
$controller = JControllerLegacy::getInstance('HMI');
$selectedTask = JRequest::getVar( 'task');
if ($selectedTask == null)
{
//This will allow you to access the main view using index?option=com_hmi
//and load the "default" view
$controller->execute( JRequest::setVar( 'view', 'hmimain' ) );
}
else
{
//Will execute the assigned task
$controller->execute( JRequest::getVar( 'task' ) );
}
// Redirect if set by the controller
$controller->redirect();
then created the /controllers/properties.json.php file with the following code
class HMIControllerProperties extends JControllerLegacy
{
function myMethod()
{
$model = $this->getModel('hmimain');
$dataToolboxItems =& $model->getToolboxItems();
echo json_encode($dataToolboxItems);
//JExit();
}
}//End of class HMIController
then i'm calling the task from jquery as follows:
var request = $.ajax({
dataType:"json",
//task=properties.mymethod will access the subcontroller within the controllers folder
//format=json will by access the json version of the subcontroller
url:"index.php?option=com_hmi&task=properties.mymethod&format=json",
type:"POST",
data:{propPage: "ABC"},
beforeSend: function (){
$("#loading_Bar").css("display","block");
}
});

In your ajax request try changing to this format:
dataType:'json',
url: 'index.php',
data: {option: 'com_hmi', task: 'properties.task', format: 'jason', propPage: 'ABC' },
type:'POST',
.....
Another thing is in the controller file add the Legacy:
HMIControllerProperties extends JControllerLegacy
And I don't think you need this lines, for me it works without them
$document->setMimeEncoding('application/json');
JResponse::setHeader('Content-Disposition','attachment;filename="json.json"');

Related

ajax not getting any response from cakephp code

I am using CakePHP 2.9 to send data on the URL using ajax and get the related response.
I tried may method to get the response, I also want to know why this //URL:'/Pages/dropdownbox/'+id is not working.
bellow are ajax code which I wrote in the index.ctp.
$("#certificatedetail").on('change',function() {
var id = 'subcribe';
$("#usertype").find('option').remove();
$("#certificateclass").find('option').remove();
$("#certificatetyp").find('option').remove();
if (id) {
$.ajax({
type: 'POST',
url:'<?= Router::url(array('controller' => 'Pages', 'action' => 'dropdownbox','id')); ?>',
//url:'/Pages/dropdownbox/'+id,
dataType:'json',
cache: false,
async:true,
success: function(html)
{
$('<option>').val('').text('select').appendTo($("#usertype"));
$('<option>').val('').text('select').appendTo($("#certificateclass"));
$('<option>').val('').text('Select').appendTo($("#certificatetyp"));
$.each(html, function(key, value)
{
$('<option>').val(key).text(value).appendTo($("#usertype"));
});
}
});
}
});
I have written this controller code in PagesController,PHP and I declared the dropdownbox in AppController.php
public function dropdownbox($id = null)
{
Configure::write('debug', 0);
$this->layout = null;
$this->autoRender = false;
$category = array();
switch ($id)
{
case $id == "subcribe":
if ($id == 'subcribe') {
$category = array(
'individual' => 'Individual',
'organization'=>'Organization',
'organizationgovt' => 'Organization-Govt',
'organizationbank' => 'Organization-Bank'
);
break;
}
}
}
/ bellow is the code where I specify the dropdownbox function in AppController.php
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow(
'login','add','index','contact','dropdownbox',
'cityres','stateres','sectorres','productres',
'project','service','about','apply','tender',
'decregistration','search','searchresult',
'tenderdetails'
);
}
You are generating the URL on your server, and using the string literal 'id' in it. The JavaScript id variable is never referenced. What you probably want is:
url:'<?= Router::url(array('controller' => 'Pages', 'action' => 'dropdownbox')); ?>' + id,
You are not returning any response from the controller. Do few things to debug it
Check in Browser's Network tab whether the called URL is correct or not.
Check the parameters are correct or not.
This is how it looks in Firefox Developer Edition
If URL is correct. Add below code in the dropdownbox() method. (Before the closing of the method)
echo json_encode($category);
Check Response Tab in the Network tab. (Example image above).
Also, console the response in the javascript code. Maybe you will be getting some other response which is not JSON.
success: function(html) {
console.log(html);
...
}
Hope it helps.

Quick Order module for Magento 2

I want to create a module of quickorder in magento 2. I have got an issues with the code path block, ajax etc. Please someone can help me on this. How can i generate the JS/Ajax autosearch file for work like search product by product name or SKU then i add that product to shopping cart page. I try to help one module like "MageWorx_SearchSuitAutoComplete" but it product an issues. Kindly help me on this.
Make A controller with front name like Quickorder/index/index,now execute a function on Quickorder.
<?php
namespace CompanyName\CustomApi\Controller\Index;
class Index extends \Magento\Framework\App\Action\Action
{
protected $resultPageFactory;
protected $httpClientFactory;
protected $productCollectionFactory;
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\View\Result\PageFactory $resultPageFactory,
\Magento\Framework\HTTP\ZendClientFactory $httpClientFactory,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
\Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
) {
$this->resultPageFactory = $resultPageFactory;
$this->productCollectionFactory = $productCollectionFactory;
$this->_httpClientFactory = $httpClientFactory;
$this->resultJsonFactory = $resultJsonFactory;
parent::__construct($context);
}
public function execute(){
$search_text = $this->getRequest()->getPost('search_text');
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect(array('name'))->addAttributeToFilter('name',
array('like' => $search_text.' %'),
array('like' => '% '.$search_text.' %'),
array('like' => '% '.$search_text)
));
echo "<pre>";
print_r($collection->getData());
die();
}
On input type make a jquery function and request a ajax call with keyup.
$('#quick-search').keyup(function(){
var search_text = jQuery("#quick-search").val();
try {
jQuery.ajax({
url : '<?php echo $block->getUrl('quickorder/index/index') ?>',
dataType : 'json',
data: { 'search_text' : search_text },
type : 'post',
success : function(data) {
jQuery('.main-search-results').html(data.products);
}
});
} catch (e) {
}
});
Or you can also used require js instead of this jquery.
Thanks

Codeigniter inline edit not working

I created the following code, but do not run. Can you help?
My Controller
public function updateDb()
{
//$this->load->model('user_m');
$this->page_m->inline($_POST['file_description']);
return;
}
My Model
public function inline( $file_description, $id ){
$this->db->set($data)->where($this->$id, $page['file_description'])->update($this->file);
}
Form
<?php echo $file->file_description?>
Jquery
function showEdit(file_description) {
$(file_description).css("background","#FFF");
}
function save(file_description) {
$(file_description).css("background","#FFF url(<?php echo base_url('assets/img/loaderIcon.gif');?>loaderIcon.gif) no-repeat right");
$.ajax({
url: "<?php echo base_url()?>index.php/admin/page/updateDb",
type: "POST",
id : '<?php echo $page->id;?>',
name : 'file_description'
});
}
Looks like you're not passing the ID to your model which it requires.
public function inline( $file_description, $id ){...}
$this->page_m->inline($_POST['file_description'], $_POST['id']);
You could use $this->input->post() though...

How to call multiple methods by URI segments in CodeIgniter

I have an issue with CodeIgniter; I have a controller named site, and in this controller there are two methods: production and story.
production calls a specific production via a model which creates production/slug.
What I want to achieve is to create the following URL:
site/production/slug/story
How do I achieve that? As the slug changes, in the story function I want to call a story from the database using $this->uri->segment(3).
You can post multi parameters:
URI: site/production/slug/story/5
public function production($one, $two, $there)
{
echo $one."<br />";
echo $two."<br />";
echo $there."<br />";
}
# OUTPUT
slug
story
5
Pass the method name as second parameter to the first method.
For example, if the URI is site/production/slug/story, pass story to the production method and do necessary checks as below:
class Site extends CI_Controller {
public function __construct()
{
parent::__construct()
}
public function story($text) {
echo $text;
}
public function production($slug = '', $callback = NULL)
{
// Do something with $slug
if (isset($callback) && method_exists(__CLASS__, $callback)) {
$this->{$callback}($slug);
}
}
}
PHPFiddle Demo

Controller must return a response in Symfony2

I have an ajax call in my code. What I want to achieve with the call works fine. I want to delete some records from the database which is actually deleted when the method is called via ajax but as in symfony method it must return a response and thats why when the method is executed its gives me the error
My Ajax call is
$.ajax({
type: "POST",
data: data,
url:"{{ path('v2_pm_patents_trashpatents') }}",
cache: false,
success: function(){
document.location.reload(true);
}
});
And the method that is executed is
public function trashpatentAction(Request $request){
if ($request->isXmlHttpRequest()) {
$id = $request->get("pid");
$em = $this->getDoctrine()->getEntityManager();
$patent_group = $em->getRepository('MunichInnovationGroupPatentBundle:PmPatentgroups')->find($id);
if($patent_group){
$patentgroup_id = $patent_group->getId();
$em = $this->getDoctrine()->getEntityManager();
$patents = $em->getRepository('MunichInnovationGroupPatentBundle:SvPatents')
->findBy(array('patentgroup' => $patentgroup_id));
if($patents){
foreach($patents as $patent){
if($patent->getIs_deleted()==false){
$patent->setIs_deleted(true);
$em->flush();
}
}
}
$patent_group->setIs_deleted(true);
$em->flush();
}
else{
$em = $this->getDoctrine()->getEntityManager();
$patent = $em->getRepository('MunichInnovationGroupPatentBundle:SvPatents')->find($id);
if ($patent) {
$patent->setIs_deleted(1);
$em->flush();
}
}
return true;
}
}
How can I successfully return from this method ?
Any ideas? Thanks
Replace return true; with return new Response();. Also don't forget to write use Symfony\Component\HttpFoundation\Response; at the top.
You can also pass error code 200 and the content type like below.
return new Response('Its coming from here .', 200, array('Content-Type' => 'text/html'));
Here is the full example of the controller
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
class WelcomeController extends Controller
{
public function indexAction()
{
return new Response('Its coming from here .', 200, array('Content-Type' => 'text/html'));
}
}

Resources