Wp return result from sql using AJAX - sql

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/

Related

Error Ajxa call in asp.net xhr.send( options.hasContent && options.data || null )

I tried to so hard to solve it but couldn't.
I got error
xhr.send( options.hasContent && options.data || null )
while saving data this error shows in Jquery.js.
Code is working perfectly in debug mode in vs 2022. I can save data in debug mode. But when
I compile (Publish) this project. I hosted in IIS and every things working perfectly but not in this form When I try to post data then I got same error.
I tried to send header but not working..
var token =
$('input:hidden[name="__RequestVerificationToken"]').val();
headers: { RequestVerificationToken: token },
var detailsList = new Array();
var detailsObj = new Object();
$("#tblDropItem tbody tr").each(function () {
let row = $(this);
let itemId = Number(row.find('.item_detl').attr('purItem_id'));
detailsObj = {
ItemId: itemId,
ItemName: row.find(".item_detl").val(),
Quantity: parseFloat(row.find(".quantity_detl").val()),
UnitId: Number(row.find('.unit_detl').attr('unit_id')),
Rate: parseFloat(row.find(".rate_detl").val()),
Amount: parseFloat(row.find(".amount_detl").val()),
}
if (detailsObj.ItemName) {
detailsList.push(detailsObj);
}
});
var postData = {
PurMode: $("#PurMode").val(),
PurDate: $("#PurDate").val(),
SupId: $("#SupId option:selected").val(),
SubAmount: parseFloat($("#SubAmount").val()),
Discount: parseFloat($("#DiscountPercent").val()),
DiscountAmount: parseFloat($("#Discount").val()),
TotalAmount: parseFloat($("#TotalAmount").val()),
Remarks: $("#Remarks").val(),
Taxable: parseFloat($("#Taxable").val()),
VatAmount: parseFloat($("#VatAmount").val()),
VATable: parseFloat($("#VATable option:selected").val())
PurchaseDetailItemList: detailsList,
__RequestVerificationToken: $("input[name=__RequestVerificationToken]").val(),
}
$.ajax({
type: "POST",
url: "/Purchase/SavePurchase",
dataType: 'JSON',
data: postData,
async:false,
success: function (result) {
toastr.success('Data Saved Successfully');
window.location = "#Url.Content("~/Purchase/Index")";
},
error: function (result) {
toastr.error("Cann't Save Data.");
}
});
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult SavePurchase(PurchaseDTO model)
{
if (!ModelState.IsValid)
{
return Json("error");
}
//code...
}
Can you please suggest any mistake..
Everything is correct, maybe you have hosted incorrectly in iis, make sure your post url is valid in console.

Yii2: How to show file uploading progress? [duplicate]

This question already has an answer here:
Track ajax post progress for fileupload using jquery ajax and FormData
(1 answer)
Closed 4 years ago.
I use Yii2 framework. I would like to show file uploading progress. I don't need complex interface with drag-n-drop or preview. Only progress bar and possible 'cancel' button. Could you point me to a simple example? Thanks.
Eventually I made it with jQuery ajax.
js:
function upload() {
var input = $('#archiveInput');
var files = input.prop('files');
if (files.length > 0) {
var data = new FormData();
data.append('archive', files[0]);
$.ajax({
url: input.data('upload-url'),
type: 'POST',
data: data,
cache: false,
contentType: false,
processData: false,
success: function () {
alert('Upload Complete');
},
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener('progress', onProgress);
return myXhr;
}
}
});
}
}
function onProgress(ev) {
if (ev.lengthComputable) {
var progress = parseInt(ev.loaded / ev.total * 100, 10);
$("#progress .progress-bar").css(
"width",
progress + "%"
);
}
}
php controller:
public function actionUpload($idSupply)
{
$directory = FileHelper::normalizePath(Yii::getAlias('#app') . '/uploads/' . $idSupply);
if (!is_dir($directory)) {
FileHelper::createDirectory($directory);
}
$fileName = 'archive.zip';
$filePath = $directory . DIRECTORY_SEPARATOR . $fileName;
if (is_file($filePath)) {
unlink($filePath);
}
move_uploaded_file($_FILES['archive']['tmp_name'], $filePath);
}

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

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);
});
});

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.