Trying to use datatables in Slim 3 what is the best way/structure to make the ajax call - datatables

I am trying to use datatables inside a view in Slim 3. To me the simplest way to use datatables is to make an ajax call, because I don't know how I would pass a json object to datatables from a controller. I'm not sure where to put my ajax calls. Should I create another folder in my App folder and call it ajax? Or am I going about this datatables all wrong?
here is my controller
<?php
namespace App\Controllers\Dashboards;
use App\Controllers\Controller;
class AdminDashboardController extends Controller
{
public function listAction($request, $response)
{
return $this->view->render($response,'dashboards/admin.html.twig');
}
}
here is my view
{% extends 'base.html.twig' %}
{% block body %}
<h1>this will be the admin dash</h1>
{% endblock %}
{% block javascripts %}
{{parent()}}
<script>
$(document).ready(function() {
$.ajax({
url: "../src/App/ajax/getAll.php",
type: "GET",
dataType: 'json',
}).done(function (result) {
console.log(result);
}).fail(function (jqXHR, textStatus, error) {
console.log("getArchivedPo: " + error);
});
});
</script>
{% endblock %}
and here is my ajax
<?php
$conn = $container['db'];
//$conn = $container->get('db');
$admin = array();
if ($conn) {
$sql = "SELECT trannum,
trantype,
tranbatch,
trandate,
username,
trvnum,
tranaccount,
tranamt,
transtatus,
trannumdocs
FROM BD.BDPTV
INNER JOIN BD.BDUSERS
ON BD.BDUSERS.usernumber = BD.BDPTV.tranuser
WHERE transtatus NOT IN ( 3, 7, 5 )";
$stmt = db2_prepare($conn, $sql);
if ($stmt) {
$result = db2_execute($stmt);
if ($result) {
while ($row = db2_fetch_array($stmt)) {
$admin[] = array(
'trnum' => $row[0],
'trtyp' => $row[1],
'trbatch' => $row[2],
'trdate' => $row[3],
'usrnam' => $row[4],
'trvnum' => $row[5],
'tracct' => $row[6],
'tramt' => $row[7],
'trvsts' => $row[8],
'numdoc' => $row[9]
);
}
} else {
error_log(db2_stmt_errormsg($stmt));
}
} else {
error_log(db2_stmt_errormsg($stmt));
}
} else {
error_log(db2_conn_errormsg());
}
$admin['data'] = $admin;
echo json_encode($admin);
Also, righ tnow I'm getting this error <b>Notice</b>: Undefined variable: container in <b>/www/slim/htdocs/bd/src/App/ajax/getAll.php</b> on line <b>3</b><br />
{"data":[]}
So should I put my ajax somewhere else?
my routes
<?php
$app->get('/', 'HomeController:indexAction')->setName('home');
$app->get('/admindash', 'AdminDashboardController:listAction')->setName('admindash');
$app->get('/ajaxrequest', [AdminDashboardController::class, 'ajax'])->setName('myAjaxRequest');
$app->get('/poentry', 'PoController:entryAction')->setName('poentry');
$app->get('/poedit', 'PoController:editAction')->setName('poedit');
$app->get('/poarchive', 'PoController:archiveAction')->setName('poarchive');
$app->get('/voucherwithpo', 'VoucherController:entryWithPoAction')->setName('voucherwithpo');
$app->get('/voucherwithoutpo', 'VoucherController:entryWithOutPoAction')->setName('voucherwithoutpo');
$app->get('/edituser', 'UserController:editAction')->setName('edituser');
$app->get('/adduser', 'UserController:addAction')->setName('adduser');
$app->get('/poarchivedash', 'ArchivePoDashboardController:listAction')->setName('poarchivedash');
$app->get('/voucherarchivedash', 'ArchiveVoucherDashboardController:listAction')->setName('voucherarchivedash');
$app->get('/notedash', 'NoteDashboardController:listAction')->setName('notedash');

