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.
Related
I'm currently working on a Facebook like chat, with 3 different chat boxes that should work simultaneously. I can send and read messages from my database, but I'm having difficulty displaying this information in the right place. In chat.php I have this snippet of code:
$.ajax({
url: "fetch_user_chat_history.php",
method: "POST",
data: jQuery.param({receiver_id:receiver_id, num:num}),
success: function(data) {
$('$chat_history_'+receiver_id).html(data);
}
});
Now I am able to read the data from my database correctly in fetch_user_chat_history.php, but when I iterate over my messages I'm unable to output them correctly back to chat.php. Here is my fetch_user_chat_history.php:
<?php
include "opendb.php";
session_start();
$output1 = '';
$output2 = '';
$increment = 0;
$sender = $_SESSION['user_id'];
$receiver_id = $_POST['receiver_id'];
$chatboxnum = $_POST['num'];
$query = 'SELECT content, timestamp_chat, sender_id FROM messages WHERE (sender_id = '.$sender.' AND receiver_id = '.$receiver_id.' OR (sender_id = '.$receiver_id.' AND receiver_id = '.$sender.'))';
$statement = $db->prepare($query);
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
switch ($chatboxnum) {
case 1:
foreach ($result as $row) {
if ($row['sender_id']==$sender) {
echo '<script>var para = document.createElement("div");';
echo 'para.innerHTML = '.$row["content"].';';
echo 'var att = document.createAttribute("class");';
echo 'att.value = "msg-send";';
echo 'para.setAttributeNode(att);';
echo 'document.getElementById("sendbox-1").appendChild(para);';
echo 'document.body.appendChild(para); </script>';
}
else {
echo "var element = document.getElementById('receivebox-1'); element.classList.add('msg-receive');";
}
$increment += 1;
}
break;
}
?>
None of my echo statements add anything to chat.php. I'm sure there's a very easy fix as I have done this before but I can't seem to get it working. I apologise for the long post.
when one record then show data when multiple record come then not show data other site.
ajaxx.php
<?php
include 'database.php';
session_start();
$post = $_POST;
$search = $post['search'];
$searchType = $post['searchType'];
if ($searchType == 'all')
{$sql = "SELECT DISTINCT title FROM hadees WHERE title LIKE '$search%' AND (type='Bukhari' OR type='Muslim') ";}
else
{$sql = "SELECT DISTINCT title FROM hadees WHERE title LIKE '$search%' AND type='$searchType' ";}
$result = mysqli_query($db,$sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$row['title'];
echo json_encode($row);
}
} else
{ echo "Not Found Result" ; }
?>
when data record is one then append the data successfully when multiple record come then not show data and append not work
javascript code
function searchh()
{
var type = $("input[name='type']:checked").val();
var searchhh = $( ".myButton option:selected" ).text();
debugger;
$.ajax({
url: 'ajaxx.php',
type: "POST",
data: {'searchType':type, 'search':searchhh},
success: function (data) {
var duce = jQuery.parseJSON(data);
alert(duce.title);
}
});
}
I think your issue is in the while loop. You don't want to encode each row one-by-one, but as a whole like this.
$myResults = [];
while($row = $result->fetch_assoc()) {
$row['title'];
$myResults[] = $row;
}
echo json_encode($myResults);
You are producing invalid JSON by using echo json_encode($row); within a loop.
Try to craft an array of rows, and then display it.
if($result->num_rows > 0)
{
$output = array();
while($row = $result->fetch_assoc())
{
output[] = $row;
}
if($searchType == 'all')
{
echo json_encode($output);
}
else
{
echo json_encode(current($output)); // print just one
}
}
I'm new at php. I get the last id from database. For each id I want the state and the link. I'll check if state == 1, then get the content of the link (there's JavaScript variable that I need that is in the content of link). I'll send that variable with location.href.
Then I get that variable with $_GET in the second page. I want to store that var into database, then come back to first page and get the second link from the database and again do the same works.
How can I send the $j into second page for saving the x_cor and y_cor, and how to increase the $j when it comes to first page again?
<html>
<head>
<title>firstpage</title>
</head>
<body>
<?php
include_once ('simple_html_dom.php');
include_once ('split_unicode_function.php');
// getting the last id from db
$connection = #mysql_connect("localhost", "root", "kkuser");
$select_db = mysql_select_db("kk", $connection);
$sql = "SELECT id FROM netbarg ORDER BY id DESC LIMIT 1";
$result = mysql_query($sql, $connection);
$rows = mysql_fetch_array($result);
$last_id = $rows['id'];
// getting id and link for each column
for ($j = 1; $j <= 2; $j++)
{
$select_db = mysql_select_db("kk", $connection);
$id = "SELECT state FROM `table` WHERE id='$j' ";
$result = mysql_query($id, $connection);
$row = mysql_fetch_array($result);
echo $state = $row[0] . '<br />';
// getting link
$link = "SELECT link FROM `table` WHERE id='$j' ";
$result = mysql_query($link, $connection);
$rows = mysql_fetch_array($result);
$link = $rows[0];
// (state is just 1 or 2)check if the state is 2 or not...
if ($state == 1)
{
$f = file_get_contents($link);
echo "<div>$f</div>";
}
}
?>
<script>
$("body").hide();
location.href ='secondpage.php?val='+point0+;
</script>
</body>
</html>
second page
<html>
<head>
<title>second page</title>
</head>
<body>
<?php
if (isset($_GET['val']))
{
$hat = $_GET['val'];
echo $hat;
$coords = trim($hat, '()');
// echo $coords.'<br />';
$a = array();
$a = explode(",", $coords);
var_dump($a);
echo $long = $a[0];
echo '<br />';
if ($long == "undefined") $lat = "undefined";
else echo $lat = $a[1];
if ($_SERVER['REQUEST_METHOD'] == "GET")
{
$connection = #mysql_connect("localhost", "root", "kkuser");
$select_db = mysql_select_db("kk", $connection);
$update = "UPDATE `table` SET `x_cor`='$long',`y_cor`='$lat' , `state`='2' WHERE `id`='$j' ";
$insert_todb = mysql_query($update, $connection);
if ($insert_todb) echo "coordinates has been updated", '<br />';
}
}
?>
<script>
location.href ='firstpage.php';
</script>
</body>
</html>
if get the last insert id use mysqli_insert_id($con);
it return last insert id from database using this geted id you can
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.
I am new to PHP, I am trying to echo a javascript alert box if taskDueDate is Today.
Any suggestions:
$varTaskAlert = mysql_query("SELECT * FROM tasks");
while ( $rows = mysql_fetch_array($varTaskAlert)) {
$varTaskID = $rows['taskid'];
$varTaskTitle = $rows['tasktitle'];
$varTaskDetail = $rows['taskdetail'];
$varTaskResource = $rows['taskresource'];
$varTaskDue = $rows['taskduedate'];
$varTaskStatus = $rows['taskstatus'];
$varTaskType = $rows['tasktype'];
$active = Active;
$curdate = date('y/m/d');
if ($varTaskStatus == $active && $varTaskDue == $curdate) {
echo '<script type="text/javascript">alert("The Task <?php echo $varTaskTitle ; ?> is Today.")</script>';
}
}
Please check date format of
$varTaskDue = $rows['taskduedate'];
Is $varTaskDue formate similar to 'y/m/d' format?
Hope this will help.
On first look you should change
echo '<script type="text/javascript">alert("The Task <?php echo $varTaskTitle ; ?> is Today.")</script>';
to
echo "<script type='text/javascript'>alert('The Task {$varTaskTitle} is Today.')</script>";
Your Echo is wrong. You are already in php you just include js alert so you can directly use that variable. Try this
echo "<script type='text/javascript'>alert('The Task {$curdate} is Today.')</script>";