Is it possible to put a part of PHP code in <script>? - php

I have a php page, within is an alert like so:
<script>
alert('Stop the timer!');
</script>";
now i'd like to try/do this:
<script>
<?php echo "$test2"; ?>
alert('Stop the timer!');
</script>
(what i try to do is to give back the content of $test2 by means of the alert...)
Now this does not work. but.... it doesn't give an error message either.
so 2 questions here are:
1) is it even possible to put a part of php in the section
2) if it doesn't work why doesn't it give an error message
(3) do i have to make the $test2 global? (and how to best format it if so)
thanks in advance.
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<!-- deze hieronder is nodig voor touchpad enabled sliders -->
<script src="jquery.ui.touch-punch.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
function getSelectValues(select) {
var result = [];
var options = select && select.options;
var opt;
for (var i=0, iLen=options.length; i<iLen; i++) {
opt = options[i];
if (opt.selected) {
result.push(opt.value || opt.text);
}
}
return result;
}
</script>
<!-- accordion -->
<script>
$(function() {
$( "#accordion" ).accordion({
event: "click",
active: false,
collapsible: true,
autoHeight: false
});
});
</script>
<script>
$(function() {
$( "#slider-vertical" ).slider({
orientation: "horizontal",
range: "min",
min: 0,
max: 100,
value: 1,
slide: function( event, ui ) {
$( "#amount" ).val( ui.value );
}
});
$( "#amount" ).val( $( "#slider-vertical" ).slider( "value" ) );
});
</script>
<script>
$(function() {
$( "#slider-vertical2" ).slider({
orientation: "horizontal",
range: "min",
min: 0,
max: 100,
value: 1,
slide: function( event, ui ) {
$( "#amount2" ).val( ui.value );
}
});
$( "#amount2" ).val( $( "#slider-vertical2" ).slider( "value" ) );
});
</script>
<title>Left X Right -BrainGame</title>
<!-- Bootstrap -->
<link href="css/bootstrap.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
<script>
$(".js-example-basic-multiple").select2(); </script>
<style type="text/css">
p.label_checkbox_pair {
clear: both;
float: none;
position: relative;
}
p.label_checkbox_pair input {
left: 80px;
position: absolute;
top: 1px;
}
p.label_checkbox_pair label {
display: block;
margin-left: 90px;
width: 200px;
}
</style>
<script src="js/icheck.js"></script>
<script>
//oud $(document).ready(function(){
//$('input').iCheck({
//checkboxClass: 'icheckbox_polaris',
//radioClass: 'iradio_polaris',
//
//increaseArea: '20%' optional
//});
//});
$(document).ready(function(){
$('input').each(function(){
var self = $(this),
label = self.next(),
label_text = label.text();
label.remove();
self.iCheck({
checkboxClass: 'icheckbox_line-blue',
radioClass: 'iradio_line-blue',
insert: '<div class="icheck_line-icon"></div>' + label_text
});
});
});
</script>
<link href="skins/line/blue.css" rel="stylesheet">
</head>
<BODY>
<br /><br />
<table HSPACE="50" CELLPADDING="20">
<tr HSPACE=50 CELLPADDING="30">
<td>
<?php
$a=array("red","blue","black","orange","green");
$random_keys=array_rand($a,5);
$textcolours=array('red','blue','black','orange','green');
shuffle($textcolours);
echo "<right><font size=6 color='$textcolours[0]' >".$a[$random_keys[0]]."<br><br></font></right>";
echo "<right><font size=6 color='$textcolours[1]' >".$a[$random_keys[1]]."<br><br></font></right>";
echo "<right><font size=6 color='$textcolours[2]' >".$a[$random_keys[2]]."<br><br></font></right>";
echo "<right><font size=6 color='$textcolours[3]' >".$a[$random_keys[3]]."<br><br></font></rightr>";
echo "<right><font size=6 color='$textcolours[4]' >".$a[$random_keys[4]]."<br><br></font></right>";
?>
</td>
<td>
<div class="left">
<form class="span4" action="" method="post">
<fieldset>
<legend>Left X Right BrainGame</legend>
<p halign="right" margin="10px">Name: <input type="text" name="naam" ></p>
<p halign="right" margin="10px">Date: <input type="text" name="date" id="datepicker" ></p>
<br>
<?php
if(isset($_POST['getdata'])){
$conn=mysql_connect('localhost','t','w');
mysql_select_db("test",$conn);
$regexp = "/^[^0-9][A-z0-9_]+([.][A-z0-9_]+)*[#][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/";
$naam=$_POST['naam'];
$date=$_POST['date'];
//$type=$_POST['type'];
//$core=$_POST['core'];
//$management=$_POST['management'];
//$names = $tools;
//$output = preg_grep('/(Andrew|John)/i', $names);
//print_r( $output );
//
//http://webcheatsheet.com/php/regular_expressions.php#match
$test = $_POST['tools'];
$result = preg_replace('/({|:|true|}|")/', '', $test);
$test2 = preg_grep('/(^RED|^BLACK|^BLUE|^ORANGE|^GREEN|^red|^black|^blue|^orange|^green)/i', $result);
$tools = json_encode($test2);
//$tools = $_POST['tools'];
//$tools = json_encode(preg_grep('/(RED|BLACK|BLUE|ORANGE|GREEN)/i', $_POST['tools']));
//$tools = json_encode($_POST['tools']);
//$analytisch=$_POST['analytisch'];
//$eneagram=$_POST['eneagram'];
if(true == false ){
echo "<label class='err'>All fields are required</label>";
}
else{
$insert="Insert into kandidaat(naam,date,tools)
values('".$naam."','".$date."','".$tools."')";
$rs=mysql_query($insert) or die(mysql_error());
?>
<script>
<?php echo "$test2"; ?>
alert('Stop the timer!');
</script>";
<?php }
}
?>
</fieldset>
<div id="accordion" style="width:90%;">
<h3>Start...</h3>
<div>
<p class="label_checkbox_pair">
<!--<div style="font-family: arial; font-size: 6px; color: #0B1DE0; vertical-align: middle;"><input style="vertical-align: middle" type="checkbox" name="iCheck" value="true"><label for="certs">ISTQB2</label></div>-->
<div style="font-family: arial; font-size: 6px; color: #0B1DE0; vertical-align: middle;"><input style="vertical-align: middle" type="checkbox" name="certs[RED]" value="true"><label>RED</label></div>
<div style="font-family: arial; font-size: 6px; color: #0B1DE0; vertical-align: middle;"><input style="vertical-align: middle" type="checkbox" name="certs[BLUE]" value="true"><label>BLUE</label></div>
<div style="font-family: arial; font-size: 6px; color: #0B1DE0; vertical-align: middle;"><input style="vertical-align: middle" type="checkbox" name="certs[BLACK]" value="true"><label>BLACK</label></div>
<div style="font-family: arial; font-size: 6px; color: #0B1DE0; vertical-align: middle;"><input style="vertical-align: middle" type="checkbox" name="certs[ORANGE]" value="true"><label>ORANGE</label></div>
<div style="font-family: arial; font-size: 6px; color: #0B1DE0; vertical-align: middle;"><input style="vertical-align: middle" type="checkbox" name="certs[GREEN]" value="true"><label>GREEN</label></div>
</p>
</div>
<h3>Part 2</h3>
<div>
<p>
<!-- zie content website https://select2.github.io/examples.html -->
<fieldset>
<div><input type="checkbox" name="tools[RED]" value="true"><label>RED</label></div>
<div><input type="checkbox" name="tools[BLUE]" value="true"><label>BLUE</label></div>
<div><input type="checkbox" name="tools[BLACK]" value="true"><label>BLACK</label></div>
<div><input type="checkbox" name="tools[ORANGE]" value="true"><label>ORANGE</label></div>
<div><input type="checkbox" name="tools[GREEN]" value="true"><label>GREEN</label></div>
</fieldset>
</p>
</div>
</div>
<br/> <button type="submit" name="getdata" class="btn">Submit</button>
Highscores
</form>
</div>
<?php
function save(){
}
?>
<?php
function make_links_clickable($text){
return preg_replace('!(((f|ht)tp(s)?://)[-a-zA-Zа-яА-Я()0-9#:%_+.~#?&;//=]+)!i', '$1', $text);
}
?>
</td>
</tr>
</table>
</body>
</html>

