I am currently having trouble with this. I would like to make one of my variables in Javascript have a PHP value. Here is what I mean:
<script>
JSvariable = <?php echo $PHPvariable; ?>;
</script>
For some reason that is not working. Here is my full (snippet) of code:
<script>
currentreplyid = <?php echo $allpostcomments[$key]['replyid']; ?>;
$('#parentcommentholder').val(currentreplyid);
</script>
I am sure it is some stupid mistake, but I can not seem to find it! What is the problem? Thank you!
PS #parentcommentholder is an input field, and it just had the value 0 after the field is supposed to of been changed.
Here is some source:
<?php
$postcommentsquery = "SELECT * FROM comments WHERE parent = :parent AND postid = :postid ORDER BY datecreated DESC";
$postcommentsparams = array(':parent' => $allreplies[$key]["postid"],
':postid' => $postid);
try{
$postcommentsstmt = $connection->prepare($postcommentsquery);
$postcommentsresult = $postcommentsstmt->execute($postcommentsparams);
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
$allpostcomments = $postcommentsstmt->fetchAll();
foreach ($allpostcomments as $key => $value) {
?>
<script>
var currentreplyid = <?php echo $allpostcomments[$key]['replyid']; ?>;
$('#parentcommentholder').val(currentreplyid);
</script>
<input id="parentcommentholder"></div>
Don't forgot for give quotes ' or ". Use following:
<script>
var JSvariable = '<?php echo $PHPvariable; ?>';
//or
var JSvariable = "<?php echo $PHPvariable; ?>";
</script>
Reason: If php variable contains string and if while assigning it to javascript variable we shall not give quote like:
<?php $PHPvariable = 'String';?>
var JSvariable = <?php echo $PHPvariable; ?>;
Will transform into :
var JSvariable = String;//which will give error in javascript
But this will work fine if PHP variable contains a numeric value like:
<?php $PHPvariable = 2;?>
var JSvariable = <?php echo $PHPvariable; ?>;
Will transform into :
var JSvariable = 2;//which will work perfect
Complete code should be:
<script>
var currentreplyid = "<?php echo $allpostcomments[$key]['replyid']; ?>";
//or if you are sure your variable contains int value
var currentreplyid = parseInt("<?php echo $allpostcomments[$key]['replyid']; ?>");
$('#parentcommentholder').val(currentreplyid);
</script>
Try the below instead of using javascript (as I don't think you need it):
<?php
$postcommentsquery = "SELECT * FROM comments WHERE parent = :parent AND postid = :postid ORDER BY datecreated DESC";
$postcommentsparams = array(':parent' => $allreplies[$key]["postid"],
':postid' => $postid);
try{
$postcommentsstmt = $connection->prepare($postcommentsquery);
$postcommentsresult = $postcommentsstmt->execute($postcommentsparams);
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
$allpostcomments = $postcommentsstmt->fetchAll();
foreach ($allpostcomments as $key => $value) {
?>
<input id="parentcommentholder" value="<?php echo ((int)$allpostcomments[$key]['replyid']>0) ? $allpostcomments[$key]['replyid'] : 0; ?>" />
<?php
}
?>
If your defiantly sure $allpostcomments[$key]['replyid'] is bringing back a value, this should work without any issues.
Related
I am using following code to pass PHP variables to javascript. but it is not working.
function gto(str) {
document.getElementById('goto').action = str;
document.getElementById('ID').value = <?php echo "$userid" ?>;
document.getElementById('name').value = <?php echo "$user_name" ?>;
document.getElementById('gname').value = <?php echo "$usergname" ?>;
document.getElementById('fmname').value = <?php echo "$userfname" ?>;
document.getElementById('img').value = <?php echo "$userimg" ?>;
document.getElementById('email').value = <?php echo "$useremail" ?>;
document.getElementById('goto').submit();
}
Following is the PHP code
<?php
if($_POST["name"] == null)
{
$user_name = 'Annomyous';
}
else{
$user_name = $_POST["name"];
$userid= $_POST["id"];
$usergname= $_POST["gname"];
$userfname= $_POST["fname"];
$userimg= $_POST["img"];
$useremail= $_POST["email"];
}
echo "<p style='color : white'>$user_name";
echo "$userid" ;
echo "$gname";
echo "$fname";
echo "$img";
echo "$email";
echo "$user_name";
echo "$user_name</p>";
$user_name =htmlspecialchars($user_name);
$user_name =str_replace("<script>","", $user_name);
?>
the output is a follows:
ReAlItY TuTs104598758504708047866ReAlItY TuTsReAlItY TuTs//this is php echo output.
JAVASCRIPT OUTPUT:-
function gto(str) {
document .getElementById('goto').action = str;
document.getElementById('ID').value = ;
document.getElementById('name').value = Annomyous;
document.getElementById('gname').value = ;
document.getElementById('fmname').value = ;
document.getElementById('img').value = ;
document.getElementById('email').value = ;
document.getElementById('goto').submit();
}
Function gto is called here:
<button class="w3-btn header-btn" onclick="gto('Contact.php');">Contact Us</button>
I can see in PHP output I am getting all variable output.
but nin juavascript im getting only Annonymous why????
I need to pass post variables to contact us so i am using the form tag and javascript but this is not working Please help me!
Thanks in Advance
values from php to js can be passed in many ways, here's one of them
try to pass the php values when calling the js function, like this:-
<button onclick="gto('Contact.php','<?php echo $userid;?>','<?php echo $username;?>');">Contact Us</button>
and then get values on js function like this:-
function gto(str,userid,username) {
document .getElementById('goto').action = str;
document.getElementById('ID').value = userid;
document.getElementById('name').value =username;
}
that's it, now use the values in js as your wish
Uh, found another issue. The js is in smart quotes, which won't work... "`" is invalid. use "'".
Also, w3schools can't handle php in their editor, so it's no use.
Example for POST requests: https://www.w3schools.com/code/tryit.asp?filename=FQSA8MJYGJ47
Hope this helps.
How do I change the value of a SELECT tag in MATERIALIZE CSS. I'm trying show the selected item that was stored from the database. I tried adding .material_select() at the end of the select but it only retrieves the LAST one in the row. How do I show every try ? Here's what I've tried so far.
$(function() {
<?php
$q = $db->query("SELECT buildingID, buildingName,building_projectID, floorNumber FROM tblBuilding");
while($r = $q->fetch(PDO::FETCH_ASSOC)){
$buildingID = $r['buildingID'];
$buildingName = $r['buildingName'];
$building_projectID = $r['building_projectID'];
$floorNumber = $r['floorNumber'];
$t = $db->query("select projectName from tblProject where projectID = $building_projectID ");
while($u = $t->fetch(PDO::FETCH_ASSOC)){
$projectName = $u['projectName'];
?>
$("#editModal<?php echo $buildingID ?>").click(function(){
alert('<?php echo $projectName ?>');
$("#editBuildingName").val("<?php echo $r['buildingName'] ?>");
$("#editBuildingProject").val("<?php echo $projectName");
$("#editBuildingFloors").val("<?php echo $floorNumber ?>");
});
<?php }}?>
});
instead of:
$("#editBuildingProject").val("<?php echo $projectName");
use this:
$("#editBuildingProject").val("<?php echo $building_projectID ?>").material_select('update');
var phpCode = '<?php
$sql = "SELECT Name,Surname,id_room FROM timatable.professors WHERE p.id_professor = '".mysqli_real_escape_string($_POST['hiddenProfId'])."'";
$resutl = mysqli_query($db,$sql);
if ($result == 1 ) {
$row = mysqli_fetch_array($result);
$professorName = $row['Name'];
$professorSurname = $row['Surname'];
} else echo "Error";
?>';
alert(phpCode);
this is my code. how to make it work ????
Try this.
First initialize, variables to null.
$professorName = "";
$professorSurname = "";
This is because, if php code enters else part, you will not get any error in javascript part.
<?php
$sql = "SELECT Name,Surname,id_room FROM timatable.professors WHERE p.id_professor = '".mysqli_real_escape_string($_POST['hiddenProfId'])."'";
$resutl = mysqli_query($db,$sql);
if ($result == 1 ) {
$row = mysqli_fetch_array($result);
$professorName = $row['Name'];
$professorSurname = $row['Surname'];
} else echo "Error";
?>
<script>
var professorName = "<?php echo $professorName ?>";
var professorSurname = "<?php echo $professorSurname ?>";
alert(professorName);
alert(professorSurname);
</script>
PHP is a server-side language. So it is processed on a server. Therefore you cannot have a PHP code in javascript.
If you want to have javascript managed some editing in database, you can use AJAX to do it without reloading the page.
$query = "SELECT id FROM server";
$result = mysql_query($query);
while($row =mysql_fetch_array($result))
{
$dServer = $row['id'];
?>
<script>
var dServer = <?php echo $dServer; ?>;
document.write(dServer);
var d=parseInt("dServer") + "<br>";
document.write(d);
</script>
}
here everything is okk,"dServer" prints the "id",but just parseInt() not converting "id" into integer. Could anyone please explain what is the problem.
Dont use as a String :
var d = parseInt(dServer) + "<br>";
You are inputting a string to parseInt(). Instead use as follows.
var d=parseInt(dServer) + "<br>";
Again why you are using javascript to print the same. You could use PHP to do print the value of id to the document.
<?php
$query = "SELECT id FROM server";
$result = mysql_query($query);
while($row =mysql_fetch_array($result))
{
$dServer = $row['id'];
?>
<script>
var dServer = <?php echo $dServer; ?>;
document.write(dServer);
var d=parseInt(dServer);
document.write("<br>"+d);
</script>
<?php
}
?>
not pretty sure how you do this. But I want to save my javascript variables as data(1,2,3,4,...) in my while loop. Happy for any help! Thanks
$id = 0;
while($rows = mysql_fetch_array($data)){
$id = $id + 1;
$data = $rows['data'];
?>
<script>
var id = '<?php echo $id; ?>'; //1,2,3,4,5,6,...
var data = '<?php echo $id; ?>'; // Example - Data 1 = Frog, Data 2 = Bird
// So here I want to sava variables so the name will be
// var "data+'id'";
// And the output is data for that row
</script>
<?php
}
?>
//And here outside I want to use the variables like this:
document.write(data1); writes out "Frog"
document.write(data2); writes out "Pig"
<script>
var jsData = [];
<?php
$id = 0;
while($rows = mysql_fetch_array($data)){
$data = $rows['data'];
?>
jsData[<?php echo $id; ?>] = '<?php echo $data; ?>';
<?php
$id++;
}
?>
</script>
This would yield a JS Array called jsData where your ID is the index and which is filled with the PHP $data values.
Declare $data = new Array(); just before the WHILE LOOP then in the WHILE LOOP you could do $data['id'][$id]= $id which will collect all the IDS.
Add $data['data'][$id]= $row['data'] below it so as also to collect each data that you want.
in the script tag do this:
var id = <?php echo '['.join(',', $data['id']).']' ?> //will create --> [1,2,3,4,5,6,7]
var data = <?php echo '['.join(',', $data['data']).']' ?> //--> ['cat', 'dog', 'cow', 'sheep']
now you can access the variable in the Javascript array created eg. $data[0] // 'cat'