Wordpress, PHP, Javascript, how to get variable within a js function? - javascript

Purpose: passing html hidden input variable into javascript function.
Working on a wordpress plugin and got stuck with javascript.
Here's hidden input I am trying to get, which is variable_product_id. This gets set when an user selects an dropdown options dynamically.
<form class="hello">
<input type="hidden" name="variation_id" value="">
</form>
Outside of form class hello, there's plugin function in below, and I am trying to get and set "variation_id" right after product_id within "wp.CheckoutButton.apply".
if( !is_user_logged_in() )
{
echo "<script type=\"text/javascript\" >
var temp = document.getElementsByName('variation_id');
//<![CDATA[
wp.CheckoutButton.apply({
BUY_BUTTON_LINK_URL:\"www.website.com/?p=42&product_id=\"+temp,
\"\":\"\" });
//]]>
</script>";
}
"wp.CheckoutButton.apply" prints button on the screen which will pass product_id that I am passing.
It's been working with no variable product options within woocommerce, for variable product, I have to get the selected hidden variation_id when an users changes values(dropdown input).
Can I use document.getElementsByName('variation_id');?
If so, how can I pass 'variation_id' within "wp.CheckoutButton.apply" function?
Is "+temp" within apply function legal?

A possible duplicate of this :
php variable into javascript
Sometimes, some data is needed in js files / js code like the base url of the site. In this case, it is best practice to create a JS variable within the header html tag. In your header tags, create a variable like below :
<script>
var baseUrl = <?php echo get_site_url(); //if get_site_url echos the result itself, then no need to use echo ?>
</script>
Now, in all of your JS files and inline js code you will have this variable and you can use it. Simply it is a global js variable (i just made it up, dont know if js has :P )
Now you can use that variable every where in your js files and js codes.
Notge : Please create baseUrl variable at top most of the header tag or some where, so that no js file is included before it.
**Edit : **
Now to get variation_id from your form element, add id to your element as below:
<input type="text" name="variation_id" id="variation_id" value="" />
In js using jquery :
var variation_id = $("#variation_id").val();
and in wp.CheckoutButton.apply , instead of temp, use variation_id. It is correct i think, but try it.
Hope this will help.

For that you need to create a localize script that can help to call a site url in js file or js function.
http://codex.wordpress.org/Function_Reference/wp_localize_script

Related

Insert javascript string into HTML with PHP in WP

I need to create some widget for WP and in widget's setting will be textarea, where user can insert some JS code. And then my widget must inject this code to WP's footer.php with this function:
add_action( 'wp_footer', 'inject_js', 10 );
In my inject_js I have:
function inject_js () {
echo esc_attr( get_option('js_code') );
}
Everything is working good and the code inserts into HTML, but I faced one problem. In my HTML I get something like this:
<!-- BEGIN JS widget -->
<script type="text/javascript">
var __cp = {
id: "J4FGckYPdasda21OaTnqo6s7kMgeGXdTBAb6SgXMD-A"
};
As I understand I got the code from user's textarea in string type and I must do something with the quotes and other symbols, but I really don't know how to solve this issue, because I am new to PHP.
What PHP function must I use or it's possible to do with some WP functions?
I tried:
echo htmlspecialchars(esc_attr( get_option('js_code') ));
and
echo addslashes(esc_attr( get_option('js_code') ));
But nothing helped.
You are seeing the effect of esc_attr - the function is html encoding (amoungst other things) the string.
It is designed for untrusted user input. As your code is specifically designed to accept javascript from a trusted source (the site owner), dont use it.
echo get_option('js_code');
wrap your code in this :- like this:
html_entity_decode(esc_attr( get_option('js_code')));

global variable not displayed in div

I declare a variable at the beginning of my .js file:
var option="blabla";
On page 1.html I click on a link to page 2.html where I have
<script>document.write(option);</script>
No text is displayed on 2.html. When I refresh the browser while I am on 2.html I get undefined as an output.
What do I have to do to have the text displayed straight after I click the link?
Alternatively, how can I get the following code work to output strUrl on 2.html:
on 1.html I have a link:
<a href="2.html" onclick="function1("item")">
on 2.html I have a div:
<div id="display">document.write(strUrl);</div>
then I have in my .js file:
function1(searchitem)
{
strUrl = 'http://blabla.com/'
+ '?key=' + searchitem;
}
You try to create a Javascript variable on a page and then use it on another page. This is a more-or-less broad problem, since you want to maintain values across pages. First of all, you need to decide where is this value going to be defined and where is it going to be used. If this is more like a server-side variable, then you need to define it on server-side and then generate it into your Javascript code. If you are using PHP, then you can do it like this:
<script type="text/javascript>
var foo = '<?php echo $bar; ?>';
</script>
Naturally, you need to initialize $bar to be able to do that. If the variable should be a client-side variable, then you need to use localStorage, like this on 1.html:
localStorage.setItem("option", "blablabla");
and then load it on 2.html:
localStorage.getItem("option");
Or, if you need to use it both on server-side and client-side, then you can use a cookie for this purpose. Using cookies i slightly more complex, but my answer to another question should get you going.
Let's focus on the cause this did not work for you. A Javascript variable will cease to exist when the page is unloaded, so you will not be able to use its value after that. So, you need to persist it somehow, storing it either on the server or the computer where the browser is being run.
As a side-note, I should mention that you can use Javascript variables accross pages if you load some pages inside iframes of a page, but that is a different scenario.
This is what FORMS and AJAX were invented for. If your server has a PHP processor (virtually ALL of them do), then you can rename your .html files to .php and use a bit of PHP to accomplish your goal.
A web page ending with .PHP works exactly the same as one ending in .html, except that you can now add snippets of PHP code where desired. It is not necessary to have any PHP code, but if you have some it can do stuff.
Method One: FORMs
If you want to switch to page2.html and see a value sent from page1.html, you can use a FORM construct and post the data from page1 to page2:
page1.php
<form action="2.html" method="post">
<input name="option" type="text" />
<input type="submit" name="sub" value="Go" />
</form>
page2.php
<?php
$p1 = $_POST['option'];
?>
<div>On page1 of this website, you typed: <?php echo $p1; ?>. That's what you did.</div>
Note how a <form> uses the name= attribute for the name of the variable that is sent to the other side.
Example Two: The AJAX method
HTML:
<div id=nonForm">
<input id="option" type="text" />
<input type="button" id="myButt" value="Go" />
</div>
<div id="results"></div>
jQuery:
$('#myButt').click(function(){
var opt = $('#option').val();
$.ajax({
type: 'post',
url: 'page2.php',
data: 'option='+opt,
success: function(john){
if (d.length) alert(john); //display result from Page2 in a pop-up box
$('#results').html(john); //Or, display it right on the page
}
});
});
PAGE2.PHP -- The AJAX processor file
<?php
$opt = $_POST['option'];
//Now, you can do something with the data in $opt, and then send back a result
$rtn = 'Hey, you sent: ' .$opt;
echo $rtn;
The primary (and most important) difference between the two methods is that the FORM will change pages on you. The user will be sent from Page1 to Page2, and the screen will flash as this happens.
What's exciting about AJAX is it sends data to Page2, where Page2 can do something with it (for example, a database lookup), and then Page2 sends different data back to Page1. This new data can then be displayed on the page WITHOUT the page refreshing.
Here are a couple of very basic AJAX examples, to get you going:
AJAX request callback using jQuery

Jquery and AJAX script to run a PHP script in the background to avoid any refreshing

I have built a follow/unfollow Twitter like system using PHP. Now I would like to run the follow-unfollow PHP script in the background using AJAX/JQUERY to avoid refreshing the page when you follow/unfollow a user. To make things simpler, I will be here just using the example of “unfollow”. As you notice, I am running an iteration to output all the members in the database. I am outputting here (as well for simplicity) just the member’s name and an unfollow button to each one.
This is the code using php.
members.php
<?php foreach($members as $member){ ?>
<p class="member_name"><?php echo $member->name; ?></p>
<p class="follow_button">Unfollow</p>
<?php } ?>
unfollow.php
<?php
if($_GET['unfollow_id']){
$unfollow_id=$_GET['unfollow_id'];
$unfollow=Following::unfollow($id, $unfollow_id); //Function that will make the changes in the database.
// $id argument will be gotten from a $_SESSION.
}
I am trying to achieve the same result running unfollow.php in the background to avoid any refreshing. This is what I have come up with, as you might imagine it is not working properly. I am including the Jquery script inside the iteration which I think is the only way of obtaining the $member->id property to then assign it to the Jquery variable.
members.php THE NEW ONE THAT TRYS TO RUN THE SCRIPT WITH AJAX JQUERY
<?php foreach($members as $member){ ?>
<p class="member_name"><?php echo $member_name; ?></p>
<button type="button" class="unfollow_button" id="unfollow">Unfollow</button>
<script type="text/javascript">
$(document).ready(function(){
$("#unfollow").click(function(){
// Get value from input element on the page
var memberId = "<?php $member->id ?>";
// Send the input data to the server using get
$.get("unfollow.php", {unfollow_id: memberId} , function(data){
// Success
});
});
});
</script>
<?php } ?>
Can you provide me any help for this to work?
Thanks in advance.
Remember, in HTML, id attributes have to be unique.
Because you're rendering multiple members on a single page, you should not use an id selector in jQuery, but a class selector (e.g. button.unfollow). If you use #unfollow, you'll run into ID conflicts between each of the members' buttons.
First, render all of your members with unfollow buttons without ids. I'm adding the member_id in the markup using a data attribute called data-member_id.
<?php foreach($members as $member) { ?>
<p class="member_name"><?=$member_name?></p>
<button type="button" class="unfollow_button" data-member_id="<?=$member->id?>">Unfollow</button>
<?php } ?>
Then add a single click handler for all button.follow buttons, which extracts the member_id from the clicked button's data-member_id attribute and sends it to the server.
<script type="text/javascript">
$(document).ready(function() {
$("button.unfollow_button").on('click', function() {
// Get value from input element on the page
var memberId = $(this).attr('data-member_id');
// Send the input data to the server using get
$.get("unfollow.php", {unfollow_id: memberId} , function(data) {
// Success
});
});
});
</script>
On a side-note, you should probably look into building a RESTful service for this, to which you can post proper HTTP requests using http://api.jquery.com/jquery.ajax/.
See here for an intro on REST in PHP I wrote a while back:
Create a RESTful API in PHP?

Update content of div using javascript/jquery/php

I am currently making a webpage where I want the user to view different database results depending on which result they pick. The results will either be picked through a button, or by a query typed in by hand into a textarea.
I have the connection to the database and everything set up in an external PHP script which I am currently linking in to my site using "require".
Within this PHP script I have a "query" variable.
I would like for this variable to be dependent on whatever value is entered by the user.
I suppose this should be doable using some sort of $query = $POST['entry'] and some kind of Ajax call in a javascript? I just don't know how this whole thing should be fitted together.
If we assume that my menu and container looks something like this, where getData.php is where the $query variable is and what returns the database data.
<div id="menu">
<textarea class="queryText" name="queryText" placeholder="Enter the query..."></textarea>
<input class="menuButt" type="button" value="Submit" onclick="JavaScript:ChangeDivVal();"/>
</div>
<div id="container">
<?php
require 'getData.php';
?>
</div>
Here is a picture if that helps my explanation of what I want to do.
I'm very grateful for any help I could possibly get!
//Ambrose
There are neat and simple mechanisms to pass the input of your textarea (the query string) to php and return the database output back to javascript. From there you then can easily attach it to any dom node you wish.
I personally do stuff with jQuery since its so handy. You might wanna use the load function for your simple purpose:
$( document ).ready(function() {
$('#querySubmitButton').click(function (evt)
{
evt.preventDefault(); // stops the submit taking place
var myQuery = $('#queryText').val(); // get the query value
// load data received from php script into the dom container
$('#container').load('getData.php', { query:myQuery, anotherVar:null });
});
});
The load function simply loads everything the desired script outputs into the given domnode. You can add as many parameters as you want in the second argument and could even use a callback to perform some more js after loading.
For details see http://api.jquery.com/load/.
Oh and by the way I changed your html to this:
<div id="menu">
<textarea id="queryText" name="queryText" placeholder="Enter the query..."></textarea>
<input id="querySubmitButton" type="button" value="Submit"/>
</div>
<div id="container"></div>
In your getData.php (which I assume produces plain html) you can then use php's $_POST var to get the query.
$query = $_POST['query'];

Yahoo Merchant Store Catalog Tags Insert Dynamically with Javascript, Jquery, or Ajax

I opened up a yahoo store through their Merchant Service. They have a pretty good store catalog that I have used on a business site that I own. I like it so I decided to use the service again on another business I own. I got the site built but have ran into a few issues with calling the Yahoo Catalog Tags. The tags are basically comments. EX: (<!--#ystore_order id=item_id -->). When the site is loaded it is parsed and the page loads the product details in place of this tag/comment.
I can get everything to work except for the action attribute of my form.
I have tried a bunch of things but I cannot seem to get the action set for my form. If I hard code the tag then it works fine but obviously if I did that then I would have to create a page for every single product.
My form:
<div id="list">
<form method="post">
<input id="btnSubmit" type="submit" value="Add To Cart">
</form>
</div>
Trying to add the comment/tag to form action attribute. I've done it this way(below) and also by getting rid of the variable and just paring the url in the jquery attr function.
<script language="javascript">
$.ajaxSetup({cache: false});
$(document).ready(function(){
//Get URL from URL Query String.
var obj = getUrlVars()["Object"];
//Set form action attribute
$('form').attr('action', '<!--#ystore_order id='+ obj +' -->');
});
</script>
I've also tried creating the form dynamically.
<script language="javascript">
$.ajaxSetup({cache: false});
$(document).ready(function(){
//Get URL from URL Query String.
var obj = getUrlVars()["Object"];
var new_form = '<form method="post" action="<!--#ystore_order id='+obj + ' -->">' +
'<input type="submit" value="Add To Cart" id="btnSubmit">' +
'</form>';
$('#list').append(new_form);
});
</script>
I have tried to escape some characters but have had no success there either.
"\<\!--#ystore_order id='+obj + ' --\>"
I know the issue has something to do with the comment syntax but if I can add it manually then I should be able to do it dynamically. I know this is a hard one to test but if anyone thinks they may have a solution I would be happy to set up an ftp account on my site so you can test and I will provide the product ID's for testing. I've fought with this for about 30+ hours.
Yahoo store tags are populated server-side. Adding a store tag on the client side using Javascript won't do anything, because the code that recognizes the store tag and appends the appropriate html will never see the tag you drop in on the client side. There's no client-side solution possible
The best solution here would be to write a server side program to populate a template with the appropriate tag in response to http requests. I'm not super-familiar with the Yahoo store, so I don't know what the best language for this would be, but it would be a very simple program given how straightforward it sounds like your template is. Since this is already embedded in a site you own, I'd just use whatever backend language you are already working in.
Once you have a server side script that executes and returns the html you need, you could use AJAX to populated it with the appropriate product details as needed.

Categories

Resources