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;
}
Related
I have trying to load a page using simple get request
<script>
$(document).ready(function(){
$("li").click(function(e){
e.preventDefault();
var href = $("a",this).attr('href');
$.ajax({
async: true,
type: "GET",
url: href,
success: function (response) {
$('#main-content').html(response);
}
})
});
});
</script>
In response I am getting content with full layout. But Here I am trying to get only content without layout. In controller I have written code like below
public function index()
{
if ($request->ajax())
{
$this->layout = null; //but same result
}
$tags = Tag::orderBy('id', 'desc')->paginate(10);
return view('admin.tags.index')->with('tags',$tags);
}
But I am getting same result with layout, how can I make layout false ? Or can change layout in controller ?
you can use the renderSections
return view('admin.tags.index')->renderSections()['content'];
https://laravel-tricks.com/tricks/render-view-without-layout
Well, you are still returning a view. Why not do:
return response()->json(["data"=>"some data"]);
after your Ajax check? This will return a JSON response to your frontend.
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 have a PrestaShop module called 'MyMenu' and I want call this menu with an AJAX call.
My module is displayed in the hookFooter() method:
public function hookFooter()
{
$display = $this->display(__FILE__, 'megamenu.tpl', $smartyCacheId);
Tools::restoreCacheSettings();
return $display;
}
I want display with this script:
<div class="load_menu"></div>
<script>
$(document).ready(function (e) {
$.ajax({
method: "POST",
url: "../modules/MyMenu.php",
data: {},
success: function (data) {
$('.load_menu').html(data);
}
})
});
</script>
The best way is to do it via a front controller linked to your module.
You can call the url like this :
$link->getModuleLink('modulename','controller', $parameters);
// Parameters is an optionnal array, it can be empty
And for the controller, place a file like this ./modules/modulename/controllers/front/ajax.php with this kind of content :
class ModuleNameAjaxModuleFrontController extends ModuleFrontController
{
public function initContent()
{
$response = array('status' => false);
require_once _PS_MODULE_DIR_.'modulename/modulename.php';
$module = new ModuleName;
if (Tools::isSubmit('action')) {
$context = Context::getContext();
$cart = $context->cart;
switch (Tools::getValue('action')) {
case 'actionname':
$response = array('status' => true);
break;
default:
break;
}
}
// Classic json response
$json = Tools::jsonEncode($response);
$this->ajaxDie($json);
// For displaying like any other use this method to assign and display your template placed in modules/modulename/views/template/front/...
// $this->context->smarty->assign(array('var1'=>'value1'));
// $this->setTemplate('template.tpl');
// For sending a template in ajax use this method
// $this->context->smarty->fetch('template.tpl');
}
}
If you don't want to pass the url by the module, the js snippet should be like this.
$(document).ready(function(){
$.ajax({
type: "POST",
headers: { "cache-control": "no-cache" },
url : baseDir + 'modules/yourmodulename/yourfile.php',
data: {
token : token
},
success : function(data){
$('.load-menu').html(data)
}
});
});
Where yourmodulename is the name of your module and yourfile.php is the code where you retrieve the menu.
Don't forget to add to your data the token, it's to prevent a CSFR attack, obviously you have to check the token in your server side script as well.
In a new file at the module root, you can create a file "ajax.php"
require_once(MODULE_DIR.'MyMenu/mymenu.php');
if(Tools::getValue('token') !=
$mymenu = Module::getInstanceByName('mymenu');
$menu = $mymenu->hookFooter();
die($menu);
In your js, at the root of your module
<script>
$(document).ready(function (e) {
$.ajax({
method: "POST",
url: "./ajax.php",
data: {},
success: function (data) {
$('.load_menu').html(data);
}
})
});
</script>
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
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 ;)