How to Redirects with a Drop Down? - yii

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

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/

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

AJAX Cascading with MVC4

I used the below method for doing Async postback using AJAX. This works fine on clicking submit. But i would like to know, is that possible to call various ActionMethods in a controller via AJAX.
I would like to implement something like cascading dropdown. How to call different ActionMethod via AJAX on dropdown value change?
Here is the code which call only one ActionMethod on submitting form.
View
#{
ViewBag.Title = "Index";
var options = new AjaxOptions()
{
Url = Url.Action("Index", "City"),
LoadingElementId = "saving",
LoadingElementDuration = 2000,
Confirm = "Are you sure you want to submit?"
};
}
<h2>Index</h2>
#using (Ajax.BeginForm(options))
{
<div id="saving">Loading...</div>
#Html.DropDownList("Countries",ViewBag.Countries as SelectList)<input type="submit" />
}
Controller
public ActionResult Index()
{
IEnumerable<SelectListItem> selectListItems = new []
{
new SelectListItem{ Text = "US",Value = "1" }
};
ViewBag.Countries = selectListItems;
return View();
}
public ActionResult GetState(string countryId)
{
IEnumerable<SelectListItem> selectListItems = new[]
{
new SelectListItem { Text = "Tennesse", Value = "1" },
new SelectListItem { Text = "Newyork", Value = "2" }
};
return View();
}
The answer to your first question "is that possible to call various ActionMethods in a controller via AJAX" is a big yes. You may call any action method from your controller through Ajax though the only result generated depends on various things like whether you send a view or partial view or JSON result.
for your next question :
I will be posting some codes
Controller.cs
public JsonResult getCity(string country)
{
var temp = (from cntry in db.Table3.OrderBy(s => s.country)
where (string.Compare(cntry.country, country) == 0)
select cntry.city).ToList();
return Json(temp, JsonRequestBehavior.AllowGet);
}
View
<h1>
Countries</h1>
<select name="countries" class="combo">
<option value=""></option>
#{
foreach (var t in (List<string>)ViewBag.countries)
{
<option value=#t>#t</option>
}
}
</select>
<h1>
State</h1>
<select name="city" class="combo2">
</select>
<div id="tese">
</div>
#*
The following jquery code finds the selected option from country dropdown
and then sends an ajax call to the Home/getcity method
and finally populate it to the city dropdown
*#
<script type="text/javascript">
$('body').on('change', '.combo', function () {
var selectedValue = $(this).val();
alert(selectedValue);
$.get("/Home/getcity", { country: selectedValue }, function (data) {
$("#tese").html(data);
$(".combo2").html("<option value = \"\"></option>")
$.each(data, function (index, value) {
$(".combo2").append("<option value = \"" + value + "\">" + value + "</option>");
});
$(".combo2").html()
});
});
</script>
This will show a dropdown of countries list. Once a country is selected it will render a new dropdown of city list
public JsonResult getCity(string country)
{
var temp = (from cntry in db.Table3.OrderBy(s => s.country)
where (string.Compare(cntry.country, country) == 0)
select cntry.city).ToList();
return Json(temp, JsonRequestBehavior.AllowGet);
}
View
<h1>
Countries</h1>
<select name="countries" class="combo">
<option value=""></option>
#{
foreach (var t in (List<string>)ViewBag.countries)
{
<option value=#t>#t</option>
}
}
</select>
<h1>
State</h1>
<select name="city" class="combo2">
</select>
<div id="tese">
</div>
#*
The following jquery code finds the selected option from country dropdown
and then sends an ajax call to the Home/getcity method
and finally populate it to the city dropdown
*#
<script type="text/javascript">
$('body').on('change', '.combo', function () {
var selectedValue = $(this).val();
alert(selectedValue);
$.get("/Home/getcity", { country: selectedValue }, function (data) {
$("#tese").html(data);
$(".combo2").html("<option value = \"\"></option>")
$.each(data, function (index, value) {
$(".combo2").append("<option value = \"" + value + "\">" + value + "</option>");
});
$(".combo2").html()
});
});
</script>

