简体   繁体   中英

send PHP variable to javascript function via HTML

I am trying to send a PHP variable to a Javascript funtion using HTML. I dont know if it is possible or not. I am a newbie.

This is all the code in both the files, index.php and abc.php PS I have changed the file name from index.html to index.php

index.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml-transitional.dtd">
<?php
require("../php/abc.php");
?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Some Title</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="file.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="here.js"></script>
</head>
<body onload="init();">
<noscript>
Your browser does not support Javascript!!
</noscript>
<table id="content">
    <tr>
        <td>
            <div id="scroll"></div>
        </td>
        <td id="colorpicker" valign="top">
            <img src="palette.png" id="palette" alt="Color Palette" border="1" onclick="getColor(event);" />
            <br />
            <input id="color" type="hidden" readonly="true" value="#000000" />
            <span id="sampleText">
            (text will look like this)
            </span>
        </td> 
    </tr>
</table>

<div>
    <input type="text" id="userName" maxlength="50" size="10" onblur="javascript: check('<?php echo $phpVariable; ?>');" />
    <input type="text" id="messageBox" maxlength="2000" size="50" onkeydown="handleKey(event);" />
    <input type="button" value="Send" onclick="sendMessage();"  />
    <input type="button" value="Delete All" onclick="deleteMessages();"  />
</div>
</body>
</html>

Javscript function

function check(param_name)
{ 
 var oUser=document.getElementById("userName"); 
 oUser.value = param_name;
}

abc.php

if(isset($_POST['user_name'], $_POST['action'])) {
$user_name = $_POST['user_name'];
$action = $_POST['action'];

if($action == 'joined') {
    $phpVariable = user_joined($user_name);
}

function user_joined($user_name) {
$servername = "";
$username = "";
$password = "";
$dbname = "";

//Create connection

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}


$user_name  = mysql_real_escape_string(htmlentities($user_name));

$sql = "INSERT INTO table_name (column_name) VALUES ('$user_name')";
$query = "INSERT INTO table_name2 (column_name) VALUES ('$user_name')";

$result = $conn->query($query);

if($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error in inserting: " . $sql. "<br>" . $conn->error;
}

return $user_name;

$conn->close();

}

Try something like that

HTML

<input type="text" id="nametxt" />
<button id="btn-check"></button>

Javascript

$(document).ready(function (){

   $("#btn-check").click(function(){

       var name = $('#nametxt').val();

       var login = {
           parameter: name
       };

        $.ajax({

              type: 'POST',
              url:  'file.php',
              data: login,
              datatype: 'json'

        }).done(function(data) {

      console.log(data);
     }); 

   });

});

PHP

<?php

//do some

echo information; -- this way return parameters

?>

As you have written, the way to output the value of a PHP variable to an HTML page is by doing <?php echo $phpVariable ?> . In newer versions of PHP (and in older ones where the setting was turned on), you can shorten this to <?= $phpVariable ?> .

You are getting an 'undefined variable' warning probably because the $phpVariable is not getting set. In your code, this variable is only initialized if $action == 'joined' . If you want it to have a default value, give it one first:

$phpVariable = null;
// note that three equals signs are not necessary here
// but a good habit for cases where it matters
if ($action === 'joined') { ... }

When you output the PHP variable into a JavaScript string, you should escape the output so that you don't leave your visitors vulnerable to XSS (cross-site scripting) attacks. In this case, json_encode should be sufficient. However, since your JavaScript is not within a <script> tag, but rather within an onblur attribute, you have to escape any characters which are special in HTML. Since you're using double quotes around the attribute value, htmlspecialchars is sufficient for that. So in all, you will output htmlspecialchars(json_encode($phpVariable)) . The reason for all this is that you don't want to rely on your input being clean -- mistakes will be made and when they do, you don't want to let someone attack your users.

<input type="text" id="userName" maxlength="50" size="10" 
    onblur="javascript: check('<?= htmlspecialchars(json_encode($phpVariable)) ?>');" />

Since we've given a default value ( null ) for $phpVariable and we are calling the check function with it, we should add a "check" to the check function to ensure that we got a real value, like this:

// you should use camelCase or under_scores, but not both, for consistency
function check(paramName) { 
    // loose equals to match null or undefined
    if (paramName == null) { 
        return;
    }
    var oUser = document.getElementById("userName"); 
    oUser.value = paramName;
}

Alternatively, if you want to be really careful about your function inputs, you could verify that paramName is a string and that it has a nonzero length, but in a dynamically typed language like JavaScript, doing all these checks manually sometimes becomes a losing battle.

This is not going to work as-is because PHP is executed server-side and JavaScript is executed client-side.

In order to do this, you're going to have to make an AJAX call to a PHP file and then use JavaScript on the results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM