Javascript - How to pull a WooCommerce variable in PHP? - javascript

I'm trying to execute some PHP code that is using the WooCommerce variable to get the order ID.
add_action('add_meta_boxes', 'gen_order_meta_boxes');
function gen_order_meta_boxes()
{
add_meta_box(
'woocommerce-order-gen',
__( 'TESTNG' ),
'order_meta_box_gen',
'shop_order',
'side',
'default'
);
}
function order_meta_box_gen()
{
echo '<button class="button save_order button-primary alert-mass">Generate</button>';
}
add_action('admin_footer', 'lolcats');
function lolcats()
{
$order = new WC_Order($post_id);
?>
<script type="text/javascript" >
jQuery(document).ready(function($)
{
$(".alert-mass").click(function(e)
{
e.preventDefault();
alert('<?php echo $order->get_order_number; ?>');
});
});
</script>
<?php
}
I can't seem to get it to return anything besides either null or 0.
Using something like this obviously works perfectly: window.location="dhlgen.php?order=1234"; because I'm trying to pass it through the URL to a PHP function which uses it later.
This also seems to fail, but it returns 'false':
function lolcats($post_id)
{
$order = new WC_Order($post_id);
?>
<script type="text/javascript" >
jQuery(document).ready(function($)
{
$(".alert-mass").click(function(e)
{
e.preventDefault();
var data = <?php echo json_encode($order->shipping_first_name); ?>;
alert(data);
});
});
</script>
<?php
}
Thank you.

Okay, I solved it.
function lolcats()
{
global $post;
$order_id = $post->ID;
?>
<script type="text/javascript" >
jQuery(document).ready(function($)
{
$(".alert-mass").click(function(e)
{
e.preventDefault();
alert('<?php echo $order_id; ?>');
});
});
</script>
<?php
}

Related

On page ready, get Javascript array created during dom creation

I am creating a Javascript array during dom creation using arr.push.
However, on page ready function, it returns an empty array.
<script type="text/javascript">
var short_urls = [];
</script>
$(document).ready(function() {
console.log(short_urls);
});
<?
foreach ($d_json['result'] as $key => $value) {
?>
<script>
short_urls.push("<? echo $shorten_url ?>");
</script>
<?
}
?>
<script type="text/javascript">
var short_urls = [];
$(document).ready(function() {
console.log(short_urls);
});
</script>
<?
foreach ($d_json['result'] as $key => $value) {
?>
<script>
short_urls.push("<? echo $shorten_url ?>");
</script>
<?
}
?>
As PHP will be executed before any javascript you can write the javascript variables out without needing to use the array.push method. However, the question used a php variable $shorten_url - where is that defined? I assume it is the value from the foreach loop
Approach #1
-----------
<script type="text/javascript">
var short_urls = [];
<?php
foreach( $d_json['result'] as $key => $value ) {
$shorten_url='???';
echo "short_urls.push('{$shorten_url}');";
}
?>
$( document).ready( function() { console.log( short_urls ); } );
</script>
Approach #2
-----------
<script type="text/javascript">
<?php
$tmp=array();
foreach( $d_json['result'] as $key => $value ) {
$shorten_url='???';
$tmp[]=$shorten_url;
}
echo "var short_urls = ['".implode("','",$tmp)."'];";
?>
$( document).ready( function() { console.log( short_urls ); } );
</script>

Using values from PHP in JavaScript

