I need to add a block to a page. In a block adding dialog I have a select box which I need to fill with data received from ajax prior to saving the block (it cannot be saved unless I select the option).
The problem is the ajax call is usually to a controller action which doesn't exist until I save the block which I can't save before the option is selected. How can I make an ajax call to any other non-action function prior to the block saving? Can it be any other controller function or it must only be an action_function? Is this possible?
[UPDATE]
I'm trying with routes. Declared a route in the package controller:
$this->app->make(Router::class)->register('/api/get_forum_posts', '\Concrete\Package\AbForum\Src\Forum\MyFunctions::get_forum_posts', null, [], [], '', [], ['GET']);
but it says:
Exception Occurred:
/srv/www/htdocs/c584/concrete/src/Controller/ApplicationAwareControllerResolver.php:89
Class "\Concrete\Package\AbForum\Src\Forum\MyFunctions" does not
exist.
but the class MyFunctions IS in that folder packages/ab_forum/src/Forum/MyFunctions.php
I got it. The following works.
In the package controller:
protected $pkgAutoloaderRegistries = [
'src/Forum' => 'Forum'
];
public function on_start()
{
$this->app->make(Router::class)->register('/api/get_forum_posts', 'Forum\MyFunctions::getForumPostsJson', null, [], [], '', [], ['GET']);
...
}
The MyFunctions controller class in packages/ab_forum/src/Forum/MyFunctions.php:
namespace Forum;
use Concrete\Core\Controller\AbstractController;
class MyFunctions extends AbstractController
{
public function getForumPostsJson()
{
$data = $request->request->all();
...
echo json_encode($json);
exit;
}
}
The block form with ajax:
$.ajax({
url: '<?php echo Url::to('api/get_forum_posts'); ?>',
type: 'GET',
data: {
topic: topic.val(),
date: date.val(),
},
})
.done(function(data) {
...
});
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();
}
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.
I am trying to call an action in a controller via an ajax request and it works but it also loads the layout twice and I am getting this notice: "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/." The url where the ajax request is being sent at is /admin/errors.
Here is the code:
<script type="text/javascript">
$("input").on("click", function() {
$.ajax({
type: "POST",
url: "<?php echo $this->url('admin', array('action' => 'geterror')); ?>",
data: { error_type: $("input:checked").val() },
success: function(data) {
$('#view-errors').html(data + "<br>");
}
});
});
</script>
and the code in the action:
public function geterrorAction()
{
if (!$user = $this->identity()) {
return $this->redirect()->toUrl('/login/log');
}
$user = $this->identity();
$layout = $this->layout();
$layout->setTerminal(true);
echo ErrorView::viewErrors($_POST['error_type']);
}
Here is a image to better help explain.
Appreciate any help!
Add a blank layout file inside layout directory.
use $this->layout('layout/blank'); inside the action of the controller. This will set a blank layout.
public function geterrorAction()
{
$this->layout('layout/blank');
// .... other codes
}
try setting the terminal true on the view model
public function geterrorAction()
{
if (!$user = $this->identity()) {
return $this->redirect()->toUrl('/login/log');
}
$user = $this->identity();
$layout = $this->layout();
echo ErrorView::viewErrors($_POST['error_type']);
$view = new ViewModel();
$view->setTerminal(true);
return $view;
}
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');
}
}
I've been trying for ages to get Json working in Joomla and I just can't do it. I think I've tried every combination of URL etc so any help would be great:
this is for the admin side structure looks like
admin
-controllers
--orderitem.php
-views
--orderitem
---tmpl
----orderitem.php
-controller.php
function updateNow(newrefresh) {
var dataJSON = JSON.encode (newrefresh);
var request = new Request.JSON({
method: 'post',
url: 'index.php?option=com_customersitedetails&view=orderitem&task=refreshscreen&format=raw',
data: {
json: dataJSON
},
onComplete: function(jsonObj) {
alert("Your form has been successfully submitted ");
}
}).send();
};
Although runs the alert box it doesn't retun JSON just
View not found [name, type, prefix]: orderitem, raw, customersitedetailsView
Any ideas where I can start? thanks
You're missing views/orderitem/view.raw.php containing a CustomersitedetailsViewOrderitem class.
views/orderitem/view.raw.php
class CustomersitedetailsViewOrderitem extends JViewLegacy
{
public function display($tpl = null)
{
$response = 'Your magic response here';
echo $response;
JFactory::getApplication()->close();
}
}
You can look here for proper ajax call in joomla
How to Write PHP in AJAX
inside your controllers you should have a file "mycall.json.php" this file will process and return a json format of your ajax call
Joomla doesn't gives a build in AJAX as part of it's system. my answer is from Josef Leblanc course in lynda.com
http://www.lynda.com/Joomla-1-6-tutorials/Joomla-1-7-Programming-and-Packaging-Extensions/73654-2.html
As I said :
Write this i the frontend JS :
$.ajax({
type: 'GET',
url: 'index.php',
data: {option: 'com_componenetname', task: 'taskname.youroperation', format: 'json', tmpl: 'raw'},
dataType: 'json',
async: true, // can be false also
error: function(xhr, status, error) {
console.log("AJAX ERROR in taskToggleSuceess: ")
var err = eval("(" + xhr.responseText + ")");
console.log(err.Message);
},
success: function(response){
// on success do something
// use response.valuname for server's data
}
,
complete: function() {
// stop waiting if necessary
}
});
in the backend you should have a file under com_componentname/controllers/taskname.json.php
the file should look like this
class ComponentnameControllerTaskname extends JControllerLegacy (Legacy only J3.0)
{
public function __construct($config = array())
{
parent::__construct($config);
$this->registerTask('operationname', 'functionname');
}
public function functionname() {
// do something in backend
echo json_encode(array(''var1' => val1, 'var2' => val2 ) );
}
}
nibra - I use this in all my joomla sites and its working perfect. your comment was wrong, pease give me my credit back