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);
}
?>
Related
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
I have a form which i want to post problem is this when ever page refresh form submit auto I just want form only form submit when I click on the button.otherwise form not post thanks in advance
<?php
session_start();
//mail("ifaisal24#gmail.com","hhhhhh",print_r($_REQUEST,TRUE));
define('HOST','xxxxx');
define('USER','xxxxx');
define('PASS','Ixxxxx_');
define('DB','xxxx');
$con = mysqli_connect(HOST,USER,PASS,DB);
require_once 'include/DB_Functions.php';
if (!isset($_SESSION['email'])){
?>
<script>
window.location = 'login2.php';
</script>
<?php
}
$db = new DB_Functions();
$response = array("error" => FALSE);
if (isset($_POST['sender_email'])&& isset($_POST['reciver_email'])&& isset($_POST['data'])) {
// receiving the post params
$sender_email = $_SESSION['email'];
$_POST['sender_email']=$_SESSION['email'];
$reciver_email = $_POST['reciver_email'];
$data =$sender_email.' : '. $_POST['data'];
///echo $sender_email;
//die();
// create a new chat
$user_data = $db->storeData($data,$sender_email,$reciver_email);
//die;
if ($user_data) {
// chat stored successfully
$response["error"] = FALSE;
// $response["uid"] = $user_data["unique_id"];
$response["user_data"]["sender_email"] = $user_data["sender_email"];
$response["user_data"]["reciver_email"] = $user_data["reciver_email"];
$response["user_data"]["data"] = $user_data["data"];
$response["user_data"]["created_at"] = $user_data["created_at"];
echo json_encode($response);
}
}
// if (isset($_REQUEST['sender_email'])&& isset($_REQUEST['reciver_email'])&& isset($_REQUEST['fatch_server_data'])) {
// $sender_email = $_REQUEST['sender_email'];
// $reciver_email = $_REQUEST['reciver_email'];
$sql = "select * from user_data WHERE (sender_email='$sender_email' AND reciver_email='$reciver_email') OR
(reciver_email ='$sender_email' AND sender_email='$reciver_email')" ;
//$sql = "select * from user_data";
$res = mysqli_query($con,$sql)or mysql_error();
$resultt = array();
while($row = mysqli_fetch_array($res)){
array_push($resultt,
array(
'data'=>$row[3],
'created_at'=>$row[4]
// 'email'=>$row[3]
));
}
// }
json_encode(array("resultt"=>$resultt));
mysqli_close($con);
?>
<?php
define('HOST','mxxxxx');
define('USER','axxxxxxx');
define('PASS','Ixxxxxxx_');
define('DB','axxxxxxxx');
$con = mysqli_connect(HOST,USER,PASS,DB);
$sql = "select * from users";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array(
// 'id'=>$row[0],
'email'=>$row[3],
));
}
json_encode(array("result"=>$result));
mysqli_close($con);
?>
<html>
<head>
<style>
#userschat {
font-family:tahoma;
font-size:12px;
color:black;
border: 5px teal solid;
height: 325px;
width: 300px;
overflow-y:scroll;
}
#usersOnLine {
font-family:tahoma;
font-size:12px;
color:black;
border: 10px teal solid;
height: 625px;
width: 300px;
overflow-y:scroll;
}
#allcon{
margin-bottom: 15px;
font-family:tahoma;
font-size:12px;
color:black;
border: 10px teal solid;
height: 40px;
width: 300px;
}
#contact{
float:right;
}
#all{
float:left;
}
#data {
width: 250px;
height: 30px;
border: 5px teal solid;
float:left;
margin-top:1px;
}
#send {
border: 5px teal solid;
width: 57px;
height: 30px;
float:right;
margin:1px;
}
.container{
width:970px;
height:auto;
margin:0 auto;
}
#messageForm{
}
.clickAble{
display: inline-block;;
cursor:pointer;
}
</style>
<meta http-equiv="refresh" content="600">
</head>
<body bgcolor="beige">>
<div class="container">
<form method="post" action="login2.php">
<input type="submit" id="l_btn" name="l_btn" value="Logout" />
</form>
<?php
if ($_POST) {
// here is where your code would be included
session_destroy();
header("Location:chat.php" . $_SERVER['REQUEST_URI']);
exit();
}
?>
<div id = "welcome"><h2>Welcome to Chat</h2>
<?php echo $_SESSION['email']; ?>
</div>
<div id = "all">
<h1> Chat Box</h1>
<div id="receiver">
<h3>receiver</h3>
<!-- NOTICE THAT THIS IS NEW NOW... -->
<!-- IT'S IMPORTANT THAT YOU HAVE THIS PARAGRAPH EXACTLY AS IT IS HERE -->
<p class='bubbled-data'></p>
</div>
<div id="sender"><h3>sender</h3>
<?php echo $_SESSION['email']; ?>
</div>
<div id="userschat">
<h4 style = " margin-top: 4px; margin-left: 7px">
<?php
foreach($resultt as $key => $val)
{
echo $val['data'];
echo "<br>";
echo $val['created_at'];
echo "<br>";
echo "<br>";
}
?>
</h4>
</div>
<form id="messageForm" action = "<?php $_PHP_SELF ?>" method = "POST">
<input type="hidden" name="sender_email" id="sender_email" value="">
<input type="hidden" name="reciver_email" id="reciver_email" value="">
<input type="text" name="data" id="data" placeholder="data" onFocus="fun1(this)" onBlur="fun2(this)" required="" />
<input id="send" type="submit" value="Send">
</form>
</div>
<div id = "contact">
<div id = "allcon">
<h1 style = " text-align: center; margin-top: 4px;"> All Contacts </h1>
</div>
<div id="usersOnLine" >
<h2 style = " margin-top: 4px; margin-left: 7px">
<?php
foreach($result as $key => $val){
echo "<span class='clickAble'>" . $val['email'] . "</span>";
echo "<br>";
echo "<br>";
}
?>
</h2>
</div>
</div>
</div>
<!-- JAVASCRIPT - JQUERY -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript">
var objDiv = document.getElementById("userschat");
objDiv.scrollTop = objDiv.scrollHeight;
(function ($) {
$(document).ready(function (e) {
var receiver = $("#receiver");
var clickAbles = $(".clickAble");
receiver.find(".bubbled-data").text(localStorage.getItem("nameValue"));
$("#reciver_email").val(localStorage.getItem("nameValue"));
// BIND THE clickAble SPAN TO AN ON-CLICK EVENT...
// SO THAT WITH EACH CLICK, YOU CAN SIMPLE APPEND THE CONTENT OF THAT SPAN TO THE RECEIVER DIV
clickAbles.on("click", function (evt) {
var nameValue = $(this).text();
receiver.find(".bubbled-data").text(nameValue);
$("#reciver_email").val(nameValue);
localStorage.setItem("nameValue", nameValue);
});
});
})(jQuery);
</script>
</body>
</html>
here is the full code.i edit it
A Post/Redirect/Get design would be a viable solution to your problem. An example of code that would accomplish this is:
if ($_POST) {
// here is where your code would be included
header("Location: " . $_SERVER['REQUEST_URI']);
exit();
}
The header function then redirects the user to the same page, which means that the $_POST information is lost, hence refreshing the page would not re-send the form.
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.
hello am building a form that uploads images, it works correctly, but i want to add something extra, to be able to specify what the image would saved as. this is what i have, code snippet
<?php
//upload.php
$output_dir = "uploads/";
if(isset($_FILES["myfile"]))
{
//Filter the file types , if you want.
if ($_FILES["myfile"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
//move the uploaded file to uploads folder;
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir. $_FILES["myfile"]["name"]);
echo "Uploaded File :".$_FILES["myfile"]["name"];
}
}
?>
HTML:
<!doctype html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<style>
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>Ajax File Upload Demo</h1>
<form id="myForm" action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" size="60" name="myfile">
<input type="submit" value="Ajax File Upload">
</form>
<div id="progress">
<div id="bar"></div>
<div id="percent">0%</div >
</div>
<br/>
<div id="message"></div>
<script>
$(document).ready(function()
{
var options = {
beforeSend: function()
{
$("#progress").show();
//clear everything
$("#bar").width('0%');
$("#message").html("");
$("#percent").html("0%");
},
uploadProgress: function(event, position, total, percentComplete)
{
$("#bar").width(percentComplete+'%');
$("#percent").html(percentComplete+'%');
},
success: function()
{
$("#bar").width('100%');
$("#percent").html('100%');
},
complete: function(response)
{
$("#message").html("<font color='green'>"+response.responseText+"</font>");
},
error: function()
{
$("#message").html("<font color='red'> ERROR: unable to upload files</font>");
}
};
$("#myForm").ajaxForm(options);
});
</script>
</body>
</html>
Give this a try, however you'll need to do some work on certain validation.
It uses a form input <input type="text" name="upload_name"> to give it a custom name.
Tested
HTML form
<!doctype html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<style>
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>Ajax File Upload Demo</h1>
<form id="myForm" action="upload.php" method="post" enctype="multipart/form-data">
Name it:
<input type="text" name="upload_name">
<br>
<input type="file" size="60" name="myfile">
<input type="submit" value="Ajax File Upload">
</form>
<div id="progress">
<div id="bar"></div>
<div id="percent">0%</div >
</div>
<br/>
<div id="message"></div>
<script>
$(document).ready(function()
{
var options = {
beforeSend: function()
{
$("#progress").show();
//clear everything
$("#bar").width('0%');
$("#message").html("");
$("#percent").html("0%");
},
uploadProgress: function(event, position, total, percentComplete)
{
$("#bar").width(percentComplete+'%');
$("#percent").html(percentComplete+'%');
},
success: function()
{
$("#bar").width('100%');
$("#percent").html('100%');
},
complete: function(response)
{
$("#message").html("<font color='green'>"+response.responseText+"</font>");
},
error: function()
{
$("#message").html("<font color='red'> ERROR: unable to upload files</font>");
}
};
$("#myForm").ajaxForm(options);
});
</script>
</body>
</html>
PHP
<?php
$upload_name = $_POST['upload_name'];
$idx = strpos($_FILES['myfile']['name'],'.');
$ext = substr($_FILES['myfile']['name'],$idx);
$file_name = $upload_name . $ext;
$output_dir = "uploads/";
if(isset($_FILES["myfile"]))
{
//Filter the file types , if you want.
if ($_FILES["myfile"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
//move the uploaded file to uploads folder;
// move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir. $_FILES["myfile"]["name"]);
// echo "Uploaded File :".$_FILES["myfile"]["name"];
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir.$file_name);
echo "Uploaded File :" . $file_name;
}
}
?>
Footnotes:
Link to their project page http://malsup.com/jquery/form/ where you can download all the files, rather than fetching the JS from their website.
I have followed this example to upload file using AJAX. File is being uploaded successfully but the problem is stopUpload function is not invoked from uploadServer.php file. Can anyone tell me what I'm doing wrong? Here's my code -
Client side script - uploadfile.html
<html>
<body>
<style type="text/css">
#f1_upload_process{
z-index:100;
position:absolute;
visibility:hidden;
text-align:center;
width:400px;
margin:0px;
padding:0px;
background-color:#fff;
border:1px solid #ccc;
}
form{
text-align:center;
width:390px;
margin:0px;
padding:5px;
background-color:#fff;
border:1px solid #ccc;
}
</style>
<p id="f1_upload_process">Loading...<br/><img src="loader.gif" /></p>
<p id="resultp"></p>
<form action="http://aiworker2.usask.ca/uploadServer.php" method="post" enctype="multipart/form-data" target="upload_target" onsubmit="startUpload();" >
File: <input name="myfile" type="file" />
<input type="submit" name="submitBtn" value="Upload" />
</form>
<iframe id="upload_target" name="upload_target" src="#" style="width:0;height:0;border:0px solid #fff;"></iframe>
<script type="text/javascript">
function startUpload(){
document.getElementById('f1_upload_process').style.visibility = 'visible';
return true;
}
function stopUpload(success){
alert('in stopUpload: '+ success);
var result = '';
document.getElementById('f1_upload_process').style.visibility = 'hidden';
if (success == 1){
document.getElementById('resultp').innerHTML ='<span class="msg">The file was uploaded successfully!<\/span><br/><br/>';
}
else {
document.getElementById('resultp').innerHTML ='<span class="emsg">There was an error during file upload!<\/span><br/><br/>';
}
return true;
}
</script>
</body>
</html>
Server Side script - uploadServer.php
<?php
$destination_path = getcwd().DIRECTORY_SEPARATOR;
$result = 0;
$target_path = $destination_path . basename( $_FILES['myfile']['name']);
if(#move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
$result = 1;
}
//sleep(1);
echo '<script language="javascript" type="text/javascript">';
echo 'window.top.window.stopUpload(\''.$result.'\');';
echo '</script>';
?>
Thanks