I would like to use a value from PHP in JavaScript, but it's not working. I fetch data from a database and store it in a PHP variable and for conditional formatting. I need to also use the data in JavaScript for validation.
The value required by me is $date = date('Y-m-d'); If I pass the value by json Encode the alert function is not working...
$(document).ready(function()
{
alert("Hi");
var array = php print(json_encode($date));
});
Whereas if I just alert the function without...
var array = php print(json_encode($date)); ;
...it works fine.
<script type="text/javascript" src="assests/js/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
alert("Hi");
var array = '<?php print(json_encode($date)); ?>';
});
</script>
</head>
<body>
<form action="majorprocess.php">
<?php
$dbconn = mysql_connect('localhost', 'root','' );
if(!$dbconn)
{
die(mysql_error());
}
else
{
$date = date('Y-m-d');
<script type="text/javascript" src="assests/js/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
alert("<?php echo json_encode(date('Y-m-d')); ?>");
});
</script>
What is the resulting HTML?
There could be a PHP error outputting instead of valid javascript.
Try putting the PHP section at the top maybe?
When asking a question it is always best to post any outputs you are getting so people can help.
try this one
</head>
<body>
<form action="majorprocess.php">
<?php
$dbconn = mysql_connect('localhost', 'root','' );
if(!$dbconn)
{
die(mysql_error());
}
else
{
$date = date('Y-m-d');
}
?>
<script type="text/javascript" src="assests/js/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var array = '<?php print(json_encode($date)); ?>';
alert(array);
});
</script>
You are using the PHP $date variable before setting its value. Make sure to move the php block before you try to output the date:
<?php
$dbconn = mysql_connect('localhost', 'root','' );
if(!$dbconn)
{
die(mysql_error());
}
else
{
$date = date('Y-m-d');
}
?>
<script type="text/javascript" src="assests/js/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
alert("<?php echo json_encode($date) ?>");
});
</script>

Php foreach and echo inside javascript

Good day to everyone:). I just want to ask how can I do php foreach and echo values inside the javascript, because I want the javascript to be a dynamic.
Here is the static js
<script type="text/javascript">
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
if($(this).attr("value")=="1"){
$(".1").toggle();
}
if($(this).attr("value")=="2"){
$(".2").toggle();
}
if($(this).attr("value")=="3"){
$(".3").toggle();
}
if($(this).attr("value")=="4"){
$(".4").toggle();
}
});
});
</script>
and this what I want to happen
<script type="text/javascript">
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
<?php foreach($data as $field): ?>
if($(this).attr("value")=="<?php echo $field->ID);?>" ){
$(".<?php echo $field->ID);?>").toggle();
}
<?php endforeach; ?>
});
});
</script>
the ID values form the database are 1,2,3,4. That would be all. Thank You!
you can push all the values to a js array and than do a loop on js array.
<script type="text/javascript">
$(document).ready(function(){
my_values = Array;
<?php foreach($data as $field): ?>
my_values.push ("<?php echo $field; ?>");
<?php endforeach; ?>
$('input[type="checkbox"]').click(function(){
// java script loop here
for ( var i in my_values)
{
if($(this).attr("value")== i )
{
$("."+this.value).toggle();
}
}
});
});
</script>

AJAX- getting a specific array value in post