Your syntax in wrong. Imagine your have saved foobar in your varibale.
If you print it like you the the result will be
foobar
But your printed it inside the script part so you need to assign it to a JavaScript variable. There are two possibilities to alert it.
alert("<?php echo $test; ?>");
Or
var content = "<?php echo $test; ?>";
alert(content);

Try this?
<script>
alert('<?php echo $test2; ?>');
</script>
The
alert('<?php echo $test2; ?>');
will be replaced by the content of your PHP variable ("Hello word" by example), just like you wrote this :
alert('Hello word');

Yes, it is possible due to the fact that PHP scripts are evaluated by a PHP interpreter on the Server first, before delivering plain HTML/CSS/JS to the client browser.
Anyways, it would have been faster to just go ahead and try it yourself.
For answering why it doesnt work in your case, we need more code to see how and where your variable(s) are defined.

Related

Date range from reports , not working properly because of query

What to add in my query to restrict users from choosing wrong dates ,
E.G. From March 7 To March 2 , the transaction within march 2-7 does not show up ,but when you change it to march 7 to april 7 it shows all transaction , is
there anything that I can add to restrict users from doing that.
Please help me.
Thank you very much.
This is my sales.php file where the user will choose what date to show.
<form action="total_sales.php" method="post">
From: <input type="text" class="datepicker" placeholder="E.G.(2018-01-14)" name="dayfrom" required pattern="[0-9]{4}+[0-9]+[0-9]"> To: <input type="text" class="datepicker" placeholder="E.G.(2018-02-11)" name="dayto" required pattern="[0-9]{4}+[0-9]+[0-9]">
<input type="submit" value="Show Sales" name="salesbtn" ></form></center>
This is my total_sales.php file.
<head>
<script>
$(function() {
$( "#tabs" ).tabs();
$('a[rel*=facebox]').facebox();
$( ".datepicker" ).datepicker();
});
$(document).ready(function(){
// Write on keyup event of keyword input element
$("#searchme").keyup(function(){
// When value of the input is not blank
if( $(this).val() != "")
{
// Show only matching TR, hide rest of them
$("#searchTbl tbody>tr").hide();
$("#searchTbl td:contains-ci('" + $(this).val() + "')").parent("tr").show();
}
else
{
// When there is no input or clean again, show everything back
$("#searchTbl tbody>tr").show();
}
});
});
// jQuery expression for case-insensitive filter
$.extend($.expr[":"],
{
"contains-ci": function(elem, i, match, array)
{
return (elem.textContent || elem.innerText || $(elem).text() || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
}
});
</script>
<script>
function goBack() {
window.history.back();
}
</script>
<?php include('session.php'); ?>
<?php include('header.php'); ?>
<?php include('navbar.php'); ?>
<style>
.footer1 {
position: absolute;
right: 45%;
font-family: ""Lucida Console", Monaco, monospace";
top: 0%;
width: 80%;
background-color:#F8F8FF;
color: black;
text-align: left;
}
h3{
font-size:20px;
font-family: "Arial";
}
table {
width:60%;
}
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
text-align: center;
}
#media print {
#page { margin: 0; }
body { margin: 1cm; }
#printPageButton {
display: none;
}
#e{
display:none;
}
.footer {
position: fixed;
left: 0;
font-family: ""Lucida Console", Monaco, monospace";
bottom: 0;
width: 100%;
background-color:#F8F8FF;
color: black;
text-align: center;
}
}
</style>
<div style="height:30px;"></div>
<div id="page-wrapper">
<div class="row">
<div class="col-lg-0">
<br><img src="../upload/logo.jpg" align="center" class="footer1" style="height:50px; width:50px;"><br>
<br>
<?php
if(isset($_POST['salesbtn'])) {
$from = date('Y-m-d', strtotime($_POST['dayfrom']))." 00:00:01";
$to = date('Y-m-d', strtotime($_POST['dayto']))." 23:59:59";
?>
<center><h1> Product Sales Report </h1><h3>From (<?php echo $from; ?>) To (<?php echo $to; ?>)</h3>
<button id="printPageButton" onClick="window.print();" class="btn btn-primary" button type="submit">Print</button>
<button id="e" class="btn btn-primary" onclick="goBack()">Back</button>
<br><br>
<table width="100%" cellspacing="0" cellpadding="0" style="font-family:Arial Narrow, Arial,sans-serif; font-size:15px;" border="1">
<tr>
<td width="30%"><div align="center"><strong>Purchase Date</strong></div></td>
<td width="30%"><div align="center"><strong>Customer</strong></div></td>
<td width="40%"><div align="center"><strong> Purchase Name</strong></div></td>
<td width="40%"><div align="center"><strong>Quantity</strong></div></td>
</tr>
<?php
try {
require ("conn.php");
$stmt1 = $conn->prepare("select * from sales_detail left join product on product.productid=sales_detail.productid left join sales on sales.salesid=sales_detail.salesid left join customer on sales.userid=customer.userid where product.supplierid='".$_SESSION['id'] ."' AND sales_date BETWEEN '$from' AND '$to' order by sales.sales_date desc");
$stmt1->execute();
while($row=$stmt1->fetch(PDO::FETCH_ASSOC)) {
$sales_date = $row['sales_date'];
$customer_name = $row['customer_name'];
$product_name = $row['product_name'];
$sales_qty = $row['sales_qty'];
?>
<tr align="center">
<td><?php echo $sales_date; ?></td>
<td><?php echo $customer_name; ?></td>
<td><?php echo $product_name; ?></td>
<td><?php echo $sales_qty; ?></td>
</tr>
</center>
<?php
}
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
?>
<tr>
</tr>
</table> </br> </br>
</div>
</div>
</div>
<?php include('script.php'); ?>
<?php include('modal.php'); ?>
<?php include('add_modal.php'); ?>
<script src="custom.js"></script>
So, I tried this and it worked:
the scripts HAVE TO BE in that order (if not it will break)
There is some problem with your pattern, but with Datepicker, you don't need it anyway
After the FROM Date selection I would set the minDate of the TO Date to +1d
Code Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<title>Document</title>
</head>
<body>
<form action="total_sales.php" method="post">
From:
<input type="text" class="datepicker" placeholder="E.G.(2018-01-14)" name="dayfrom" required > To:
<input type="text" class="datepicker" placeholder="E.G.(2018-02-11)" name="dayto" required >
<input type="submit" value="Show Sales" name="salesbtn">
</form>
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="http://code.jquery.com/ui/1.8.21/jquery-ui.min.js"></script>
<script>
$(function () {
$(".datepicker").datepicker({
dateFormat: "yy-mm-dd",
minDate: "-1d",
maxDate: "+1w"
});
});
</script>
</body>
</html>

percentage of progress bar does not work correctly(I'm interested in understanding the code forms)

The percentage of progress bar does not work correctly
The correct progress bar does not work and it's 100% fast
But the file has not uploaded yet
Click the submit button
The progress bar is completed quickly
But still the file is being uploaded
I'm interested in understanding the code forms
<?php
$msg = [
"title file"
,"url file"
,"send file"
];
?>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/bootstrap-rtl.css" rel="stylesheet">
<link href="css/font-awesome.min.css" rel="stylesheet">
<script src="jquery.js" type="text/javascript"></script>
<script src="js/bootstrap.min.js"></script>
<style>
.del {
border-radius: 100%;
display: inline-block;
font-size: 13px;
height: auto;
margin-right: 4px;
padding: 5px;
}
.box {
height: 41px;
padding-top: 2px;
vertical-align: middle;
}
#uploadurl {
border: 1px solid #ccc;
margin-bottom: 7px;
margin-top: 14px;
padding-top: 11px;
}
</style>
<script>
var template = '<div class="form-group box">' +
'<input type="text" class="col-sm-5 form-control" name="title[]" placeholder="<?=$msg[0]?>">' +
'<input type="text" class="col-sm-6 form-control" name="url[]" placeholder="<?=$msg[1]?>">' +
'<i class="fa fa-times" aria-hidden="true"></i>' +
'<div class="progress-bar progress progress-bar-success myprogress" role="progressbar" style="width:0%">0%</div></div>';
$(document).ready(function(){
$('.add').on('click',function (e) {
$("#uploadurl").append(template);
});
$(document).on('click','.del',function (e) {
var del = $(this).closest('.box').index();
$('.box').eq(del).remove();
});
$('#submit').click(function (e) {
e.preventDefault();
$("input[name='url[]']").each(function (index, value){
$('.myprogress').eq(index).css('width', '0');
var url = $(this).val();
var title = $("input[name='title[]']").eq(index).val();
if(title == ""){
title = <?=strtotime(date('Y-m-d h:s:i'))?>;
}else{
title =<?=strtotime(date('Y-m-d h:s:i'))?>+"_"+title;
}
var data = "url="+url+"&title="+title;
$.ajax({
type: 'POST',
url: "upload.php",
data: data,
datatype:"json",
// contentType: "application/x-www-form-urlencoded",
processData: false,
// this part is progress bar
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
$('.myprogress').text(percentComplete + '%');
$('.myprogress').css('width', percentComplete + '%');
}
}, false);
return xhr;
},
success: function (data) {
$('#fileupload').append("<a style='display: block' href='"+data+"'>"+data+"</a>");
}
});
});
});
});
</script>
<div class="container">
<form id="upload-form" method="post">
<div id="uploadurl" class="col-md-12">
<div class="form-group box">
<input type="text" class="col-sm-5 form-control" name="title[]" placeholder="<?=$msg[0]?>">
<input type="text" class="col-sm-6 form-control" name="url[]" placeholder="<?=$msg[1]?>">
<div class="progress-bar progress-bar-success myprogress" role="progressbar" style="width:0%">0%</div>
</div>
</div>
<div style="display: block">
+
<input type="submit" class="btn btn-primary" id="submit" value="<?=$msg[2]?>" name="submit">
</div>
</form>
<div id="fileupload">
</div>
</div>
upload.php
$title = $_POST['title'];
$url = $_POST['url'];
$now = date('Y-m-d h:s:i');
$partition = date('Ym', strtotime($now));
$folder = "file/attach/".$partition."/";
if (!file_exists($folder)) {
$old = umask(0);
mkdir($folder, 0777);
umask($old);
}
$p = pathinfo($url);
$newfile = $folder.$title.".".$p['extension'];
if ( copy($url, $newfile) ) {
echo $newfile;
}else{
echo "false";
}
Click on the link below to view the demo
In the firebug you see, the file is still being uploaded
But the percentage of progress has been 100%.
demo
When I needed a progress bar to add to my file downloads(in my project); I used this code. I have tested this code also. Try the code below; I am quite sure it will serve your purpose:
<!doctype html>
<head>
<title>File Upload Progress Demo</title>
<style>
body { padding: 30px }
form { display: block; margin: 20px auto; background: #eee; border-radius:
10px; padding: 15px }
.progress { position:relative; width:400px; border: 1px solid #ddd; padding:
1px; border-radius: 3px; }
.bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px;
}
.percent { position:absolute; display:inline-block; top:3px; left:48%; }
</style>
</head>
<body>
<h1>File Upload Progress Demo #1</h1>
<code><input type="file" name="myfile"></code>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploadedfile"><br>
<input type="submit" value="Upload File to Server">
</form>
<div class="progress">
<div class="bar"></div >
<div class="percent">0%</div >
</div>
<div id="status"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js">
</script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
(function() {
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
$('form').ajaxForm({
beforeSend: function() {
status.empty();
var percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal)
percent.html(percentVal);
},
complete: function(xhr) {
bar.width("100%");
percent.html("100%");
status.html(xhr.responseText);
}
});
})();
</script>
</body>
</html>
My php upload file:
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error in the upload, please try again!";
}
?>
Hope it helps you and serve as a documentation for you...Happy coding

