I want to ask how to refresh the modal after I submit the form in another action? I use yii2.
Here is my code :
index.php:
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\bootstrap\Modal;
/* #var $this yii\web\View */
/* #var $searchModel backend\models\KategoriSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Kategoris';
$this->params['breadcrumbs'][] = $this->title;
$this->registerJs("
$('#myModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget)
var modal = $(this)
var title = button.data('title')
var href = button.attr('href')
modal.find('.modal-title').html(title)
modal.find('.modal-body').html('<i class=\"fa fa-spinner fa-spin\"></i>')
$.post(href).done(function( data ) {
modal.find('.modal-body').html(data)
});
})
");
?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'kateg_id',
'kateg_nama',
[
'class' => 'yii\grid\ActionColumn',
'template' => '{size} {view} {update} {delete}',
'buttons' => [
'size' => function($url, $model, $key) {
return Html::a(Html::tag('i','',
[
'class'=>'fa fa-th-list',
'title'=>'Size'
]),
[
'size',
'id'=>$model->kateg_id,
],
[
'data-toggle'=>'modal',
'data-target'=>'#myModal',
'data-title'=>'Size',
]);
}
]
],
],
]); ?>
<?php
Modal::begin([
'id' =>'myModal',
'header' => '<h4 class="modal-title">...</h4>',
'footer' => Html::button('Close', ['class' => 'btn btn-default','data-dismiss'=>'modal']),
]);
Modal::end();
?>
The size button on my grid view will show the modal that returns the render ajax from action size in my controller.
After that here is my size view:
$form = ActiveForm::begin(); ?>
<?= $form->field($model, 'ukuran')->textInput(['id'=>'ukuran']) ?>
<?= $form->field($model, 'kateg_id')->textInput(['id'=>'kategori','type'=>'hidden','value'=>$id]) ?>
<div class="form-group">
<?= Html::button('Tambah', [
'class' => 'btn btn-primary',
'onclick' =>'
$.post({
url: "' . Url::to(['kategori/size']) . '?id="+$("#kategori").val(),
data: {ukuran: $("#ukuran").val()},
success: function(res){
alert("PROCESS_SUCCES");
}
});
',
]) ?>
</div>
<?php ActiveForm::end(); ?>
<?php Pjax::begin(['id' => 'pjax-grid-view']); ?>
<div id="grid">
<?= GridView::widget([
'dataProvider' => $dataProvider,
// 'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'ukuran_id',
'ukuran',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
<?php Pjax::end(); ?>
I'm trying to add refresh after alert but it does not work. It will close the modal and back to index again.
So I'm confused what it should be?
$.post({
url: "' . Url::to(['kategori/size']) . '?id="+$("#kategori").val(),
data: {ukuran: $("#ukuran").val()},
success: function(res){
alert("PROCESS_SUCCES");
}
});
I noticed in your .post call, you don't do anything with the res that's passed as the parameter of the success function. You just alert "PROCESS_SUCCES" (is this a macro for something?), and it stops. To modify elements on your page, you would want to select one and use the .html() or .val() functions to change it. Something like this:
$.post({
url: "' . Url::to(['kategori/size']) . '?id="+$("#kategori").val(),
data: {ukuran: $("#ukuran").val()},
success: function (res) {
alert("PROCESS_SUCCES");
$("#my_output_area").html(res);
}
});
Alternatively, you can use $.ajax() instead of $.post().
$.ajax({
type: "post",
url: "' . Url::to(['kategori/size']) . '?id="+$("#kategori").val(),
data: {ukuran: $("#ukuran").val()},
success: function (res) {
alert("PROCESS_SUCCES");
$("#my_output_area").html(res);
}
});
Related
I am trying to build a small program on a webpage that shows a drop-down list input type with the makes of cars (Ford and BMW in this case). Once a selection is made, the user clicks the submit button and below the form, a list of models specific to the make will appear in the results div.
I was provided with 4 files:
index.php:
<form id="form">
<label for="make">
Make
<select name="make" id="make">
<option value="" selected="selected">None</option>
<option value="Ford">Ford</option>
<option value="BMW">BMW</option>
</select>
</label>
<input name="submit" value="submit" type="submit" id="submit">
</form>
<div id="results">
</div>
<script src="js/main.js"></script>
data.php:
<? php
function data() {
$data = array(
array(
'make' => 'Ford',
'model' => 'Fiesta'
),
array(
'make' => 'Ford',
'model' => 'Focus'
),
array(
'make' => 'Ford',
'model' => 'Mustang'
),
array(
'make' => 'BMW',
'model' => '320'
),
array(
'make' => 'BMW',
'model' => 'X3'
),
array(
'make' => 'BMW',
'model' => 'X5'
),
);
}
ajax.php:
<?php
require_once( 'data.php' );
$data = data();
$json_data = array();
And main.js:
$(document).ready(() => {
var run_ajax = function() {
results = $('#results');
$.ajax({
type: 'post',
url: 'ajax.php',
data: formData,
dataType: 'json',
beforeSend: function() {
},
success: function(response) {
},
});
}
$('#submit').on('submit', function(e) {
e.preventDefault();
run_ajax();
});
});
How do I access the data in data.php from main.js? I'd appreciate a thorough explanation of possible. Thank you in advance.
Every thing is done seeing your provided code you have to just connect them but first you need to change the data.php file to the following
<?php
function data() {
return array(
array(
'make' => 'Ford',
'model' => 'Fiesta'
),
array(
'make' => 'Ford',
'model' => 'Focus'
),
array(
'make' => 'Ford',
'model' => 'Mustang'
),
array(
'make' => 'BMW',
'model' => '320'
),
array(
'make' => 'BMW',
'model' => 'X3'
),
array(
'make' => 'BMW',
'model' => 'X5'
),
);}
then your ajax.php file to the following
<?php
require_once( 'data.php' );
$data = data();
$make = $_POST['make'];
// print_r($data);exit;
foreach($data as $car){
if(in_array($make,$car)){
$filtered[]=$car;
}
}
echo json_encode($filtered);
then change your main.js function to the following
$(document).ready(() => {
var run_ajax = function () {
results = $('#results');
$.ajax({
type: 'post',
url: 'ajax.php',
data: $("form").serialize(),
dataType: 'json',
beforeSend: function () {},
success: function (response) {
for (var key in
response) {
$("#results").append(" <div > Make: " + response[key]['make'] +
", Model:" + response[key]['model'] + " </div>");
}
},
});
}
$('#form').on('submit', function (e) {
e.preventDefault();
run_ajax();
});
});
hope that sorts out
EDIT
Actually, we have to send the select dropdown's selected make and filter out the cars with the same make to be responsed back and shown in the lower div have to change a few more things inside the ajax.php file
Your data() function must first return an array:
function data(){
$data = array('key'=>'value');
return $data;
}
Then echo or print() the json_encoded array:
$data = data();
echo json_encode($data);
Firstly your you dont need to define a function in your data.php file, since it is included in the ajax.php file, any variable there would be accessible
data.php:
<? php
$data = array(
array(
'make' => 'Ford',
'model' => 'Fiesta'
),
array(
'make' => 'Ford',
'model' => 'Focus'
),
array(
'make' => 'Ford',
'model' => 'Mustang'
),
array(
'make' => 'BMW',
'model' => '320'
),
array(
'make' => 'BMW',
'model' => 'X3'
),
array(
'make' => 'BMW',
'model' => 'X5'
),
);
the ajax.php file reads the data from data.php file filters the array and put the models of the selected make into a new array and echo as json string
ajax.php:
<?php
require_once('data.php');
$filtered_make = [];
$make = $_POST['make'];
foreach ($data as $car) {
if (strtolower($make) == strtolower($car['make'])) $filtered_make[] = $car['model'];
}
echo json_encode($filtered_make);
index.php:
<form id="form">
<label for="make">
Make
<select name="make" id="make">
<option value="" selected="selected">None</option>
<option value="Ford">Ford</option>
<option value="BMW">BMW</option>
</select>
</label>
<input name="submit" value="submit" type="submit" id="submit">
</form>
<div id="results">
</div>
<script src="http://www.izivote.com/res/js/jquery.min.js"></script>
<script src="js/main.js"></script>
onsuccess, in the main.js file, the returned list of models in the json object from ajax.php is put in a list and displayed in the result container
main.js:
$(document).ready(() => {
var run_ajax = function() {
results = $('#results');
var formData = $('#form').serialize();
$.ajax({
type: 'post',
url: 'ajax.php',
data: formData,
dataType: 'json',
beforeSend: function() {
},
success: function(response) {
var resultHTML = "<ul>";
for(var index in response){
resultHTML += "<li>" + response[index] + "</li>";
}
resultHTML += "</ul>";
results.html(resultHTML);
},
});
}
$('#form').on('submit', function(e) {
e.preventDefault();
run_ajax();
});
});
I hope this helps
return the data() as an array.
then encode the $data to json.
<?php
require_once( 'data.php' );
$data = data();
$json_data = json_encode(array());
and ajax:
$.ajax({
type: 'post',
url: 'ajax.php',
data: formData,
dataType: 'json',
beforeSend: function() {
},
success: function( response ) {
console.log(response); // check the return result
$.each(response, function(key, val){
$("#results").append("<div>Make:"+key+" , Model:"+val+"</div>");
});
},
error: function (msg) {
alert("Error: check console");
console.log(msg);
}
});
not tested but hope it helps
I have a Modal popup that has two fields, the first one is to submit some information a do an internal query into a database, and the second field on that Modal popup is to show the returned data. However when I test independently (without being a Modal) it worked, however when tested as a Modal it only submit the data but not show any result on the same modal, what could be wrong? Thanks.
This is the view that calls to the Modal popup.
<?php Pjax::begin() ?>
<p>
<?= Html::button('Quick Search', ['value' =>Url::to('index.php?r=site/mypopup'),'class' =>'btn btn-success', 'id'=>'modalButton']) ?>
</p>
<?php
Modal::begin([
'header'=> '<h4>My Modal Popup</h4>',
'id' => 'modal',
'size' => 'modal-lg',
]);
echo "<div id='modalContent'></div>";
Modal::end();
<?php Pjax::end(); ?>
This is the mypopup view:
<?php Pjax::begin(['enablePushState' => false]); ?>
<?php $form = ActiveForm::begin(['id' => 'mypopup-form', 'options' => ['data-pjax' => true],]); ?>
<?= $form->field($model, 'pattern')->textArea(['rows' => 1]) ?>
<div class="form-group">
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary', 'name' => 'mypopup-button']) ?>
</div>
<?php
echo "<pre>";
//SECOND FIELD
print_r($model->data);
?>
<?php ActiveForm::end(); ?>
<?php Pjax::end(); ?>
This is the controller of mypoup:
public function actionMypopup()
{
$model = new PopupForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->insertPopup();
return $this->renderAjax('mypopup', ['model' => $model]);
} else {
return $this->renderAjax('mypopup', ['model' => $model]);
}
}
This is the js file:
$(function(){
$('#modalButton').on('click', function(){
$('#modal').modal('show')
.find('#modalContent')
.load($(this).attr('value'));
});
$(document).ajaxComplete(function (event, xhr, settings) {
alert(xhr.getResponseHeader());
});
});
I have overcome the issue by modifying two parts:
First of all I have created a jQuery beforeSubmit method in the main.js file, so it wouldn't refresh the page and submit the form via ajax.
This code code goes below the previous code on the js file.
$('body').on('beforeSubmit', 'form#mypopup-form', function() {
var form = $(this);
if (form.find('.has-error').length) {
return false;
}
$.ajax({
url: form.attr('action'),
type: 'post',
data: form.serialize(),
success: function(data) {
$(form).find('.results').html(data);
return false;
});
}
});
Second, then after it will call the ajax to form action; and in the view I have added a condition to check if its posting some data from ajax and then display the results in div name results.
This code goes above all the code on the mypopup file:
<?php if(isset($_POST['MyPopupForm']))
{
echo "<pre>";
print_r($model->data);
echo '</pre>';exit();
}?>
and on the same file at the end:
<div class="results"></div>
<?php ActiveForm::end(); ?>
<?php Pjax::end(); ?>
By using kartik select2 plugins in Yii2, I try to make dependence dropdown for country and states.
Form field for country and states:
$url = yii\helpers\Url::toRoute('op-client/lists');
$this->registerJs($this->render('script.js'), \yii\web\VIEW::POS_READY);
$form->field($model, 'country_id')->widget(Select2::classname(), [
'data' => $countryData,
'language' => 'en',
'options' => ['placeholder' => 'Select'],
'pluginOptions' => [
'allowClear' => true,
],
'pluginEvents' =>
[
'change' => 'function()
{
getstate
(
$("#select2-opclient-country_id-container").val(),
"'.$url.'"
)
}',
],
]).'
$form->field($model, 'states_id')->widget(Select2::classname(), [
'data' => $statesData,
'language' => 'en',
'options' => ['placeholder' => 'Select'],
'pluginOptions' => [
'allowClear' => true,
],
]).'
Script.js
function getstate($countryid,url)
{
//console.log(startdate + enddate);
var csrfToken = $('meta[name="csrf-token"]').attr("content");
$.ajax({
type:"POST",
cache:false,
url:url,
data:{countryid:countryid, _crsf:csrfToken},
success:function(data){
$("#select2-opclient-states_id-container").val(data);
},
})
}
Controller:
public function actionLists()
{
$request = Yii::$app->request;
$country = $request->post('countryid');
$countStates = OpStates::find()
->where(['country_id' => $country])
->count();
$states = OpStates::find()
->where(['country_id' =>$country])
->all();
if($countStates > 0)
{
foreach($states as $state){
echo "<option value='".$state->id."'>".$state->state_name."</option>";
}
}
else
{
echo "<option></option>";
}
}
When I run the program, it show error "Uncaught ReferenceError: countryid is not defined".
But I thought i passed the countryid into it already? Where have I done wrong?
Any help/advice will be appreciated. Thankss
Please check below code,i think you did little mistake in country_id variable name.
public function actionLists()
{
$request = Yii::$app->request;
$country = $request->post('country_id');
$countStates = OpStates::find()
->where(['country_id' => $country])
->count();
$states = OpStates::find()
->where(['country_id' =>$country])
->all();
if($countStates > 0)
{
foreach($states as $state){
echo "<option value='".$state->id."'>".$state->state_name."</option>";
}
}
else
{
echo "<option></option>";
}
}
and here
function getstate(countryid,url)
{
//console.log(startdate + enddate);
var csrfToken = $('meta[name="csrf-token"]').attr("content");
$.ajax({
type:"POST",
cache:false,
url:url,
data:{countryid:countryid, _crsf:csrfToken},
success:function(data){
$("#select2-opclient-states_id-container").val(data);
},
})
}
It will solve your issue.
I have an HTML list and I want to change their order with drag and drop and also update in database. But I do not know how it is done. Can you helpl me? I used HTML5sortable plugin, but it does not update in db.
Here is my list:
<ul class="sortable grid" >
<?php
$images = get_children(array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'order' => 'ASC', 'orderby' => 'menu_order ID'));
$i = 0;
foreach ($images as $value) {
?>
<li style='list-style-type: none' >
<img src='<?php echo $value->guid;?>' width='90' />
<a class='btn btn-danger' href='#' onclick='deletePic(<?php echo $i;?>)'>
<i class='icon-trash icon-white'></i>
Delete
</a>
</li>
<?php $i++; } ?>
</ul>
write a ajax call inside sortupdate event handler
$('.sortable').sortable().bind('sortupdate', function() {
var menuId=[];
//store list id or some other unique field to identify your image into menuId variable
var request = $.ajax({
url: "script.php",
type: "POST",
data: { id : menuId },
dataType: "html"
});
});
I have this JS/jQuery code
window.onload = function(){
var request = $.ajax({
url: "../wp-content/plugins/woocommerce/admin/test.php",
type: "GET",
dataType: "html"
//data: {$lastid},
});
request.done(function(msg) {
$(".recent-orders").append(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
EDIT: This is the method where I get the $lastid.
<?php
function woocommerce_dashboard_recent_orders() {
$args = array(
'numberposts' => 8,
'orderby' => 'post_date',
'order' => 'ASC',
'post_type' => 'shop_order',
'post_status' => 'publish'
);
$orders = get_posts( $args );
if ($orders) :
echo '<ul class="recent-orders">';
foreach ($orders as $order) :
$this_order = new WC_Order( $order->ID );
echo '
<li>
<span id = "order-$order->ID" class="order-status '.sanitize_title($this_order->status).'">'.ucwords(__($this_order->status, 'woocommerce')).'</span> ' . get_the_time( __( 'l jS \of F Y h:i:s A', 'woocommerce' ), $order->ID ) . '<br />
<small>'.sizeof($this_order->get_items()).' '._n('item', 'items', sizeof($this_order->get_items()), 'woocommerce').' <span class="order-cost">'.__('Total:', 'woocommerce' ) . ' ' . woocommerce_price($this_order->order_total).'</span></small>
</li>';
endforeach;
$lastid = $order->ID;
echo '</ul>';
else:
echo '<p>' . __( 'There are no product orders yet.', 'woocommerce' ) . '</p>';
endif;
}
?>
That calls a php file called test.php.
test.php
<?php
//woocommerce_dashboard_recent_orders_realtime();
/**
* Init the dashboard widgets.
*
* #access public
* #return void
*/
function filter_where( $where = '' ) {
$oid = 2100;
$where = " AND ID > $oid";
return $where;
}
add_filter( 'posts_where', 'filter_where' );
$args = array(
'numberposts' => 8,
'orderby' => 'post_date',
'order' => 'DESC',
'post_type' => 'shop_order',
'post_status' => 'publish',
'suppress_filters' => FALSE
);
$orders = get_posts( $args );
if ($orders) :
foreach ($orders as $order) :
//echo " $order->ID";
$this_order = new WC_Order( $order->ID );
echo '
<li>
<span id = "order-$order->ID" class="order-status '.sanitize_title($this_order->status).'">'.ucwords(__($this_order->status, 'woocommerce')).'</span> ' . get_the_time( __( 'l jS \of F Y h:i:s A', 'woocommerce' ), $order->ID ) . '<br />
<small>'.sizeof($this_order->get_items()).' '._n('item', 'items', sizeof($this_order->get_items()), 'woocommerce').' <span class="order-cost">'.__('Total:', 'woocommerce' ) . ' ' . woocommerce_price($this_order->order_total).'</span></small>
</li>';
//echo (gettype($time3));
endforeach;
endif;
//}
?>
What I want to do is to pass the $lastid from the javascript to the test.php file and receive it as something like $lastid also.
I know I should post, but I'm having trouble using it. Can anyone lead me to the right method?
My CODE now
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" >
window.onload = function(){
//setInterval(function(){
//var lastid = '<?php echo $lastid; ?>';
//alert(lastid);
var request = $.ajax({
url: "../wp-content/plugins/woocommerce/admin/test.php",
type: "POST",
dataType: "html",
data: { lastid : '<?php echo $lastid; ?>'},
});
request.done(function(msg) {
$(".recent-orders").append(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
//addElement();
//},1000);
setInterval(function(){
},1000);
}
</script>
<?php
function woocommerce_dashboard_recent_orders() {
$args = array(
'numberposts' => 8,
'orderby' => 'post_date',
'order' => 'ASC',
'post_type' => 'shop_order',
'post_status' => 'publish'
);
$orders = get_posts( $args );
if ($orders) :
echo '<ul class="recent-orders">';
foreach ($orders as $order) :
$this_order = new WC_Order( $order->ID );
echo '
<li>
<span id = "order-$order->ID" class="order-status '.sanitize_title($this_order->status).'">'.ucwords(__($this_order->status, 'woocommerce')).'</span> ' . get_the_time( __( 'l jS \of F Y h:i:s A', 'woocommerce' ), $order->ID ) . '<br />
<small>'.sizeof($this_order->get_items()).' '._n('item', 'items', sizeof($this_order->get_items()), 'woocommerce').' <span class="order-cost">'.__('Total:', 'woocommerce' ) . ' ' . woocommerce_price($this_order->order_total).'</span></small>
</li>';
endforeach;
$lastid = $order->ID;
echo '</ul>';
else:
echo '<p>' . __( 'There are no product orders yet.', 'woocommerce' ) . '</p>';
endif;
}
?>
<?php
function filter_where( $where = '' ) {
$oid = 2110;
$where = " AND ID > $oid";
return $where;
}
$lastid = $_GET['lastid'];
add_filter( 'posts_where', 'filter_where' );
$args = array(
'numberposts' => 8,
'orderby' => 'post_date',
'order' => 'DESC',
'post_type' => 'shop_order',
'post_status' => 'publish',
'suppress_filters' => FALSE
);
$orders = get_posts( $args );
echo "LAST ID: $lastid";
if ($orders) :
foreach ($orders as $order) :
$this_order = new WC_Order( $order->ID );
echo '
<li>
<span id = "order-$order->ID" class="order-status '.sanitize_title($this_order->status).'">'.ucwords(__($this_order->status, 'woocommerce')).'</span> ' . get_the_time( __( 'l jS \of F Y h:i:s A', 'woocommerce' ), $order->ID ) . '<br />
<small>'.sizeof($this_order->get_items()).' '._n('item', 'items', sizeof($this_order->get_items()), 'woocommerce').' <span class="order-cost">'.__('Total:', 'woocommerce' ) . ' ' . woocommerce_price($this_order->order_total).'</span></small>
</li>';
endforeach;
endif;
remove_filter( 'posts_where', 'filter_where' );
//}
?>
I'm not sure if I understand if I understand your question, but it seems like your first page has already evaluated $lastId, most likely from an insert query... and you want to also set it to a javascript variable, while also using post method. Assuming all that this is how I would for the first page
<script>
var $lastid = <?php echo $lastid ?>;
...
window.onload = function(){
var request = $.ajax({
url: "../wp-content/plugins/woocommerce/admin/test.php",
type: "POST",
dataType: "html"
data: {"lastid":$lastid},
});
request.done(function(msg) {
$(".recent-orders").append(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
....
</script>
Then on the second page use this to access the post
<?php
$lastid = $_POST['lastid'];
?>
That is how you do post in php hope this helps.
Try the following in the original code
...
url: "../wp-content/plugins/woocommerce/admin/test.php?lastid=2098"
...
Then in test.php, access the variable using
$lastid = $_GET['lastid'];
There are several other ways that this can be done, this is just a quick and dirty method.
1. Send the variable:
Change:
//data: {$lastid},
to:
data: { lastid : '<?php echo $lastid; ?>'},
2. Get variable in test.php:
$lastid = $_GET['lastid'];
window.onload = function(){
var lastId = <?php echo $lastId; ?>;
var request = $.ajax({
url: "../wp-content/plugins/woocommerce/admin/test.php" + "?lastid=" + lastId,
type: "GET",
dataType: "html"
//data: {$lastid},
});
request.done(function(msg) {
$(".recent-orders").append(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
on test.php add this line
$lastId = $_GET['lastid'];