Im making a like system and am encorporating ajax to make it smooth. Everything works okay except it always defaults to the last post in for loop. My thinking is there is no way for the javascript to know which element of id "like" to post to.
main.js:
$(".like>a").click(function() {
$.post(base_url + "index.php/userprofile/like_post/", { post : post }, function(data) {
alert('liked');
}, "json");
return false;
});
Im passing through the post variable from the view file. I grab the postID of each post.
userprofile_view.php:
<?php foreach ($posts as $post)
{ ?>
<?php $postID = $this->model_posts->getPostData('id', $post->post); ?>
<script type="text/javascript">
var post = "<?php echo $postID; ?>";
var base_url = "<?php echo base_url(); ?>";
</script>
model_posts.php:
function likePost($post) {
$data['user_ID'] = $this->session->userdata('id');
$data['post_liked'] = $post;
$insert = $this->db->insert('user_post_likes', $data);
return $insert;
}
userprofile.php(controller):
public function like_post() {
$this->load->model('model_posts');
$post = $this->input->post('post');
$this->model_posts->likePost($post);
}
If someone couldhelp me out that would be great!
The problem is your usage of a global variable in a loop, so the variable will have only the last value of the loop.
You can use a data-* attribute like
<script type="text/javascript">
var base_url = "<?php echo base_url(); ?>";
</script>
<?php foreach ($posts as $post)
{ ?>
<?php $postID = $this->model_posts->getPostData('id', $post->post); ?>
<div class='posts'>
<div class='posts_img'>
<img src="<?php echo base_url() . 'img/profilepictures/thumbs/' . $profilepicture?>">
</div>
<div class='posts_user'>
<strong><?php echo $prefname; ?></strong>
</div>
<div class='posts_date'>
<?php echo $this->model_posts->getPostTime($post->post); ?>
</div>
<div class='post'>
<p><?php echo $post->post ?></p>
</div>
<?php if($this->model_posts->doesUserLike($me, $postID)) { ?>
<div class='unlike'>
<?php echo anchor('userprofile/unlike_post/' . $me . '/' . $postID, 'unlike'); ?>
</div>
<?php } else { ?>
<div class='like' data-post="<?php echo $postID; ?>">
<?php echo anchor('#', 'like', array('id' => 'like')); ?>
</div>
<?php } ?>
then
$(".like>a").click(function () {
var post = $(this).parent().attr('data-post');
$.post(base_url + "index.php/userprofile/like_post/", {
post: post
}, function (data) {
alert('liked');
}, "json");
return false;
});
if you're sending same ID field with different values stop, send unique IDs with selected values OR send ID with values as post array, PHP can deal with it
<script type="text/javascript">
var post = "<?php echo $postID; ?>";
var base_url = "<?php echo base_url(); ?>";
</script>
This is your problem. You're declaring these variables in global scope. So every time your PHP foreach loop iterates, you're redefining the variable in global scope, overwriting the previous value.
Instead, set an id attribute on each <a> tag to be the $postID, and get that ID in your click handler, like so:
$(".like>a").click(function() {
var post = this.id;
$.post(base_url + "index.php/userprofile/like_post/", { post : post }, function(data) {
alert('liked');
}, "json");
return false;
});
You would have to modify the code that creates the <a> tags to include the id attribute with the $postID value assigned to it...I don't see that part included in your code samples.

<input> calling a PHP function using AJAX

I am trying to call a PHP function using AJAX to check if the pressed button is the right button.
But I can't seem to figure it out.
I am using this as <input> code :
<?php
$i=0;
while ($i<4){
?>
<input style="background-color: <?php echo $buttonColors[$i]; ?>" onclick="echoHello(<?php echo $i?>)" type="submit" value="<?php echo $buttonName[$i]; ?>">
<?php $i=$i+1; } ?>
and I'm trying to call a PHP function when the button is clicked. I tried this :
<script>
function echoHello()
{
alert("<?php hello(); ?>");
}
</script>
<?php
function hello() {
echo "Hello World";
}
?>
This worked so I tried to change this to :
<script>
function echoHello(num)
{
alert("<?php hello(num); ?>");
}
</script>
<?php
function hello($num) {
if($num == 1) {
echo "Correct button!!!";
} else {
echo "WRONG BUTTON";
}
?>
But this didn't seem to work. What am I doing wrong?
I think you have quite some thing mixed up here.
I would suggest just writing out the buttons, and pass the buttons value to the javascript:
<?php
$i=0;
while ($i<4){
?>
<input onclick="echoHello(this.value)" type="submit" value="<?php echo $buttonName[$i]; ?>">
<?php
$i=$i+1;
} ?>
and then in your javascript (after adding all the jQuery goodness):
function echoHello(btnValue) {
$.ajax({
type: "POST",
url: "formhandler.php",
data: { buttonValue: btnValue }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
The javascript above will send the button value to your 'formhandler.php' page, using AJAX.
In the 'formhandler.php', you could then check what the value of $_POST["buttonValue"] is.
Using your setup, together with jQuery, PHP and JSON, it could be something like this:
function echoHello(btnValue) {
$.getJSON('page.php', {
choice: btnValue
})
.done(function(data) {
// based on $_GET["choice"], your PHP could render some JSON like:
// {"background":"image.jpg","fields":["newValue1", "newValue2", "newValue3"]}
// clear the current html
$("#form").html('');
// load a new background
$('body').css({'background-image':data.background})
// set up the new fields:
$.each(data.fields, function( i, item ) {
$("#form").append('<input type="text" value="' + item + '"/>');
});
});
}
This is just a sample, to give you an idea! It's untested also ;)

Categories