Javascript and PHP to fill WordPress form element - javascript

I am using WordPress and want to take the email from a registered user's account to auto-fill a form.
I'm using two plugins: Snippets for the PHP code and Scripts n Styles for the JavaScript.
The PHP code is
<?php global $current_user; wp_get_current_user();
$user_email = $current_user->user_email;
?>
<script type="text/javascript">
var useremail = <?php echo json_encode($user_email) ?> ;
</script>
and the Javascript is
<script type="text/javascript">
window.onload = function ()
document.getElementsByName("element_name")[0].value = useremail;
}
</script>
However nothing is being filled into the element.
Does anyone have any experience using PHP and JavaScript to auto-populate a form element?
I believe the issue is with the PHP code since I can insert a value into the form using the JavaScript if I put the value I want in quotes.

First line in your php should be:
<?php $current_user = wp_get_current_user();
and:
<?php echo $user_email ; ?>
In js, you're missing an open brace {
window.onload = function () {

Related

Turn PHP variable into Javascript variable and use that Javascript variable as an argument in a Javascript function

An input from a form in my index.php page is sent to my search.php page. This input is turned into the PHP variable $q with $_GET. How do I turn this PHP variable into a Javascript variable that is a string? Then how do I pass this string as an argument in a Javascript function in the body tag when the page loads? The onload function only works if the first parameter is a string. Here is my simplified code:
<?php
if(isset($_GET["q"])) {
$q = $_GET["q"];
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="assets/js/script.js">
var q = "<?php echo $q;?>";
</script>
</head>
<body onload="return Search(*PHP variable turned into Javascript string*, otherFunction(), otherFunction2())">
<div>
Content
</div>
</body>
</html>
Javascript within your script tag 'should' be ignored if there's a src for it. However you can't have precompiled php in a js file. One option is to set the javascript variables within your php files, then separately include your js files. If your js files make use of those variables, make sure to set the variables first:
<script type="text/javascript">
var q = "<?php echo $q;?>";
</script>
<script src="assets/js/script.js"></script>
The script doesn't work because you're trying to include an external JavaScript file, while also using the same tag for inline script.
This part
<script src="assets/js/script.js">
var q = "<?php echo $q;?>";
</script>
Should look something like this
<script src="assets/js/script.js"></script>
<script>
var q = "<?php echo $q;?>";
</script>
Fully fixed code
<?php
if(isset($_GET["q"])) {
$q = $_GET["q"];
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="assets/js/script.js"></script>
<script>
var q = "<?php echo $q;?>";
</script>
</head>
<body onload="return Search(q, otherFunction(), otherFunction2())">
<div>
Content
</div>
</body>
</html>
Edit: Footnote
As #dossy points out, you should avoid directly passing user input into the HTML code. Use json_encode() to avoid any malicious code or invalid input.
<script>
var q = <?php echo json_encode($q); ?>;
</script>
This is what json_encode() is for. Other answers that use the naive approach of var x = "<?php echo $var; ?>"; will break if $var contains a double quote, for example.
This is the safest way of doing this:
<script type="text/javascript">
var q = <?php echo json_encode($q); ?>;
</script>

How to convert and transmit PHP Variable data Using JSON to HTML page's Javascript

I can't seem to figure it out how to convert the following PHP variable to HTML:
$persondata = "<div id='teach'><h3>Name: " . $row["fname"]. "<br>User Name: " . $row["username"]. "</h3><p>Password: " . $row["upass"]. "</p></div><br>";
I wanted to pass that exact data to my HTML page, so that I can use JavaScript's getElementById function to insert it into a selected data field.
I asked a similar question here, which helped me work out some of logic I need, but I can't work out this part of the equation.
If you could please let me know of a simple way of going about this, it would be very much appreciated, as I don't even know the keywords to search for.
Hope below code help you:
<?php
$persondata = '';
foreach($rows as $row){
$persondata .= "<div class='teach'><h3>Name: " . $row["fname"]. "<br>User Name: " . $row["username"]. "</h3><p>Password: " . $row["upass"]. "</p></div><br>";
}
?>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('#data-row').html("<?php echo $persondata ?>");
});
</script>
</head>
<div id="data-row"></div>
A javaScriptVar equals with an echo in php of your php variable.
That is to put php inside js
<script type="text/javascript">
//Your JS
var jsvar = <?php echo $persondata; ?>
//Your JS
</script>
Put PHP var like above into js.
Continuing from above answer:
That is to put php inside js
<script type="text/javascript">
//Your JS
var jsvar = <?php echo $persondata; ?>;
//Your JS
</script>
Put PHP var like above into js.
If you want to transmit data from a PHP script in a server to a client side HTML page for using in js. Go like following.
First get all your data in PHP in an array and use json_encode() and after that echo that variable.
Now in the client side HTML use jQuery.ajax() and send request to that PHP file in server.
When you have the response in Json use js to fragment it and append
wherever you want.
Above is the basic procedure to send data from PHP to HTML page using JS.

Opening url retrieved with PHP inside Javascript

Need to open $link with javascript, that is retrieved from an XML file using PHP. Here's the code:
<?php
$url = "map.xml" ;
$xml = simplexml_load_file($url);
$link = $xml->url[mt_rand(0,count($xml->url)-1)]->loc ; // Get Random Location
?>
<html>
<head>
<title></title>
</head>
<body>
<script>
$(document).ready(function(){
window.open($link, "_blank"); // will open new tab on document ready
});
</script>
</body>
</html>
You cannot access php variables from javascript. With php you can render html and javascript on server. So you need to print your $link variable to the page:
window.open("<?= $link ?>", "_blank");
Note that short echo tag <?= is only guaranteed to be available on php 5.4+, if you are stuck supporting an older version use <?php echo instead

Passing a PHP variable into Javascript returns NULL

I know there are a lot of questions covering something similar, but I've tried the answers without any luck.
Snippet of PHP:
$usernum_query = "SELECT numPersonID FROM tbllogins WHERE txtUserName='$currentuser'";
if(!$usernumber = $db1->query($usernum_query)){
die('There was an error running the usernumber query [' . $db1->error . ']');
}
while($row = $usernumber -> fetch_assoc()) {
$userIDnum = $row['numPersonID'];
$userIDnum = utf8_encode($userIDnum);
}
Snippet of Javascript:
$(function(){
$("#0").click(function(){
var userIDnum = <?php echo json_encode($userIDnum); ?>;
alert(userIDnum);
The most common answer I've come across says to UTF_encode my variable, which I think I've done correctly. I've also tried:
var userIDnum = <?php echo $userIDnum; ?>;
Which doesn't work.
In my HTML outside of the script,
<?php echo json_encode($userIDnum); ?>
return "90" (with the quotes)
<?php echo $userIDnum; ?>
returns 90 (without the quotes).
Within the script, I get null and no alert box, respectively.
Any ideas as to why the variable isn't passed into the script? Thanks!
edit: tried with quotes and got the same result
[Taken from comments as requested]
If I can make a recommendation, put your value in a data-attribute in the HTML (e.g. <body data-user-id="<?php echo $userId ?>">. This keeps you from mixing code languages together which is hard to read, and would allow your external script to run correctly without making it a PHP page.
As far as IE9, I'll take a quick look. You might want to see how jQuery manages the data attributes. You should, at the least, have access to
domObject.getAttribute('data-user-id').
Yep, just did a quick lookup, and even IE10 doesn't support the dataset feature. So, you'll need to use getAttribute for IE <= 10.
A solution based on a suggestion by calamari:
In the HTML:
<!DOCTYPE html>
<!--[if lt IE 11 ]> <html class="ie10orless"> <![endif]-->
<head>
... more code here ...
And in the script:
var oldIE;
if ($('html').is('.ie10orless')) {
oldIE = true;
}
if (oldIE) {
var x = document.getElementsByTagName("div")[0].getAttribute("data-number");
alert("in IE");
alert(x);
} else {
var userinfo = document.querySelector('#user');
alert("NOT in IE");
alert(userinfo.dataset.number);
}
Hope this helps someone else. Thanks everyone for the other suggestions as well.
There are couple of things to check. Lets say this is your script:
<?php $htmlString= 'testing'; //Lets say this is a snippet of your php
?>
<html>
<body>
<script type="text/javascript"><!-- And this is the snippet of your JS -->
// notice the quotes around the ?php tag
var htmlString="<?php echo $htmlString; ?>"; //Make sure there's double
//quotes around your php
alert(htmlString);
</script>
</body>
</html>
Make sure you have PHP and JS in a file called .php. If its an external .js file, php inside it will not work (you can rename the JS file to a .php extension if you have it set up that way)
Also make sure you have the html, php and js setup the way above. There has to be double quotes around php, for example:
var userIDnum = <?php echo json_encode($userIDnum); ?>;
change this to below:
var userIDnum = "<?php echo json_encode($userIDnum); ?>";

Returning information from PHP to javascript

I have a javascript bootkmarklet that the user can load into what ever webpage they are on.
This then displays a php generated page over the top of the current webpage, this includes some information that the javascript has take from the page the user is on.
What I now need is to be able to have the javascript first run one php file that connects with a mysql database, have the result from the database returned to the javascript which can then call the php file that generates the page overlay.
What I am looking for really is a way for the process to go:
User runs javascript --> javascript runs php for mysql --> javascript gets mysql result back --> javascript runs second php file
Here is a starting point of how to use the ajax features in JQuery.
Edit - separate javascript file
html file:
<html>
<head><title> Ajax test page</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="ajaxfunctions.js"></script>
</head>
<body>
<div id="ajaxResult"></div>
</body>
</html>
js file called 'ajaxfunctions.js':
$(document).ready(function() {
$("#ajaxResult").load("ajaxHello.php");
});
php file called 'ajaxHello.php':
<?php
header("text/html");
echo "hello from php";
?>
To read data from a database the php code needs to be a little longer:
<?php
header("text/html");
$username = "root";
$password = "";
$databaseName = "mydatabase";
$connect = mysql_connect("localhost",$username,$password);
if (!$connect) die("Connection Error");
$result = mysql_select_db("$databaseName");
if(!$result) die("Select DB Error");
$result = mysql_query("select email from users where firstname='Abbey'");
if (!$result) die('Invalid query: ' . mysql_error());
$row = mysql_fetch_assoc($result);
echo "Abbeys email address ".$row['email'];
?>
This examples looks up Abbeys email address from the users table in the users database and returns it. The Database name, username and password are all set at the top of the script.
Usually the ajax request passes some data from the html page, I am happy to add this code if this helps.
Is this something like what you are looking for?

Categories