Passing Php Variable to another variable using ajax? - javascript

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'];

Related

How do I format this string with json encode?

To fill the value "items" in the script I need to get the individual order item names and prices and list them in the following format:
EventID::Price::Name::productID | EventID::Price::Name::productID
I don't know exactly how to output them in the format outlined above.
My code (to be added to functions.php)
add_action( 'woocommerce_thankyou', 'wg_tracking' );
function wg_tracking( $order_id ) {
$order = wc_get_order( $order_id );
$order_total = $order->get_total();
$code = $coupon->get_code();
$currency = $order->get_currency();
foreach ( $order->get_items() as $item_id => $item ) {
$total = $item->get_total();
$product_name = $item->get_name();
$item_id = $item->get_id();
} $items_list = //something here to order the data?
}
?>
<script>
(function(w,e,b,g,a,i,n,s){w['ITCVROBJ']=a;w[a]=w[a]||function(){
(w[a].q=w[a].q||[]).push(arguments)},w[a].l=1*new Date();i=e.createElement(b),
n=e.getElementsByTagName(b)[0];i.async=1;i.src=g;n.parentNode.insertBefore(i,n)
})(window,document,'script','https://analytics.webgains.io/cvr.min.js','ITCVRQ');
ITCVRQ('set', 'trk.programId', 777777);
ITCVRQ('set', 'cvr', {
value: '<?php echo $order_total ?>',
currency: '<?php echo $currency ?>',
language: 'de_DE',
eventId: 777777,
orderReference : '<?php echo $order_id ?>',
comment: '',
multiple: '',
checksum: '',
items: '<?php echo SOMETHING ?>',
voucherId: '<?php echo $code ?>',
});
ITCVRQ('conversion');
</script>
Based on the recommendation to use json encode, I've now got this.
add_action( 'woocommerce_thankyou', 'wg_tracking' );
function wg_tracking( $order_id ) {
//grab order
$order = wc_get_order( $order_id );
//grab woocommerce objects
$order_total = $order->get_total();
$code = $coupon->get_code();
$currency = $order->get_currency();
// are there any coupons used?
$coupons = "";
$couponCount = 0;
foreach ($order->get_used_coupons() as $coupon) {
$couponCount++;
if($couponCount > 1) { // add comma if more than one coupon
$coupons .= ',';
}
$coupons .= $coupon;
}
// grab line items from the order
$line_items = $order->get_items();
//loop over line items
$wgItems = array();
foreach ( $line_items as $item ) {
$wgItem = array();
$wgItem ['price'] = $order->get_line_total( $item, true, true );
$wgItem ['name'] = $item->get_name();
$wgItems[] = $wgItem;
}
}
?>
<script>
(function(w,e,b,g,a,i,n,s){w['ITCVROBJ']=a;w[a]=w[a]||function(){
(w[a].q=w[a].q||[]).push(arguments)},w[a].l=1*new Date();i=e.createElement(b),
n=e.getElementsByTagName(b)[0];i.async=1;i.src=g;n.parentNode.insertBefore(i,n)
})(window,document,'script','https://analytics.webgains.io/cvr.min.js','ITCVRQ');
ITCVRQ('set', 'trk.programId', 282105);
ITCVRQ('set', 'cvr', {
value: '<?php echo $order_total ?>',
currency: '<?php echo $currency ?>',
language: 'de_DE',
eventId: 1064725,
orderReference : '<?php echo $order_id ?>',
comment: '',
multiple: '',
checksum: '',
items: '<?php echo json_encode($wgItems) ?>',
voucherId: '<?php echo $coupons ?>',
});
ITCVRQ('conversion');
</script>
You can serialize the values to a string and encode with JSON. json_encode should do the trick.
<script>
const data = <?= json_encode($YOUR_ARRAY) ?>
</script>

How to load more logo's with ajax?

