ajax code with echo <script> not work - javascript

I have this ajax code:
<script>
$(document).ready(function() {
$('ul#tab li:first').html('<?php echo $channel;?>');
$('ul#tabs li').on("click", function() {
// $('ul#tab li.active').html($(this).html());
$('ul#tab li').html("");
//$('ul#tab li.active').html($(this).html());
var index = $("ul#tabs li").index($(this));
$.post("../admin/ajax/ch1.php", {
index: index
}, function(result) {
$('ul#tab li.active').html(result);
});
});
});
</script>
and in the php ch1.php is
<?php
$ch1tab1= file_get_contents("../channels/ch1tab1.html");
$ch1tab2= file_get_contents("../channels/ch1tab2.html");
$ch1tab3= file_get_contents("../channels/ch1tab3.html");
$ch1tab4= file_get_contents("../channels/ch1tab4.html");
$ch1tab5= file_get_contents("../channels/ch1tab5.html");
$channel = $_POST['index'];
if ($_POST['index'] == 0 ){ $channel = $ch1tab1;}
else if ($_POST['index'] == 1){ $channel = $ch1tab2;}
else if ($_POST['index'] == 2 ){ $channel= $ch1tab3;}
else if ($_POST['index'] == 3 ) {$channel = $ch1tab4;}
else if ($_POST['index'] == 4 ) {$channel = $ch1tab5;}
echo $channel; ?>
the varible ch1tab4 have a code , and it is not work , echo blank
what i should to do plz ?

Why don't you use jQuery's .load() function? It uses the following syntax:
$(selector).load(URL,data,callback);

Related

Refresh part of page when user navigated back to it