Chat application not working on internet server

I have a multi user chat application with four files as under:
log.html,
index.php,
post.php and
style.css
I have installed these on server (host :megaleech.in) & there are two following concerns that I am facing:
a) chat inputs do not reflect inside chat box when user press the send button.
b) We need to press exit button two times instead of one to take the user to login form.
You can see it on domain: http://demo.megaleech.in/chting/
It should be noted that this chat application is working perfectly fine on wamp server on my personal laptop and above mentioned concerns are only when I upload files to said internet server.
Please help in resolving concern.
Thanks in advance.
My codes are as under:
log.html : This is empty file
index.php
<?php
session_start();
function loginForm(){
echo'
<div id="loginForm">
<form action="index.php" method="post">
<p>Please enter your name to continue:</p>
<label for="name">Name:</label>
<input type="text" name="name" id="name" />
<input type="submit" name="enter" id="enter" value="Enter" />
</form>
</div>
' ;
}
if(isset($_POST['enter'])){
if($_POST['name'] != ""){
$_SESSION['name'] = stripslashes(htmlspecialchars($_POST['name']));
}
else{
echo '<span class="error">Please type in a name</span>';
}
}
?>
<?php
if(!isset($_SESSION['name'])){
loginForm();
}
else{
?>
<doctype html>
<head>
<title>Chat - Customer Module</title>
<link type="text/css" rel="stylesheet" href="style.css" />
</head>
<div id="wrapper">
<div id="menu">
<p class="welcome">Welcome, <b><?php echo $_SESSION['name']; ?></b></p>
<p class="logout"><a id="exit" href="#">Exit Chat</a></p>
<div style="clear:both"></div>
</div>
<div id="chatbox"><?php
if(file_exists("log.html") && filesize("log.html") > 0){
$handle = fopen("log.html", "r");
$contents = fread($handle, filesize("log.html"));
fclose($handle);
echo $contents;
}
?></div>
<form name="message" action="">
<input name="usermsg" type="text" id="usermsg" size="63" />
<input name="submitmsg" type="submit" id="submitmsg" value="Send" />
</form>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
// jQuery Document
$(document).ready(function(){
});
</script>
<script type="text/javascript">
// jQuery Document
$(document).ready(function(){
//If user wants to end session
$("#exit").click(function(){
var exit = confirm("Are you sure you want to end the session?");
if(exit==true){window.location = 'index.php?logout=true';}
});
});
$("#submitmsg").click(function(){
var clientmsg = $("#usermsg").val();
$.post("post.php", {text: clientmsg});
$("#usermsg").attr("value", "");
return false;
});
function loadLog(){
var oldscrollHeight = $("#chatbox").attr("scrollHeight") - 20; //Scroll height before the request
$.ajax({
url: "log.html",
cache: false,
success: function(html){
$("#chatbox").html(html); //Insert chat log into the #chatbox div
//Auto-scroll
var newscrollHeight = $("#chatbox").attr("scrollHeight") - 20; //Scroll height after the request
if(newscrollHeight > oldscrollHeight){
$("#chatbox").animate({ scrollTop: newscrollHeight }, 'normal'); //Autoscroll to bottom of div
}
},
});
}
setInterval("loadLog() ",1000);
</script>
<html>
<?php
}
?>
<?php
if(isset($_GET['logout'])){
//Simple exit message
$fp = fopen("log.html", 'a');
fwrite($fp, "<div class='msgln'><i>User ". $_SESSION['name'] ." has left the chat session.</i><br></div>");
fclose($fp);
session_destroy();
header("Location: index.php");
}
?>
style.css
body {
font:12px arial;
color: #222;
text-align:center;
padding:35px; }
form, p, span {
margin:0;
padding:0; }
input { font:12px arial; }
a {
color:#0000FF;
text-decoration:none; }
a:hover { text-decoration:underline; }
#wrapper, #loginform {
margin:0 auto;
padding-bottom:25px;
background:#EBF4FB;
width:504px;
border:1px solid #ACD8F0; }
#loginform { padding-top:18px; }
#loginform p { margin: 5px; }
#chatbox {
text-align:left;
margin:0 auto;
margin-bottom:25px;
padding:10px;
background:#fff;
height:270px;
width:430px;
border:1px solid #ACD8F0;
overflow:auto; }
#usermsg {
width:395px;
border:1px solid #ACD8F0; }
#submit { width: 60px; }
.error { color: #ff0000; }
#menu { padding:12.5px 25px 12.5px 25px; }
.welcome { float:left; }
.logout { float:right; }
.msgln { margin:0 0 2px 0; }
post.php
<?php
session_start();
if(isset($_SESSION['name'])){
$text = $_POST['text'];
$fp = fopen("log.html", 'a');
fwrite($fp, "<div class='msgln' id='chat".date("U")."'>(".date("g:i A").") <b>".$_SESSION['name']."</b>: ".stripslashes(htmlspecialchars($text))."<br></div>");
fclose($fp);
}
?>

jQuery does not delete user info

I have a php page that uses a jQuery to confirm before deleting data, Infact when I click delete it doesnt do anything the link doesnt do anything, I tried my efforts still nothing happens, please assist me
my code
teacher.php
<?php
require_once('../auth.php');
?>
<html>
<head>
<title>Silay Institute</title>
<link rel="stylesheet" href="../css/main.css" type="text/css" media="screen" />
<!--sa poip up-->
<link href="src/facebox.css" media="screen" rel="stylesheet" type="text/css" />
<script src="lib/jquery.js" type="text/javascript"></script>
<script src="src/facebox.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('a[rel*=facebox]').facebox({
loadingImage : 'src/loading.gif',
closeImage : 'src/closelabel.png'
})
})
</script>
<link rel="stylesheet" href="febe/style.css" type="text/css" media="screen" charset="utf-8">
<script src="argiepolicarpio.js" type="text/javascript" charset="utf-8"></script>
<script src="js/application.js" type="text/javascript" charset="utf-8"></script>
<style>
#mainhhh {
background: none repeat scroll 0 0 #FFFFFF;
border: 8px solid #EEEEEE;
border-radius: 5px 5px 5px 5px;
box-shadow: 0 0 10px #4E707C;
font: 11px "Trebuchet MS",Verdana,Arial,Helvetica,sans-serif;
margin: 5em auto;
position: relative;
text-align: left;
width: 1000px;
}
#mainhhh h1 {
background: none repeat scroll 0 0 #0092C8;
border-bottom: 1px solid #007DAB;
color: #FFFFFF;
font-size: 14px;
margin: 0;
padding: 5px 10px;
text-shadow: 0 1px 0 #007DAB;
}
</style>
</head>
<body>
<div id="mainhhh">
<h1>
<a id="addq" href="index.php" title="click to enter homepage" style="background-image:url('../images/out.png'); background-repeat:no-repeat; padding: 3px 12px 12px; margin-right: 10px;"></a>
<label for="filter">Filter</label> <input type="text" name="filter" value="" id="filter" />
<a rel="facebox" href="addteacher.php" id="addq">Add Teacher</a>
</h1>
<table cellpadding="1" cellspacing="1" id="resultTable">
<thead>
<tr>
<th style="border-left: 1px solid #C1DAD7"> Name </th>
<th>ID Number</th>
<th>Work</th>
<th>Gender</th>
<th>Status</th>
<th>Birthday</th>
<th>Advisory</th>
<th> Action </th>
</tr>
</thead>
<tbody>
<?php
include('../connect.php');
$result = mysql_query("SELECT * FROM teacher");
while($row = mysql_fetch_array($result))
{
echo '<tr class="record">';
echo '<td style="border-left: 1px solid #C1DAD7">'.$row['fname'].' '.$row['mname'].' '.$row['lname'].'</td>';
echo '<td><div align="left">'.$row['idnumber'].'</div></td>';
echo '<td><div align="left">'.$row['work'].'</div></td>';
echo '<td><div align="left">'.$row['gender'].'</div></td>';
echo '<td><div align="left">'.$row['status'].'</div></td>';
echo '<td><div align="left">'.$row['bday'].'</div></td>';
echo '<td><div align="left">';
$sdsd=$row['idnumber'];
$results = mysql_query("SELECT * FROM `teacher` JOIN `advisory` ON `advisory`.`tid`=`teacher`.`idnumber`");
while($rows = mysql_fetch_array($results))
{
echo $rows['level'].' section '.$rows['section'];
}
echo '</div></td>';
echo '<td><div align="center"><a rel="facebox" href="editprofile.php?id='.$row['id'].'" title="Click To Edit">Edit Profile</a> | delete</div></td>';
echo '</tr>';
}
?>
</tbody>
</table>
</div>
<script src="js/jquery.js"></script>
<script type="text/javascript">
$(function() {
$(".delbutton").click(function(){
//Save the link in a variable called element
var element = $(this);
//Find the id of the link that was clicked
var del_id = element.attr("id");
//Built a url to send
var info = {'id': del_id};
if(confirm("Sure you want to delete this update? There is NO undo!"))
{
$.ajax({
type: "GET",
url: "deleteteacher.php",
data: info,
success: function(){
}
});
$(this).parents(".record").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow");
}
return false;
});
});
</script>
</body>
</html>
deleteteacher.php
<?php
// This is a sample code in case you wish to check the username from a mysql db table
include('../connect.php');
if($_GET['id'])
{
$id = intval($_GET['id']);
$sql = "delete from teacher where id='$id'";
mysql_query( $sql);
}
?>
As I remember, you should send a JSON object as data; its means you should make a dictionary, not just an assignment. When you write $_GET['id'] compiler searches for an element in the data dictionary with key "id" to returns its value; but since you don't send a dictionary structured data, it returns NULL and of course nothing will happen.
You should write something like this in your delete function:
var info = {'id': del_id};