I found a solution how to get a load more button that displays more content on click, but it was for posts, I want to make it work for my custom post type 'Klanten'.
I tried editing the code to match my post type, but I get an error: "Undefined index: offset"
functions.php
wp_enqueue_script( 'dfib-theme-custom', get_template_directory_uri() .'/js/custom.js', array('jquery') );
wp_localize_script( 'dfib-theme-custom', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php')) );
add_action( 'wp_ajax_load_more_posts', 'load_more_posts' );
add_action( 'wp_ajax_nopriv_load_more_posts', 'load_more_posts' );
function load_more_posts(){
global $post;
$args = array('post_type'=>'klanten', 'posts_per_page'=> 4, 'offset'=> $_POST['offset']);
$rst=[];
$query = new WP_Query($args);
if($query->have_posts()):
while($query->have_posts()):$query->the_post();
$rst[] = $post;
endwhile;
wp_reset_postdata();
$offset = $_POST['offset']+4;
endif;
wp_send_json_success(array('klanten'=>$rst, 'offset'=>$offset));
}
custom.js
$('#load_more_posts').on('click', function(e){
console.log('hi');
e.preventDefault();
var $offset = $(this).data('offset');
console.log('var'+$offset);
$.ajax({
method: 'POST',
url: ajax_object.ajax_url,
type: 'JSON',
data: {
offset: $offset,
action: 'load_more_posts'
},
success:function(response){
console.log(response);
$('#load_more_posts').data('offset', parseInt(response.data.offset));
}
});
})
php-file
$query = new WP_Query( array(
'post_type' => 'klanten',
'posts_per_page' => 4,
'offset' => 0,
'paged' => 1,
'order' => 'ASC',
'orderby' => 'rand',
) );
if ( $query->have_posts() ) { ?>
<div class="klanten__wrapper">
<?php
while ( $query->have_posts() ) :
$query->the_post();
?>
<div class="logo__wrapper">
<img class="klant__logo" src="<?php the_post_thumbnail_url(); ?>">
</div>
<?php endwhile; ?>
<div id="load_more_posts" class="loadmore">Load More...</div>
</div>
<?php
wp_reset_postdata();
return ob_get_clean();
}
Console log
I want to show 4 logo's (elements), and load 4 more each time someone clicks the loadmore button
Replace this
<div id="load_more_posts" class="loadmore" data-offset="4">Load More...</div>
You need to return ajax data with logo array and then append data like below code.
AJAX call
$('#load_more_posts').on('click', function(e){
console.log('hi');
e.preventDefault();
var $offset = $(this).data('offset');
console.log('var'+$offset);
$.ajax({
method: 'POST',
url: ajax_object.ajax_url,
type: 'JSON',
data: {
offset: $offset,
action: 'load_more_posts'
},
success:function(response){
console.log(response);
var html = "";
$(response.data.klanten).each(function(index,value) {
html += '<div class="logo__wrapper"> <img class="klant__logo" src="'+value.post_thumbnail+'"></div>'
});
$('.logo_wrapper').append(html);
$('#load_more_posts').data('offset',
parseInt(response.data.offset));
}
});
})
HTML Code
<div class="klanten__wrapper">
<div class="logo_wrapper">
<?php
while ( $query->have_posts() ) :
$query->the_post();
?>
<div class="logo__wrapper">
<img class="klant__logo" src="<?php the_post_thumbnail_url(); ?>">
</div>
<?php endwhile; ?>
<div>
<div id="load_more_posts" class="loadmore">Load More...</div>
</div>
function.php
wp_enqueue_script( 'dfib-theme-custom', get_template_directory_uri() .'/js/custom.js', array('jquery') );
wp_localize_script( 'dfib-theme-custom', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php')) );
add_action( 'wp_ajax_load_more_posts', 'load_more_posts' );
add_action( 'wp_ajax_nopriv_load_more_posts', 'load_more_posts' );
function load_more_posts(){
global $post;
$args = array('post_type'=>'klanten', 'posts_per_page'=> 4, 'offset'=> $_POST['offset']);
$rst=[];
$query = new WP_Query($args);
if($query->have_posts()):
while($query->have_posts()):$query->the_post();
$rst[] = $post;
$post_thumbnail = get_the_post_thumbnail($post->id);
$rst['post_thumbnail'] = $post_thumbnail;
endwhile;
wp_reset_postdata();
$offset = $_POST['offset']+4;
endif;
wp_send_json_success(array('klanten'=>$rst, 'offset'=>$offset));
}
I got help from a colleague and he figured it out. I added this in my js-file (jQuery)
// Counter for logos
var logoCount = $('.logo__wrapper').length;
var counter = 12;
// Show only first 12 logos
$('.logo__wrapper:nth-of-type(1n+13)').addClass('is-hidden');
// Load more logos button click
$('#load_more_posts').on('click', function (e) {
// Loop hidden logo's
$('.logo__wrapper.is-hidden').each(function (i) {
// Hide button if no more logo's
if (counter++ === logoCount) {
$('#load_more_posts').hide();
$('.loadmore__end').toggle();
}
// Show next 12 logos
if (i < 12) {
$(this).removeClass('is-hidden');
}
// Break loop after 12 logos
else {
return false;
}
});
});

Jquery .click function for getting subcat of id element

I try to build a car search plugin, with 3 category levels.
Like: 1 row = Maincat, 2 row = Subcat, 3 row = Subsubcat...
Here is an example of what i want to do:
https://www.aez-wheels.com/3DKonfigurator/index.php?lcs=onz2sm13at&lng=en
in my code the first level appears and the second level loads. but the third level is not loading.
I Think the problem is, that the second row is created dynamicaly.
Can somebody tell me where i have a wrong code?
// Loading WordPress hooks
function __construct()
{
add_action( 'avada_after_header_wrapper', array($this, 'llm_car_conf_list') );
// Register ajax action
add_action( 'wp_ajax_get_cat', array($this, 'getCat') );
// Register ajax action for non loged in user
add_action('wp_ajax_nopriv_get_cat', array($this, 'getCat') );
}
// function for the maincat
function llm_car_conf_list() {
if ( is_front_page() ) {?>
<div class="llm_car_container">
<div class="car_wrapper">
<div class="car_row">
<div class="car_title"><h2>1. Fahrzeug wählen</h2></div>
<ul id="maincat" class="car_conf"><?php
$categories = get_categories(array (
'taxonomy' => 'product_cat',
'parent' => 0
));
foreach ( $categories as $category ) {
printf( '<li class="car_list_item"><a id="%1$s">%2$s</a></li>',
esc_html ($category->term_id ),
esc_html( $category->cat_name )
);
}
?></ul></div>
// Jquery to load first subcat
<script type="text/javascript">
(function($){
$("#maincat li").click(function(){
$("#second_row").empty();
$.ajax({
type: "post",
url: "<?php echo admin_url( 'admin-ajax.php' ); ?>",
data: { action: 'get_cat', cat_id: $(this).find('a').attr('id') },
success: function(data) {
$("#second_row").append(data);
}
});
});
})(jQuery);
</script>
<div class="car_row">
<div class="car_title"><h2>2. Typ wählen</h2></div>
<ul id="second_row" class="car_conf"></ul>
</div>
// Jquery to load subsubcat
<script type="text/javascript">
(function($){
$("#second_row li").click(function(){
$("#third_row").empty();
$.ajax({
type: "post",
url: "<?php echo admin_url( 'admin-ajax.php' ); ?>",
data: { action: 'get_cat', cat_id: $(this).find('a').attr('id') },
success: function(data) {
$("#third_row").append(data);
}
});
});
})(jQuery);
</script>
<div class="car_row">
<div class="car_title"><h2>3. Jahrgang wählen</h2></div>
<ul id="third_row" class="car_conf"></ul>
</div>
</div>
</div>
<?php
}
}
// Function to load the subcats
function getCat() {
$categories = get_categories(array (
'taxonomy' => 'product_cat',
'child_of' => $_POST['cat_id'],
'parent' => $_POST['cat_id']
));
foreach ( $categories as $category ) {
printf( '<li id="%1$s" class="car_list_item"><a id="%1$s">%2$s</a></li>',
esc_html ($category->term_id ),
esc_html( $category->cat_name )
);
}
die();
}
Here is my full code, that works in my plugin
<?php
defined('ABSPATH') or die("Thanks for visting");
if ( ! class_exists( 'frontendAjaxDdown' ) ):
class frontendAjaxDdown
{
// Loading WordPress hooks
function __construct()
{
add_action( 'avada_after_header_wrapper', array($this, 'llm_car_conf_list') );
// Register ajax action
add_action( 'wp_ajax_get_cat', array($this, 'getCat') );
add_action( 'wp_ajax_get_subcat', array($this, 'getSubCat') );
add_action( 'wp_ajax_get_subsubcat', array($this, 'getSubSubCat') );
// Register ajax action for non loged in user
add_action('wp_ajax_nopriv_get_cat', array($this, 'getCat') );
add_action('wp_ajax_nopriv_get_subcat', array($this, 'getSubCat') );
add_action('wp_ajax_nopriv_get_subsubcat', array($this, 'getSubSubCat') );
}
function llm_car_conf_list() {
if ( is_front_page() ) {?>
<div class="llm_car_container">
<div class="car_wrapper">
<div class="car_row">
<div class="car_title"><h2>1. Fahrzeug wählen</h2></div>
<ul id="maincat" class="car_conf"><?php
$categories = get_categories(array (
'taxonomy' => 'product_cat',
'hide_empty' => 1,
'parent' => 0
));
foreach ( $categories as $category ) {
printf( '<li class="car_list_item"><a id="%1$s"><img src="http://climair-schweiz.ch.185-117-169-242.srv201.webpreview.ch/wp-content/uploads/carbrands/%2$s.png" width="20px">%2$s</a></li>',
esc_html ($category->term_id ),
esc_html( $category->cat_name )
);
} ?>
</ul>
</div>
<script type="text/javascript">
(function($){
$("#maincat li").click(function(){
$("#second_row, #third_row, #fourth_row").empty();
$.ajax({
type: "post",
url: "<?php echo admin_url( 'admin-ajax.php' ); ?>",
data: { action: 'get_cat', cat_id: $(this).find('a').attr('id') },
success: function(data) {
$("#second_row").append(data);
}
});
});
})(jQuery);
</script>
<div class="car_row">
<div class="car_title"><h2>2. Model wählen</h2></div>
<ul id="second_row" class="car_conf"></ul>
</div>
<div class="car_row">
<div class="car_title"><h2>3. Baujahr | Typ wählen</h2></div>
<ul id="third_row" class="car_conf"></ul>
</div>
<div class="car_row">
<div class="car_title"><h2>4. Form | Türen wählen</h2></div>
<ul id="fourth_row" class="car_conf"></ul>
</div>
</div>
</div> <?php
}
}
function getCat() {
$categories = get_categories(array (
'taxonomy' => 'product_cat',
'hide_empty' => 1,
'child_of' => $_POST['cat_id'],
'parent' => $_POST['cat_id']
));
foreach ( $categories as $category ) {
printf( '<li id="%1$s" class="car_list_item"><a id="%1$s">%2$s</a></li>',
esc_html ($category->term_id ),
esc_html( $category->cat_name )
);
} ?>
<script type="text/javascript">
(function($){
$("#second_row li").click(function(){
$("#third_row, #fourth_row").empty();
$.ajax({
type: "post",
url: "<?php echo admin_url( 'admin-ajax.php' ); ?>",
data: { action: 'get_subcat', cat_id: $(this).find('a').attr('id') },
success: function(data) {
$("#third_row").append(data);
}
});
});
})(jQuery);
</script> <?php
die();
}
function getSubCat() {
$categories = get_categories(array (
'taxonomy' => 'product_cat',
'hide_empty' => 1,
'child_of' => $_POST['cat_id'],
'parent' => $_POST['cat_id']
));
foreach ( $categories as $category ) {
printf( '<li id="%1$s" class="car_list_item"><a id="%1$s">%2$s</a></li>',
esc_html ($category->term_id ),
esc_html( $category->cat_name )
);
}
?> <script type="text/javascript">
(function($){
$("#third_row li").click(function(){
$("#fourth_row").empty();
$.ajax({
type: "post",
url: "<?php echo admin_url( 'admin-ajax.php' ); ?>",
data: { action: 'get_subsubcat', cat_id: $(this).find('a').attr('id') },
success: function(data) {
$("#fourth_row").append(data);
}
});
});
})(jQuery);
</script> <?php
die();
}
function getSubSubCat() {
$categories = get_categories(array (
'taxonomy' => 'product_cat',
'hide_empty' => 1,
'child_of' => $_POST['cat_id'],
'parent' => $_POST['cat_id']
));
foreach ( $categories as $category ) {
printf( '<li class="car_list_item">%2$s</li>',
esc_url( get_category_link( $category->term_id ) ),
esc_html( $category->cat_name )
);
}
die();
}
}
endif;
new frontendAjaxDdown();
?>

yii2 refresh modal after submit form

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

Json Encoded PHP array has null appended to it

At this point in the debugging this is what I am sending to my javascript
header("Content-Type: application/json");
//echo json_encode($full_product_list);
echo json_encode(array());
and here is my ajax call
jQuery.get( "non public api sorry ")
.done(function(data) {
console.log("I got a response")
console.log(data)
})
.fail(function(data) {
console.log("Error?")
console.log(data);
})
It errors everytime and in the data my response string for the empty array is
"[]null"
Entire function being called for reference same thing I get an error and at the end of my json there is "null" appended.
function getAllProducts() {
$full_product_list = array();
$loop = new WP_Query( array( 'post_type' => 'product', 'posts_per_page' => -1 ) );
$pf = new WC_Product_Factory();
while ( $loop->have_posts() ) : $loop->the_post();
$post_id = get_the_ID();
$product = $pf->get_product($post_id);
$attributes = $product->get_attributes();
$attrs = array();
foreach ($attributes as $attr) {
$name = str_replace("pa_fablab_", "", $attr["name"]);
$attrs[$name] = $attr["value"];
}
$item = array(
"id" => $post_id,
"name" => get_the_title(),
"price" => $product->get_price()
);
if (sizeof($attrs) > 0) {
$full_product_list[] = array_merge($item, $attrs);
}
endwhile; wp_reset_query();
header("Content-Type: application/json");
//echo json_encode($full_product_list);
echo json_encode(array());
}
Return something from your php page, add die() after to remove the null
header("Content-Type: application/json");
//echo json_encode($full_product_list);
echo json_encode(array("message"=>"ok"));
die();

Categories

Resources