In my shop page, for each product I have cart quantities that the user can change without add to cart button (it's with display none and activated by js).
my problem is that if a user changed item quantity in single product page and navigated back into shop page it show the wrong quantity from cache.
Right now i'm reloadin the whole page using this code:
jQuery( document ).ready(function( $ ) {
$(document).ready(function () {
if(performance.navigation.type == 2 || performance.navigation.type == 0){
var isquanpage = document.getElementsByClassName('store-quantity');
if (isquanpage.length > 0) {
console.log(isquanpage);
$("#a2cloader").show();
location.reload(true);
document.addEventListener('DOMContentLoaded', function() {
$("#a2cloader").hide();
}, false);
}
}
});
});
I want to refresh just the quantities and not the whole page:
<div class="quantity-div" >
<i class="fas fa-plus sumsum-quantity-b" value="+" onclick="store_quantity_b('+', this.parentNode.querySelector('input[type=number]').id);"></i>
<input class="sumsum-quantity store-quantity" form="<?php echo $product->id; ?>" inputmode="decimal" style="padding:0;border-radius:5px;" type="number" min="0" value="<?php echo $cartquan ?>"
name="<?php echo $varid; ?>" onclick="this.select()" id="quantity-<?php echo $varid ?>" data-cartquan="<?php echo $cartquan ?>" data-varititle="<?php echo get_the_title( $attribute_value['variation_id']); ?>">
<i class="fas fa-minus sumsum-quantity-b" value="-" onclick="store_quantity_b('-', this.parentNode.querySelector('input[type=number]').id);"></i>
</div>
And what i tried to do is this:
quanfield = document.getElementsByClassName("store-quantity");
cartquantities =<?php echo json_encode(WC()->cart->get_cart_item_quantities();); ?>;
console.log(cartquantities);
But it gets the cached version of the cart and not the updated one.
OK, i found a solution, I'm using hook on woocommerce add to cart fragments like this:
// cart quantities
add_filter( 'woocommerce_add_to_cart_fragments', woocommerce_cartquant_fragment' );
function woocommerce_cartquant_fragment( $fragments ) {
global $woocommerce;
ob_start();
?>
<p id="cartquantities" style="display:none"><?php echo json_encode(WC()->cart->get_cart_item_quantities()); ?></p>
<?php
$fragments['p#cartquantities'] = ob_get_clean();
return $fragments;
}
and then using this script:
//refresh page from history
jQuery( document ).ready(function( $ ) {
$(document).ready(function () {
if(performance.navigation.type == 2 || performance.navigation.type == 0){
let quanfield, quanname,cartquantities,store,obj;
let findname =[];
$("#a2cloader").show();
timeout = setTimeout(function() {
cartquantities = document.getElementById("cartquantities").innerText;
cartquantities = cartquantities.replace("{","");
cartquantities = cartquantities.replace("}","");
cartquantities = cartquantities.replace(/['"]+/g, '');
cartquantities = cartquantities.split(",");
for (i = 0; i < cartquantities.length; i++) {
cartquantities[i] = cartquantities[i].split(":");
findname[i] = cartquantities[i][0];
}
//console.log(findname);
quanfield = document.getElementsByClassName("store-quantity");
//console.log(quanfield.length);
for (i = 0; i < quanfield.length; i++) {
quanname = quanfield[i].name;
obj = findname.findIndex(o => o==quanname);
//console.log(obj);
if (obj !=-1){
quanfield[i].value=cartquantities[obj][1];
quanfield[i].setAttribute("data-cartquan", cartquantities[obj][1]);
}else{
quanfield[i].value=0;
quanfield[i].setAttribute("data-cartquan", 0);
}
$("#a2cloader").hide();
}
}, 1500 );
}
});
});
Is there a possibility to make javascript wait for the fragments instead of setting timeout?
SOLVED! used interval to check when fragments are updated
<script>
//refresh page from history
jQuery( document ).ready(function( $ ) {
$(document).ready(function () {
if(performance.navigation.type == 2 || performance.navigation.type == 0){
let quanfield, quanname,cartquantities,store,obj,timer;
let findname =[];
$("#a2cloader").show();
//var t=0;
timer = setInterval(checkfrags, 5);
function checkfrags(){
//t+=5;
if(document.getElementById("cartquantities").innerText=="null") {
//console.log(t);
}else{
cartquantities = document.getElementById("cartquantities").innerText;
cartquantities = cartquantities.replace("{","");
cartquantities = cartquantities.replace("}","");
cartquantities = cartquantities.replace(/['"]+/g, '');
cartquantities = cartquantities.split(",");
for (i = 0; i < cartquantities.length; i++) {
cartquantities[i] = cartquantities[i].split(":");
findname[i] = cartquantities[i][0];
}
//console.log(findname);
quanfield = document.getElementsByClassName("store-quantity");
//console.log(quanfield.length);
for (i = 0; i < quanfield.length; i++) {
quanname = quanfield[i].name;
obj = findname.findIndex(o => o==quanname);
//console.log(obj);
if (obj !=-1){
quanfield[i].value=cartquantities[obj][1];
quanfield[i].setAttribute("data-cartquan", cartquantities[obj][1]);
}else{
quanfield[i].value=0;
quanfield[i].setAttribute("data-cartquan", 0);
}
$("#a2cloader").hide();
}
//console.log(document.getElementById("cartquantities").innerText+"done "+t);
document.getElementById("cartquantities").innerText="null";
clearInterval(timer);
}
}
}
});
});
</script>
<p id="cartquantities" style="display:none">null</p>

Woocommerce | Plus Minus remove negative numbers (min_value)

I ask you for help please, I haven't come out of it for hours.
I set the quantity selector on the Woocommerce shop page,
which automatically puts the item in the cart and / or removes it.
I have a big problem, when I am on zero and I press - the numbers go negative, I would make sure that it cannot go below zero.
Thanks so much!!
Function.php
// Remove Add To cart Button
remove_action('woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10);
// Add our Quanity Input
add_action('woocommerce_after_shop_loop_item', 'QTY');
function QTY()
{
global $product;
?>
<div class="shopAddToCart">
<button value="-" class="minus2" >-</button>
<input type="text"
disabled="disabled"
size="2"
value="<?php echo (Check_if_product_in_cart($product->get_id())) ? Check_if_product_in_cart($product->get_id())['QTY'] : 0;
?>"
id="count"
data-product-id= "<?php echo $product->get_id() ?>"
data-in-cart="<?php echo (Check_if_product_in_cart($product->get_id())) ? Check_if_product_in_cart($product->get_id())['in_cart'] : 0;
?>"
data-in-cart-qty="<?php echo (Check_if_product_in_cart($product->get_id())) ? Check_if_product_in_cart($product->get_id())['QTY'] : 0;
?>"
class="quantity qty qty-botton"
max_value = "<?php echo ($product->get_max_purchase_quantity() == -1) ? 1000 : $product->get_max_purchase_quantity(); ?>"
min_value = <?php echo $product->get_min_purchase_quantity(); ?>
>
<button type="button" value="+" class="plus2" >+</button>
</div>
<?php
}
//Check if Product in Cart Already
function Check_if_product_in_cart($product_ids)
{
foreach (WC()->cart->get_cart() as $cart_item):
$items_id = $cart_item['product_id'];
$QTY = $cart_item['quantity'];
// for a unique product ID (integer or string value)
if ($product_ids == $items_id):
return ['in_cart' => true, 'QTY' => $QTY];
endif;
endforeach;
}
//Add Event Handler To update QTY
add_action('wc_ajax_update_qty', 'update_qty');
function update_qty()
{
ob_start();
$product_id = absint($_POST['product_id']);
$product = wc_get_product($product_id);
$quantity = $_POST['quantity'];
foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item):
if ($cart_item['product_id'] == $product_id) {
WC()->cart->set_quantity($cart_item_key, $quantity, true);
}
endforeach;
wp_send_json('done');
}
*.js jQuery on Footer
jQuery(document).ready(function ($) {
"use strict";
// Add Event Listner on the Plush button
$('.plus2').click(function () {
if (parseInt($(this).prev().val()) < parseInt($(this).prev().attr('max_value'))) {
$(this).prev().val(+$(this).prev().val() + 1);
var currentqty = parseInt($(this).prev().attr('data-in-cart-qty')) + 1;
var id = $(this).prev().attr('data-product-id');
var data = {
product_id: id,
quantity: 1
};
$(this).prev().attr('data-in-cart-qty', currentqty);
$(this).parent().addClass('loading');
$.post(wc_add_to_cart_params.wc_ajax_url.toString().replace('%%endpoint%%', 'add_to_cart'), data, function (response) {
if (!response) {
return;
}
if (response) {
var url = woocommerce_params.wc_ajax_url;
url = url.replace("%%endpoint%%", "get_refreshed_fragments");
$.post(url, function (data, status) {
$(".woocommerce.widget_shopping_cart").html(data.fragments["div.widget_shopping_cart_content"]);
if (data.fragments) {
jQuery.each(data.fragments, function (key, value) {
jQuery(key).replaceWith(value);
});
}
jQuery("body").trigger("wc_fragments_refreshed");
});
$('.plus2').parent().removeClass('loading');
}
});
}
});
$('.minus2').click(function () {
$(this).next().val(+$(this).next().val() - 1);
var currentqty = parseInt($(this).next().val());
var id = $(this).next().attr('data-product-id');
var data = {
product_id: id,
quantity: currentqty
};
$(this).parent().addClass('loading');
$.post(wc_add_to_cart_params.wc_ajax_url.toString().replace('%%endpoint%%', 'update_qty'), data, function (response) {
if (!response) {
return;
}
if (response) {
var url = woocommerce_params.wc_ajax_url;
url = url.replace("%%endpoint%%", "get_refreshed_fragments");
$.post(url, function (data, status) {
$(".woocommerce.widget_shopping_cart").html(data.fragments["div.widget_shopping_cart_content"]);
if (data.fragments) {
jQuery.each(data.fragments, function (key, value) {
jQuery(key).replaceWith(value);
});
}
jQuery("body").trigger("wc_fragments_refreshed");
});
$('.plus2').parent().removeClass('loading');
}
});
});
});
Just add a check before running the line:
$(this).next().val(+$(this).next().val() - 1);
that will become:
if ( $(this).next().val() > 0 ) {
$(this).next().val(+$(this).next().val() - 1);
}
Also note that you are using an identical id for each quantity input of each product. The id attribute value should be unique on the page.
Here you can find some methods of adding plus and minus buttons in the quantity field of the add to cart form (which you could take inspiration from):
Custom plus and minus quantity buttons in Woocommerce 3
WooCommerce plus and minus buttons
WooCommerce: Add to Cart Plus & Minus Buttons
Thanks Vincenzo Di Gaetano.
I solved it like this:
$('.minus2').click(function () {
var $minus2 = $(this);
var oldValue = $minus2.parent().find("input").val();
if (oldValue > 0) {
$(this).next().val(+$(this).next().val() - 1);
.....

Check value with checkbox click

The problem in question is not to allow me to click on a checkbox if the atendimento number (atendimento.value) is different from a previously entered number.
When I first click on 1 checkbox I store this value and a push to an array.
If I click on another checkbox and the atendimento.value is different, it will display the error message with toast.
I would like to know what I'm forgetting / missing in my code.
ng.checkAtendimento = function(id) {
var atendimento = document.getElementById('atendimento-' + id);
var checkOs = document.getElementById('checkOs-' + id);
var array = [];
if(checkOs.checked){
array.push(atendimento.value);
console.log(array);
}else{
var index = array.indexOf(atendimento.value);
array.splice(index, 1);
console.log(array);
}
if(array[0] != atendimento.value){
console.log(array[0]);
toastr.error(
'error',
'service', {
closeButton: true,
progressBar: true,
timeOut: 7000
});
checkOs.checked = false;
}
}
HTML/PHP
<input id="checkOs-<?php echo $entity->getId(); ?>"
ng-click="checkAtendimento('<?php echo $entity->getId(); ?>');"
type="checkbox"
class="array-ordemservico"
name="[]array-ordemservico"
value="<?php echo $entity->getId();?>" />
<input id="atendimento-<?php echo $entity->getId(); ?>"
class="array-atendimento"
style="display:none" type="checkbox"
value="<?php echo $entity->getAtendimento(); ?>" />
ng.checkAtendimento = function(id){
var atendimento = document.getElementById('atendimento-' + id);
$("#checkOs-" + id).on("change", function (){
index = $.inArray(atendimento.value, ArrayCheckbox);
if ($("#checkOs-" + id).prop('checked')){
if (ArrayCheckbox.length > 0 && index === -1 && atendimento.value != ""){
toastr.error(
'error',
'OS',{
closeButton: true,
progressBar: true,
timeOut: 7000
});
$("#checkOs-" + id).prop("checked", false);
} else if(ArrayCheckbox.length == 0 && atendimento.value != ""){
ArrayCheckbox.push(atendimento.value);
}
} else if((ArrayCheckbox[0] == atendimento.value)){
ArrayCheckbox.splice(index, 1);
}
});
}

jQuery captcha match

i have a jQuery and php captcha after i add the code to validate the match its not working
here is my jQuery code
$(document).ready(function() {
$('img#captcha-refresh').click(function() {
change_captcha();
});
function change_captcha(){
document.getElementById('captcha').src="reCaptcha/get_captcha.php?rnd=" + Math.random();
}
var captchascr = $('#captcha').attr('src');
$('#captcha-code').on('change', function(){
var captchaval = $(this).val();
if (captchascr == captchaval) {
console.log('match');
}else {
console.log('No match');
}
});
});
html
<div class="captcha-box">
<img src="reCaptcha/get_captcha.php" id="captcha" />
</div>
<div class="text-box">
<label>Type the two words:</label>
<input name="captcha-code" type="text" id="captcha-code">
</div>
<div class="captcha-action">
<img src="reCaptcha/refresh.jpg" id="captcha-refresh" />
</div>
here is the php code
session_start();
$word_1 = '';
for ($i = 0; $i < 4; $i++)
{
$word_1 .= chr(rand(97, 122));
}
for ($i = 0; $i < 4; $i++)
{
$word_2 .= chr(rand(97, 122));
}
$_SESSION['random_number'] = $word_1.' '.$word_2;
$dir = 'fonts/';
$image = imagecreatetruecolor(165, 50);
$font = "recaptchaFont.ttf"; // font style
$color = imagecolorallocate($image, 0, 0, 0);// color
$white = imagecolorallocate($image, 255, 255, 255); // background color white
imagefilledrectangle($image, 0,0, 709, 99, $white);
imagettftext ($image, 22, 0, 5, 30, $color, $dir.$font, $_SESSION['random_number']);
header("Content-type: image/png");
imagepng($image)
here is the session is created at the php file i just don't know how to call the session so i make the matching, can someone please help?
Make the AJAX Call to the new file named validate_captcha.php.
The PHP Code in file to handle AJAX Call
<?php
session_start();
$task = !empty($_POST['task']) ? $_POST['task'] : null;
$response = 'false';
if ( $task == 'validateCaptha' ){
$inputCaptcha = !empty($_POST['inputCaptcha']) ? $_POST['inputCaptcha'] : null;
$sessionCaptcha = $_SESSION['random_number'];
if ($inputCaptcha == $sessionCaptcha){
$response = 'true';
}else{
$response = 'false';
}
echo $response;
exit();
}
?>
The jQuery AJAX Code
$(document).ready(function() {
$('img#captcha-refresh').click(function() {
change_captcha();
});
function change_captcha(){
document.getElementById('captcha').src="reCaptcha/get_captcha.php?rnd=" + Math.random();
}
$('#captcha-code').on('change', function(){
var inputCaptcha = $(this).val();
$.ajax({
url: 'reCaptcha/validate_captcha.php',
type: 'POST',
async: false,
data: {'task':'validateCaptha', 'inputCaptcha':inputCaptcha},
success: function(response){
if (response=='true'){
alert('Match');
}else{
alert('Not Match');
}
}
});
});
});
Hope this may help you.

How to properly declare a php function as a variable in another function

I'm looking to display a piece of javascript after the 6th paragraph of every post on my wordpress blog. So far, I can only get the function to work when I'm using a fixed variable:
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
$ad_code = 'fixed variable such as <div>box</div>';
if (is_single()) {
return prefix_insert_after_paragraph( $ad_code, 6, $content );
}
return $content;
}
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
$closing_p = '</p>';
$paragraphs = explode( $closing_p, $content );
foreach ($paragraphs as $index => $paragraph) {
if ( trim( $paragraph ) ) {
$paragraphs[$index] .= $closing_p;
}
if ( $paragraph_id == $index + 1 ) {
$paragraphs[$index] .= $insertion;
}
}
return implode( '', $paragraphs );
}
The javascript I'm trying to add:
function ad_unit() ?>
<script type="text/javascript">
ad = document.getElementById('marker');
if (ad.getBoundingClientRect().width) {
adWidth = ad.getBoundingClientRect().width;
} else {
adWidth = ad.offsetWidth; // for old IE
}
/* Choose the right ID */
if ( adWidth >= 600 )
aId = ["test1"];
else if ( adWidth >= 468 )
aId = ["test2"];
else
aId = ["test3"];
document.write (
'<div id="' + akId[0] + '"></div>'
);
</script>
<?php
I've tried to declare $placeholder = ad_unit(); but it keep displaying the unit at the top of the content instead of after the 6th paragraph. Somehow the prefix_insert_after paragraph function doesn't work after I add the javascript function. Any ideas?
Try it with ob_start() and ob_get_clean()
function ad_unit()
{
ob_start();
?>
<script type="text/javascript">
ad = document.getElementById('marker');
if (ad.getBoundingClientRect().width) {
adWidth = ad.getBoundingClientRect().width;
} else {
adWidth = ad.offsetWidth; // for old IE
}
/* Choose the right ID */
if ( adWidth >= 600 )
aId = ["test1"];
else if ( adWidth >= 468 )
aId = ["test2"];
else
aId = ["test3"];
document.write ('<div id="' + akId[0] + '"></div>');
</script>
<?php
return ob_get_clean();
}
So what happens is that with ob_start() you enable output buffering. You output the HTML but buffer it, then with ob_get_clean() you get the buffered output from the output buffer.
This will be cleaner without a function (and definitely work, I don't remember what plain HTML does when put in a PHP function):
// Somewhere above the rest of your application
ob_start(); ?>
/// YOUR HTML/javascript
<?php
$advertisement = ob_get_clean();
You need opening and closing brackets for the php function
<?php
function ad_unit() { ?>
<script type="text/javascript">
ad = document.getElementById('marker');
if (ad.getBoundingClientRect().width) {
adWidth = ad.getBoundingClientRect().width;
} else {
adWidth = ad.offsetWidth; // for old IE
}
/* Choose the right ID */
if ( adWidth >= 600 )
aId = ["test1"];
else if ( adWidth >= 468 )
aId = ["test2"];
else
aId = ["test3"];
document.write (
'<div id="' + akId[0] + '"></div>'
);
</script>
<?php }

Categories