passing dynamic textboxes via javascript to php

I have a page where as the user can create dynamic textboxs that are resizable and draggable using jquery on the click of a button.
I want to pass the data in the textboxes plus the height width and position of them on the page from javascript to php.
I am at a bit of a block on this any help appreciated.
heres my code
<!DOCTYPE html>
<html>
<meta charset="utf-8" />
<?
if($_SERVER['REQUEST_METHOD'] == "POST") {
$posted=$_POST['textarea'];
echo "posted=".$new_post."<br>";
}
?>
<head>
<style>
body{background-color:#ccc;}
.dragbox{position:absolute;top:20px;width:320px; height:0;padding: 0.0em; margin:25px; border:0;cursor:move; z-index:1;display: block; }
.textarea1{ width: 300px; height: 300px; padding: 0.5em;}
#handle{
display: block;
height: 16px;
width: 100px;
background-color: red;
position: relative;
top:10px;
font-size:10px;
}
</style>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.1/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.1/jquery-ui.js"></script>
</head>
<body>
<form id="frmMain" name="frmMain" enctype="multipart/form-data" action="dynamic_div.php" method="post">
<script>
var i=0;
var p=75;
function creatediv1(id) {
id=id+i;
var xp=xp+i;
var newdiv = document.createElement('div');
newdiv.setAttribute('id', id);
newdiv.setAttribute('class', 'dragbox');
newdiv.setAttribute('contenteditable','true');
newdiv.style.position = "relative";
newdiv.style.top = p;
newdiv.style.cursor='move';
newdiv.innerHTML = "<div id='handle'>Drag me into position</div></div><br><textarea id="+i +" name='textarea["+i+"]' class='textarea1' width='300' style='overflow-y: auto;background-color:transparent;border: 2px dashed #000; '>some text here</textarea>";
document.body.appendChild(newdiv);
$(function() {
$( "#"+id ).draggable({
// Find position where image is dropped.
stop: function(event, ui) {
// Show dropped position.
var Stoppos = $(this).position();
$("div#stop").text("STOP: \nLeft: "+ Stoppos.left + "\nTop: " + Stoppos.top);
alert("left="+Stoppos.left+"top="+Stoppos.top);
}
});
$("#"+i).resizable({
stop: function(event, ui) {
var width = ui.size.width;
var height = ui.size.height;
alert("width="+width+"height="+height);
}
});
$("#"+i).draggable({handle:"#handle"});
});
i++;
p=p+25;
}
</script>
<input id="btn1" type="button" value="Add New textbox" onclick="creatediv1('draggable');" />
<input type="submit" value="Submit" >
</form>
</body>
</html>
From the above discussion I understand that you are facing problem in getting the dynamically added Textboxes data in PHP, what I can suggest try using
<?php
print_r($_POST["textarea"]); //just for debugging
foreach ($_POST["textarea"] as $text_area) {
//do what you want with $text_area
}
?>
EDIT
from java script change
....
newdiv.innerHTML = "<div id='handle'>Drag me into position</div></div><br><textarea id="+i +" name='textarea[]' class='textarea1' width='300' style='overflow-y: auto;background-color:transparent;border: 2px dashed #000; '>some text here</textarea>";
and then try above php code.
EDIT 1
<!DOCTYPE html>
<html>
<meta charset="utf-8" />
<?
if($_SERVER['REQUEST_METHOD'] == "POST") {
$posted=$_POST['textarea'];
echo "posted=".$new_post."<br>";
}
?>
<head>
<style>
body{background-color:#ccc;}
.dragbox{position:absolute;top:20px;width:320px; height:0;padding: 0.0em; margin:25px; border:0;cursor:move; z-index:1;display: block; }
.textarea1{ width: 300px; height: 300px; padding: 0.5em;}
#handle{
display: block;
height: 16px;
width: 100px;
background-color: red;
position: relative;
top:10px;
font-size:10px;
}
</style>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.1/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.1/jquery-ui.js"></script>
</head>
<body>
<form id="frmMain" name="frmMain" enctype="multipart/form-data" action="dynamic_div.php" method="post">
<script>
var i=0;
var p=75;
function creatediv1(id)
{
id=id+i;
var xp=xp+i;
var newdiv = document.createElement('div');
newdiv.setAttribute('id', id);
newdiv.setAttribute('class', 'dragbox');
newdiv.setAttribute('contenteditable','true');
newdiv.style.position = "relative";
newdiv.style.top = p;
newdiv.style.cursor='move';
newdiv.innerHTML = "<div id='handle'>Drag me into position</div></div><br><textarea id="+i +" name='textarea[]' class='textarea1' width='300' style='overflow-y: auto;background-color:transparent;border: 2px dashed #000; '>some text here</textarea>";
//Updated this line
document.getElementById("frmMain").appendChild(newdiv);
$(function()
{
$( "#"+id ).draggable(
{
stop: function(event, ui)
{
var Stoppos = $(this).position();
$("div#stop").text("STOP: \nLeft: "+ Stoppos.left + "\nTop: " + Stoppos.top);
$('.textarea1').append("left="+Stoppos.left+"top="+Stoppos.top);
}
});
$("#"+i).resizable(
{
stop: function(event, ui)
{
var width = ui.size.width;
var height = ui.size.height;
$('.textarea1').append("width="+width+"height="+height);
}
});
$("#"+i).draggable({handle:"#handle"});
});
i++;
p=p+25;
}
</script>
<input id="btn1" type="button" value="Add New textbox" onclick="creatediv1('draggable');" />
<input type="submit" value="Submit" >
</form>
</body>
</html>
In this $( "#"+id ).draggable({ code you will get undefined id error because var id is not in Global scope.
and second you will never get value of id if you set it in Global because creatediv1 function set ID value but it will execute when html is fully loaded where as document.ready code will execute when html gets loaded so ID value will always comes up with error,
Try
<!DOCTYPE html>
<html>
<meta charset="utf-8" />
<?
if($_SERVER['REQUEST_METHOD'] == "POST") {
$posted=$_POST['textarea'];
echo "posted=".$new_post."<br>";
}
?>
<head>
<style>
body{background-color:#ccc;}
.dragbox{position:absolute;top:20px;width:320px; height:0;padding: 0.0em; margin:25px; border:0;cursor:move; z-index:1;display: block; }
.textarea1{ width: 300px; height: 300px; padding: 0.5em;}
#handle{
display: block;
height: 16px;
width: 100px;
background-color: red;
position: relative;
top:10px;
font-size:10px;
}
</style>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.1/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.1/jquery-ui.js"></script>
</head>
<body>
<form id="frmMain" name="frmMain" enctype="multipart/form-data" action="dynamic_div.php" method="post">
<script>
var i=0;
var p=75;
function creatediv1(id)
{
id=id+i;
var xp=xp+i;
var newdiv = document.createElement('div');
newdiv.setAttribute('id', id);
newdiv.setAttribute('class', 'dragbox');
newdiv.setAttribute('contenteditable','true');
newdiv.style.position = "relative";
newdiv.style.top = p;
newdiv.style.cursor='move';
newdiv.innerHTML = "<div id='handle'>Drag me into position</div></div><br><textarea id="+i +" name='textarea["+i+"]' class='textarea1' width='300' style='overflow-y: auto;background-color:transparent;border: 2px dashed #000; '>some text here</textarea>";
document.body.appendChild(newdiv);
$(function()
{
$( "#"+id ).draggable(
{
stop: function(event, ui)
{
var Stoppos = $(this).position();
$("div#stop").text("STOP: \nLeft: "+ Stoppos.left + "\nTop: " + Stoppos.top);
$('.textarea1').append("left="+Stoppos.left+"top="+Stoppos.top);
}
});
$("#"+i).resizable(
{
stop: function(event, ui)
{
var width = ui.size.width;
var height = ui.size.height;
$('.textarea1').append("width="+width+"height="+height);
}
});
$("#"+i).draggable({handle:"#handle"});
});
i++;
p=p+25;
}
</script>
<input id="btn1" type="button" value="Add New textbox" onclick="creatediv1('draggable');" />
<input type="submit" value="Submit" >
</form>
</body>
</html>
try this :
name='textarea[]'
<?php
echo "<pre>";
print_r($_POST["textarea"]); //just for debugging
echo "<pre>";
for($i=0; $i<count($_POST["textarea"]);$i++) {
//$_POST["textarea"][i] ...
}
?>

Categories