How to add a new ZF2' Zend\Form\Element within jQuery ajax

I want to add a new ZF2' Zend\Form\Element within jQuery ajax. But while I use the Zend Form , I don't know how to make it. This is the add.phtml file.
<script type="text/javascript">
$(document).ready(function(){
$(".pid").change(function(){
var id = $('.pid').val();
var $_this = $(this);
$.ajax({
type:"POST",
url:"<?php echo $this->url('Element/default',array('action'=>'change'));?>",
data:"pid="+id,
dataType:'json',
async:false,
success:function(data){
if(data.response){
//here I want to add a new select component after select conponent "pid" using like "$this->formRow($form->get('mid'))" or else .
}
}
});
});
});
</script>
the following is the remaining part of the html.
<?php
$title = 'add';
$this->headTitle($title);
?>
<h1><?php echo $this->escapeHtml($title); ?></h1>
<?php
$form = $this->form;
$form->setAttribute('action', $this->url(
'Element/default',
array(
'action' => 'add'
)
));
$form->prepare();
echo $this->form()->openTag($form);
echo $this->formRow($form->get('pid'));
echo $this->formRow($form->get('name'));
echo $this->formRow($form->get('desc'));
echo $this->formSubmit($form->get('submit'));
echo $this->form()->closeTag();
How do I add a new zend form element within jquery ajax ? Thanks.
You have script to receive data using ajax and view/html should be received by this script. You need controller/action to rendering data and return as response.
use Zend\View\Model\JsonModel;
//some controller
public function changeAction(){ // your requested action
//1. get partial helper to rendering html;
$partial = $this->getServiceLocator()->get('ViewHelperManager')->get('partial');
$form = new Form();// your form
//2. render html
$html = $partial('path/to/your/file/phtml',['form'=>$form]);
//3. return data as JSON because in your ajax configuration dataType: 'json'
return new JsonModel([
'html' => $html,
]);
}
in your js success function should be:
success:function(data){
if(data.html){
$_this.find('blockToAppend').append(data.html);
}
}

Ajax.ActionLink parameter from DropDownList

I have the following view part:
<div class="editor-label">
#Html.LabelFor(model => model.Type)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.Type, ElangWeb.Helpers.ModelHelpers.GetExerciseTypes())
</div>
I want to have a link which will generate some partialview based on my model's Type property which is an Enum (I return different partial views based on the type),
I've added the following link:
#Ajax.ActionLink("AddExerciseItem",
"AddExerciseItem",
"Exercise",
new { type=#Model.Type},
new AjaxOptions() { HttpMethod="GET", InsertionMode = InsertionMode.InsertBefore, UpdateTargetId="ExerciseItems"})
My controller action is defined as follows:
public ActionResult AddExerciseItem(ExerciseType type)
{
return PartialView("ExerciseItemOption", new ExerciseItemOption());
}
I however does not work because I have the exeption "Object reference not set to an instance of an object" for my Model. How to resolve this issue?
You could use a normal link:
#Html.ActionLink(
"AddExerciseItem",
"AddExerciseItem",
"Exercise",
null,
new { id = "add" }
)
that you could unobtrusively AJAXify:
// When the DOM is ready
$(function() {
// Subscribe to the click event of the anchor
$('#add').click(function() {
// When the anchor is clicked get the currently
// selected type from the dropdown list.
var type = $('#Type').val();
// and send an AJAX request to the controller action that
// this link is pointing to:
$.ajax({
url: this.href,
type: 'GET',
// and include the type as query string parameter
data: { type: type },
// and make sure that you disable the cache because some
// browsers might cache GET requests
cache: false,
success: function(result) {
// When the AJAX request succeeds prepend the resulting
// markup to the DOM the same way you were doing in your
// AJAX.ActionLink
$('#ExerciseItems').prepend(result);
}
});
return false;
});
});
Now your AddExerciseItem controller action could take the type parameter:
public ActionResult AddExerciseItem(string type)
{
...
}