Call javascript function within a PHP form - javascript

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.

Related

Is it possible to change HTML within PHP code?

What is the easiest way to run Javascript code inside PHP, preferably without using external libraries? Specifically, I need the innerHTML of a div to change depending on some calculations performed using the user's form inputs that were captured earlier with $_POST in a separate form. How can I get the following JS code to run inside the following PHP code? (My most basic attempt was using echo command, but it's throwing up errors)
HTML:
<div id="output">
</div><!--#output -->
PHP (desired JS included):
if (count($valid_locations)<$num_of_locations){
echo '<script>const output = document.querySelector("#output");</script>;';
echo '<script>output.innerHTML = "<div class="alert-danger"> Trip unable to be created. Please adjust the budget/number of travelers/duration etc.</div>;";</script>';
}else{
createTrip($trips);
}
Right now, the IF condition is True and the code does run, but it echos ";" for some reason. I have verified that the condition is met and it runs by adding in a simple echo "this runs";, which did appear upon refresh. I just don't understand why it's outputting to the default echo space and the script isnt running to change the innerHTML of the output div. Is this even possible to do with PHP? If so, what's the best way? (doesn't need to be secure, won't be used publicly). I've heard of a few things such as ajax but it seems so complicated. Any explanations on stuff like that specific to this scenario would be greatly appreciated.
Following up on the comments, you don't need JS to achieve what you want. You could just use PHP
<?php
$output = null;
if (!empty($_POST)) {
//...
//... do stuff
//...
if (count($valid_locations)<$num_of_locations){
$output = 'Error occured - bla bla bla';
}
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php if (isset($output)) {?>
<div id="output"><?= $output; ?></div>
<?php } ?>
</body>
</html>

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

Unearthing a js php load/execution issue

Running a base web framework from https://github.com/panique/huge/
The overarching problem I have is: html table needing live updates to account for database (mysql) changes.
Where I'm stuck: I have added to the index/index.php page, the following javascript code to the end of the file (note: header and footers loaded around this index/index.php page) in attempt to refresh the need for updating the table every few seconds in order reload the html table based off of the mysql database state. The index/tableChange module simply gathers the mysql data and returns the query.
<?php echo "
<script language='javascript' type='text/javascript'>
function loadlnk() {
document.getElementById('tableHolder').innerHTML =
\"<object type=\"text/html\" data=\"<?php echo config::get('URL'); ?>index/tableChange\"></object>\";
setTimeout(loadlnk, 3000);
}
loadlnk();
</script>";
?>
When I test the index/tableChange snippet out, I am able to load the php by itself in its own individual webpage (but for the purpose of this question, I'm needing to load that content of tableChange into the index/index page).
I also tried adding the $(document).ready(function() { around inside of the script, but this didn't seem to help accomplish anything visible to changing the table.
I looked at what I understood and could find, but I don't think it's a quote issue.
You might like to remove the inner PHP tags and the echo statement and try like this:
<?php
echo "
<script language='javascript' type='text/javascript'>
function loadlnk() {
document.getElementById('tableHolder').innerHTML =
\"<object type=\"text/html\" data=\"" . config::get('URL') ."index/tableChange\"></object>\";
setTimeout(loadlnk, 3000);
}
loadlnk();
</script>";
?>
I found that I was getting an error in the console, similar to the following:
Load denied by X-Frame-Options: https://localhost/test/target.php does
not permit framing.
The solution, at least a quick one in this instance was to add a header before sending the output from /test/target.php ~ name header('X-Frame-Options: sameorigin'); then it worked just fine.

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.

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