Insert javascript string into HTML with PHP in WP - javascript

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

Related

Call javascript function within a PHP form

The architecture I use to load contents onto a common area on the web page is as below
I have a java script function within the form as shown below called javaScriptFunc which never gets invoked.
Is it possible to invoke a java script function within a form?
Please do let me know if more clarity is needed. I'll try to clarify. I'm stuck with this for a while now. I'd appreciate any help please
I think you are missing some PHP tags if I understand what you are trying to do correctly. Try this:
<form method="post" action="" id='somdId'>
<?php
require_once 'some_php_file.php';
if (isLoggedIn()) {
// Some PHP code here
?>
<script>
javaScriptFunc(<?php echo formatJson(someArgs); ?>);
</script>
<?php
}
?>
Not very clear what you want. You need to echo the script like this
echo ("<script type='text/javascript'>javaScriptFunc(" . formatJson(someArgs) . ");</script>");
provided you have already defined the function javaScriptFunc somewhere else in script.
For some reason, I the JS function doesn't seem to fire from within a form. I've worked around by re-writing the load logic to load the whole PHP page instead of a form. just a different way of doing things.

Insert code with JS just like echo in php

I want to get some code snippets from a PHP server to be "injected" in HTML. Basically when I open page.php I get some text like "_off".
The injection works with this code, however I can't use php in this html since it is local.
<img src="images/test
<?php
{ echo "_off"; }
?>
.jpg">
JavaScript seems to be the logical step. But if I just enter this at the position where I want the text of course it doesn't work:
<script type="text/javascript"> $.get( "page.php", function( data ) { document.write(data); } ); </script>
Any ideas?
You need to use $('#someElement').html(data) or $('#someElement').text(data) if you want to write the data to a specific place on the page. You should avoid using document.write
Here is a fiddle to demonstrate: https://jsfiddle.net/yd9mx4d3/

How to execute javascript without click or onload event from php?

I have one javascript named func.js, in that there is one function called show which takes 2 arguments, what I need to do is I want to call that function from php, I can't use any click or onload event here my script looks like this
<html>
<head></head>
<script type='text/javascript' src='path/to/func.js'></script>
<body>
some div etc
<form method='post' action="" >
.....
.....
</form>
</body>
</html>
<!-- after submit of form validation is in php -->
<?php
/* here I want to call javascript, where arguments are php variables
show('argument1','argument2'); */
// I tried to echo like this
echo "<script>show('$argument1',$argument2')</script>";
?>
So what's the solution for my case ?
The code you have should work… most of the time. Unfortunately, you haven't told us why it doesn't work - is there a PHP error? Is there a JS error? — and you haven't shown us either the resulting JavaScript that PHP is outputting or the contents of the variables so we can figure it out for ourselves.
The two most likely explanations (and the only ones that occur to me at the moment) for the problem are:
There is a problem with the data in the variables
That the variables contain characters which cannot appear inside JavaScript strings or ' characters which must be escaped inside JavaScript strings.
JSON is a sufficient subset of JavaScript that the json_encode function will escape (and quote) most data so it is suitable for use in JS.
<script>
show(<?php echo json_encode($argument1); ?>, <?php echo json_encode($argument2); ?>)
</script>
There is a problem with your timing
You have an HTML comment saying "after submit of form validation is in php", but there is nothing in the code you have shared to enforce that.
You need to have something like if (isset($_POST['some_data_from_your_form'])) { ... } wrapped around the generation of the script so it only appears when the form is submitted and not when it initially loads.
If that doesn't work, then you really do need to look at what the variables are, what the generated JS is, and what your JavaScript error console says.
Script elements are not allowed after the end of the HTML element. While browsers will recover from that error, you really should move the script inside the BODY.
It could be to do with the data inside the arguments, what sort of data is it?
echo "<script>show('".str_replace("'", "\'", $argument1)."', '".str_replace("'", "\'", $argument2)."')</script>";
If you're passing information such as J'min it will cause an issue. Does the data have multiple lines? Then it needs to be filtered.
First of all, your tags are broken
<script type='text/javascript' href='path/to/func.js'</script>
You should change href to src and close the script tag, so it becomes
<script type='text/javascript' src='path/to/func.js'>
Also, javascript is client-sided which means you can't call javascript functions in PHP.
I think a good solution here would be to use an AJAX call to validate your form.
Have you tried putting the arguments outside the quotes?
echo "<script>show('".$argument1."', '".$argument2."')</script>";
echo '<script type="text/javascript">show(' . $argument1 . ',' . $argument2 . ');</script>';
above might work for you.

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

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

Kohana 3 JavaScript issue

We have a simple JQuery date picker that we are trying to include on a page. The function works on a strait html site, however, when we include the working function via Kohana the function does not work. We have tried including it both as a file by loading all of the JavaScript references in an array in a template and printing them with
<?php foreach($scripts as $file) { echo HTML::script($file, NULL, TRUE), "\n"; }?>
As well as simply putting the script in a separate view and using view::factory to include the file. When we do the latter the </script> tag is not recognized by browsers or at least its syntax highlighting is not picking it up, though this does not effect other scripts such as Google maps. For what ever it is worth, here is the function:
jQuery(function(){
jQuery(".datepick").datepicker();
});
and the element it is acting on is:
<input class="datepick" id="to" type="text" />
Does anyone have any suggestions for us. We are getting pretty desperate to make this one little simple function work.
You probably don't need the last TRUE on the HTML::script() call, as that will add index.php to your script URL, implying that you are using PHP to serve the actual script files.
In this case, I think your call should just be:
<?php foreach ($scripts as $file) { echo HTML::script($file), "\n"; } ?>
I don't think this is related to Kohana but to your HTML code.
How do you include your scripts (is jQuery included before your javascript code) ?

Categories

Resources