Firstly about the error message you get: You need to include parts of the slim start up where you define the container and the $container['db'] otherwise that cannot be found.
But now the solution where you do not have an additional php file:
You should add a route for the ajax request you could do that in the AdminDashboardController as well
class AdminDashboardController {
// listAction function
function ajax($request, $response) {
// copy from your ajax file
return $response->withJson($admin);
}
}
then add a route:
$app->get('/ajaxrequest', 'AdminDashboardController:ajax')->setName('myAjaxRequest');
And then you can reference that route inside your twig file
$(document).ready(function() {
$.ajax({
url: "{{ path_for('myAjaxRequest') }}",
type: "GET",
dataType: 'json',
}).done(function (result) {
console.log(result);
}).fail(function (jqXHR, textStatus, error) {
console.log("getArchivedPo: " + error);
});
});

Related

Wp return result from sql using AJAX

I need some help i am making a wordpress plug in.
when i try to get some rows from sql thro a AJAX post i will get nothing back.
Even if i try just to return a string it will stays empty.
I Dont get any error .
Thank you so much for helping.
Script:
jQuery(document).ready(function($){
$('.country').change(function(){
alert("asasasas");
var country_id = $(this).val();
alert(country_id);
$.ajax({
cache: false,
type: "POST",
url: "<?php echo plugin_dir_url('brandstof-ajax.php'); ?>",
data: {
action : 'my_action',
id : country_id,
},
success: function(data)
{
alert("sucessss");
alert(data);
console.log(data);
jQuery('.brandstof').html(data);
},
error: function(errorThrown){
alert(errorThrown);
}
});
});
my function:
<?php
add_action('wp_ajax_nopriv_ajax_request', 'my_action');
add_action('wp_ajax_ajax_request', 'my_action');
function my_action() {
$country_id = $_REQUEST['id'];
global $wpdb;
$qbrandstof = $wpdb->get_results("SELECT distinct brandstof FROM autos where jaar='2023'");
foreach($qbrandstof as $brandstof)
{
?>
<option value="<?php echo $brandstof["brandstof"]; ?>"><?php echo $brandstof["brandstof"]; ?></option>
<?php }
die();
}
?>
You should register and localize your script.
Example: -
function my_enqueue() {
wp_enqueue_script( 'ajax-script', plugin_dir_url( __FILE__ ) . '/js/my-ajax-script.js', array('jquery') );
wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
then you can use that javascript object in your script to call the ajax callback function remember to add action in ajax request.
in your case you have used
add_action('wp_ajax_nopriv_ajax_request', 'my_action');
add_action('wp_ajax_ajax_request', 'my_action');.
then action will 'ajax_request'.
try out this code.
jQuery(document).ready(function($){
$('.country').change(function(){
alert("asasasas");
var country_id = $(this).val();
alert(country_id);
$.ajax({
cache: false,
type: "POST",
url: my_ajax_object.ajax_url,
data: {
action : 'ajax_request',
id : country_id,
},
success: function(data)
{
alert("sucessss");
alert(data);
console.log(data);
jQuery('.brandstof').html(data);
},
error: function(errorThrown){
alert(errorThrown);
}
});
})
});
Reference :- https://developer.wordpress.org/reference/hooks/wp_ajax_action/

Updating the image in laravel 8 + inertia, validation error even the fields are filled

I'm working with Laravel 8 + inertiajs. I can create a product with or without an image. But when I try to update a product and upload a new image, the validation looks for the required field even they're already filled.
here is my input field:
<input name="images" type="file" #input="form.images = $event.target.files[0]" />
in my vue:
props: {
product: Object,
categories: Array
},
data() {
return {
form: this.$inertia.form({
name: this.product.name,
category_id: this.product.category_id,
description: this.product.description,
date: this.product.date,
images: this.product.images
})
}
},
methods: {
update() {
this.form.put(this.route('products.update', this.product.id, {
preserveState: true
}))
},
}
})
my update controller:
public function update(UpdateProductRequest $request, Product $product)
{
$inputs = $request->validated();
if ($request->hasFile('images')) {
$filename = $request->images->getClientOriginalName();
$file = $request->images->storeAs(('images'), $filename);
$product->images = $file;
$inputs['images'] = $product->images;
}
$product->name = $inputs['name'];
$product->category_id = $inputs['category_id'];
$product->description = $inputs['description'];
$product->date = $inputs['date'];
$product->update();
session()->flash('flash.banner', 'Product Updated Successfuly');
session()->flash('flash.bannerStyle', 'success');
return redirect()->route('products.index');
}
multipart/form-data request is not natively supported in some languages for the put,patch or delete methods. The workaround here is to simply upload files using post instead.
Some frameworks, such as Laravel and Rails, support form method spoofing, which allows you to upload the files using post, but have the framework handle the request as a put or patch request. This is done by including a _method attribute in the data of your request.
Inertia.post(`/users/${user.id}`, {
_method: 'put',
avatar: form.avatar,
})

Exception: Service 'voltService' wasn't found in the dependency injection container

I am trying to replicate the examples in the Volt tutorial here, using the basic example of phalcon here, so nothing complicated.
So I created this app/controllers/PostsControllers like this:
<?php
use Phalcon\Mvc\Controller;
class PostsController extends Controller
{
public function indexAction()
{
/* $post = Post::findFirst();
$menu = Menu::findFirst();*/
$post = array("title"=>"The titre");
$menu = "menu1";
$this->view->show_navigation = true;
$this->view->menu = $menu;
$this->view->title = $post["title"];
$this->view->post = $post;
// Or...
$this->view->setVar('show_navigation', true);
$this->view->setVar('menu', $menu);
$this->view->setVar('title', $post["title"]);
$this->view->setVar('post', $post);
}
}
And its corresponding app/views/posts/index.phtml like this:
{# app/views/posts/show.phtml #}
<!DOCTYPE html>
<html>
<head>
<title>{{ title }} - An example blog</title>
</head>
<body>
{% if show_navigation %}
<ul id='navigation'>
{% for item in menu %}
<li>
<a href='{{ item.href }}'>
{{ item.caption }}
</a>
</li>
{% endfor %}
</ul>
{% endif %}
<h1>{{ post.title }}</h1>
<div class='content'>
{{ post.content }}
</div>
</body>
</html>
I also registered volt in my bootstrap file (/public/index.php) which looks like that:
<?php
use Phalcon\Loader;
use Phalcon\Mvc\View;
use Phalcon\Mvc\Application;
use Phalcon\Di\FactoryDefault;
use Phalcon\Mvc\Url as UrlProvider;
use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;
use Phalcon\Mvc\View\Engine\Volt;
// Register an autoloader
$loader = new Loader();
$loader->registerDirs(
[
"../app/controllers/",
"../app/models/",
]
);
$loader->register();
// Create a DI
$di = new FactoryDefault();
// Setup the view component
$di->set(
"view",
function () {
$view = new View();
$view->setViewsDir("../app/views/");
$view->registerEngines(
[
'.volt' => 'voltService',
]
);
return $view;
}
);
// Setup a base URI so that all generated URIs include the "tutorial" folder
$di->set(
"url",
function () {
$url = new UrlProvider();
$url->setBaseUri("/care/");
return $url;
}
);
$application = new Application($di);
try {
// Handle the request
$response = $application->handle();
$response->send();
} catch (\Exception $e) {
echo "Exception: ", $e->getMessage();
}
But when I try to access to /posts directory (localhost/care/posts) I get the following error:
Exception: Service 'voltService' wasn't found in the dependency injection container
I checked if Volt service was not already declared in Services.php as it is said in a similar post here but it is not.
Thank you
The issue is with this block of code. You are telling your view that it should use the volt extension and process it using a service called voltService.
// Setup the view component
$di->set(
"view",
function () {
$view = new View();
$view->setViewsDir("../app/views/");
$view->registerEngines(
[
'.volt' => 'voltService',
]
);
return $view;
}
);
If you look at your snippet, there is no service called voltService defined.
However if you add this to your services, it should work:
// Register Volt as a service
$di->set(
'voltService',
function ($view, $di) {
$volt = new Volt($view, $di);
$volt->setOptions(
[
'compiledPath' => '../app/compiled-templates/',
'compiledExtension' => '.compiled',
]
);
return $volt;
}
);
Reference: https://docs.phalconphp.com/en/3.2/volt#setup

How to Redirects with a Drop Down?

I have parent page and there are two child view _sectionhead.php and _classteacher.php i need to renderPartial to those child view when user select from dropdwon how can do this
this is my create from
IF there is any other way i like to know it.i need quick help
In view:
<?php Yii::app()->clientScript->registerScript('some-name', "
$('select').on('change', function (event) {
var url = $(event.currentTarget).val();
if (url != 0)
$.get(url, function (data) {
$('#result').html(data);
});
});", CClientScript::POS_READY) ?>
<?php echo
CHtml::dropDownList("param", "select here", [
'Select here',
$this->createUrl('/testing/action1') => "Add class teacher",
$this->createUrl('/testing/action2') => "Add class techer"
]) ?>
<div id="result"></div>
Assuming you are doing in HTML ,Add below in HTML code
<option onClick="fnCallPage('classteacher')">class teacher</option>
<option onClick="fnCallPage('Section')">Section</option>
Add below in Javascript tag :
function fnCallPage(param){
//Javascript code for sending
}
Based on #Fraz solution:
HTML:
<option onClick="fnCallPage('_classteacher')">class teacher</option>
<option onClick="fnCallPage('_sectionhead')">Section</option>
<div id="divContainerPartial"></div> <!-- View rendered container -->
Javascript:
function fnCallPage(param){
$.ajax({
url: '<?php echo Yii::app()->createUrl('yourModel/renderPageByAjax');?>/' + param,
type: 'GET',
success: function(html){
$('#divContainerPartial').html(html);
},
error: function(data){
alert('Error loading a '+param+' view.');
}
});
}
Controller:
/**
* #param $view String : View name to render.
*/
public function actionRenderPageByAjax($view)
{
$params = array(); // Variables to view.
$this->renderPartial('//myFolderView/'.$view, array(
'params' => $params,
), false, true);
}

How to bind yii action in extjs

I am working in extjs+Yii. My yii action is:
public function actionCreateNew()
{
$record=Qbquestionset::model()->findAllByAttributes(array("questionPaperId"=>1));
foreach($record as $rec)
{
if($rec==NULL)
{
echo"Paper does not exists";
}
else
{
echo $rec->questionId;
$record1=Qbquestion::model()->findByAttributes(array("questionId"=>$rec->questionId));
echo "</br>". $record1->question;
echo "</br>".CJSON::encode(array("Question"=>$record1->question));
}
}
}
This function is retrieving Questions and sending it in json format.
Now in extjs I had created model, view, controller and view as=
Model= Question.js
Ext.define('Balaee.controller.Question',
{
extend:'Ext.app.Controller',
stores:['Question'],
models:['Question','QuestionOption'],
views:['question.Question','question.QuestionView'],
init:function()
{
console.log("inside Question controller");
},
});
Store.js===
Ext.define('Balaee.store.Question', {
extend: 'Ext.data.Store',
model: 'Balaee.model.Question',
autoLoad: true,
proxy:{
type: 'ajax',
//url:'data/poll.json',
api: {
//read: 'data/question.json',
read: 'http://localhost/NewQuestion/index.php?r=QuestionBank/qbpaper/CreateNew',
},
reader: {
type: 'json',
//root: 'questions',
}
}
});
View=== questionView.js
Ext.define('Balaee.view.question.QuestionView',
{
extend:'Ext.view.View',
id:'QuestionViewId',
alias:'widget.questionView',
store:'Question',
config:
{
tpl:'<tpl for=".">'+
'<div id="main">'+
'</br>'+
'<b>Question :-</b> {Question}</br>'+
//'<p>-------------------------------------------</p>'+
//'<tpl for="options">'+ // interrogate the kids property within the data
//'<p>&nbsp&nbsp<input type="radio" name="opt" >&nbsp{option}</p>'+
//'</tpl></p>'+
'</div>'+
'</tpl>',
itemSelector:'div.main',
}
});//
So I am binding yii action to store by mentioning its url. But store is not retrieving any value. So what changes are needed to retrieve yii optputs in extjs store?
One problem I can see is with your Yii action. You should return JSON result, while you returning something weird.
Try this:
public function actionCreateNew()
{
$record = Qbquestionset::model()->findAllByAttributes(array("questionPaperId" => 1));
$result = array();
foreach($record as $rec) {
if ($rec != NULL) {
$result[] = $record1->question;
}
}
echo CJSON::encode(array(
'success' => true,
'root' => $result,
'total' => count($result)
));
}
You should also define root: 'root' property of reader.