PHP & jQuery ajax Chat - php

I have created a chat application using PHP, mysql, and ajax for posting data to the server. I have tested it by spamming the chat repeatedly, and everything works for about 7 or 8 seconds until my chat will not post further. On refresh, I get a "NO DATA RECEIVED" error from google chrome. Basically I think I am overloading my site. Is there a way that I could optimize this chat? Or is it not a server-side issue at all?
This is my jQuery that is posting to my server:
$(document).ready(getMessage());
//Send message
$('#send').click(function() {
var message = $('#message').val();
var username = $('#un').val();
var id = $('#id').val();
var fullname = $('#name').val();
$.ajax({
url: 'chat/send_message.php',
type: 'POST',
data: {
message: message,
username: username,
user_id: id,
fullname: fullname
},
success: function() {
$('#message').val('');
getMessage();
}
});
return false;
});
function getMessage() {
$.post('chat/get_message.php', {getMessage: true}, function(message) {
$('#chatbox').html(message);
$('#chatbox').scrollTop($('#chatbox')[0].scrollHeight);
});
}
setInterval(getMessage, 5000);
This is the PHP that handles the sending of the message. It just stores it in a database:
<?php
//Message sending
if(isset($_POST['message'])) {
try {
$pdo = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');
} catch (PDOException $e) {
echo("Could not connect to the server.");
}
$message = $_POST['message'];
$timesent = date('Y-m-d H:i:s');
$id = $_POST['user_id'];
$fullname = $_POST['fullname'];
$username = $_POST['username'];
$query = $pdo->prepare("INSERT INTO `message`(`message`,`user_id`,`timesent`,`fullname`,`username`) VALUES (:message,:user_id,:timesent,:fullname,:username)");
$query->execute(array(
':message' => $message,
':user_id' => $id,
':timesent' => $timesent,
':fullname' => $fullname,
':username' => $username,
));
} else {
echo("Could not send message");
}
This is my HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><head>
<?php
include 'resources/head.php';
if(!$user->isLoggedIn()) {
Redirect::to('index.php');
}
?>
<title>GoonSquad | Chat</title>
<style type="text/css">
form, p, span {
margin:0;
padding:0; }
input { font:12px arial; }
a {
color:#0000FF;
text-decoration:none; }
a:hover { text-decoration:underline; }
#wrapper {
margin:0 auto;
padding-bottom:0;
background: rgba(0, 0, 0, 0.13);
width: 1000px;;
border:1px solid #ACD8F0;
text-align: center;
}
#chatbox {
text-align:left;
margin:0 auto;
margin-bottom:25px;
padding:10px;
background:#fff;
height:400px;
width:940px;
border:1px solid #ACD8F0;
overflow:auto; }
#message {
width:860px;
border:1px solid #ACD8F0;
margin-right: 5px;
}
#submit { width: 60px; }
.error { color: #ff0000; }
#menu { padding:12.5px 25px 12.5px 25px; }
.welcome {
margin-left:auto;
margin-right: auto;
margin-top: 20px;
font-size: 150%;
}
.message {
width: 100%;
height: auto;
background-color: #cccccc;
margin-bottom: 6px;
border-radius: 3px;
padding: 6px;
}
.msgln { margin:0 0 2px 0; }
</style>
</head>
<body>
<?php include 'resources/header.php' ?>
<div id="row">
<div id="large-9 columns" class="override" role="content">
<div id="wrapper" class="left-align">
<div id="menu">
<p class="welcome">GoonSquad Chat</p>
<div style="clear:both"></div>
</div>
<div id="chatbox">
</div>
<form id="messenger" action="" enctype="multipart/form-data">
<input type="text" id="message" class="left" autocomplete="off" size="63" maxlength="2000">
<input type="submit" id="send" class="button tiny" value="Send" >
<input type="hidden" id="id" value="<?php echo $user->data()->id; ?>">
<input type="hidden" id="name" value="<?php echo $user->data()->fullname?>">
<input type="hidden" id="un" value="<?php echo $user->data()->username?>"
</form>
</div>
</div>
</div>
<script type="text/javascript" src="scripts/chat.js"></script>
</body>
</html>

Related

How to insert data in database through jQuery Ajax in php

Hello stack right now I am facing a problem I am unable to insert data in database through jQuery Ajax I have attached all related files Can anyone go through it I am new in php development.
**task.php**
<html>
<head>
<style type="text/css">
html, body {
margin: 5px;
padding: 5px;
background: #fff;
}
form {
border: 1px solid #999;
padding: 0.25em;
background: #EEE;
}
div {
padding-bottom: 0.25em;
}
/* essential */
label {
float: left;
width: 6em;
text-align: right;
padding-right: 0.5em;
}
input, textarea {
text-align: left;
width: 200px;
height:30px;
}
input.submit {
margin-left: 6.5em;
width: auto;
}
label, input.submit {
font: normal 0.8em Verdana, Geneva, Arial, Helvetica, sans-serif;
}
</style>
<script src="jquery-3.3.1.js"></script>
<script src="insert.js"></script>
<script>
</script>
</head>
<body>
<h1>FORM</h1>
<form>
<div>
<label>Name:</label>
<input type="text" name="name" id="Name" />
</div>
<div>
<label>Age:</label>
<input type="text" name="age" id="age"/>
</div>
<div>
<label>Email Id:</label>
<input type="text" name="emailId" id="emailId"/>
</div>
<div>
<label>Password:</label>
<input type="text" name="password" id="pass"/>
</div>
<div>
<input type="submit" id="submit" name="submit" value="Submit" onclick="insertData()" />
</div>
</form>
</body>
</html>
This is my insert.php file where I have write all query related to insert my data.
**insert.php**
<?php
include("connection.php");
if(isset($_POST['submit']))
{
$Fname=$_POST["name"];
$Age=$_POST["age"];
$EmailId=$_POST["emailId"];
$Password=$_POST["password"];
$Insert = "INSERT INTO simpleform (Name, Age, Email_Id, Password)
VALUES ('.$Fname.', '.$Age.', '.$EmailId.', '.$Password.')";
$Query=mysqli_query($con, $Insert);
print_r($Insert);
if(!$Query)
{
echo mysqli_error();
}
else
{
echo "Successfully Inserted <br />";
}
}
?>
This is my insert.js file where I did all ajax related work.
**insert.js**
function insertData() {
debugger;
var name=$("#Name").val();
var age=$("#age").val();
var emailId=$("#emailId").val();
var pass=$("#pass").val();
debugger;
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "kamalesh/insert.php",
data: {name:name,age:age,emailId:emailId,pass:pass},
dataType: "JSON",
success: function(data) {
alert("Data Inserted");
}
});
}
It looks like In your insert.php the if(isset($_POST['submit'])) is preventing the script from running when your insert.js function passes parameters to insert.php. When AJAX passes parameters to insert.php, the isset($_POST['submit']) will return false.
You will need to remove the if(isset($_POST['submit'])) from nsert.php. I will also suggest you to prevent the form from submitting and refreshing your page. Look into e.preventDefault.
Also for your $insert query you should remove the "." before and after each variable in the "VALUES". They are not needed.

A large box keeps appearing above the form

I have a small problem with my website's contact page. Whenever I use php for the form another large box appears above the form as if there was a additional set of <p> tags there; I am not sure why this keeps happening.
Here is the code.
Update: I have removed the box problem but now I have to figure out the css to change so that the form fits in with the rest of the webpage, and auto; doesn't work.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Cromika Web Designs - Contact</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script type="text/javascript">
function checkForm() {
var theName = document.getElementById('name').value;
var theEmail = document.getElementById('email').value;
var theMessage = document.getElementById('message');
var emailerr = document.getElementById('emailspan');
var nameerr = document.getElementById('namespan');
var messageerr = document.getElementById('messagespan');
var message;
var myregex = /\S+#\S+\.\S+/;
if(theName==""){
message = 'Name is required;';
document.form1.name.focus();
nameerr.innerHTML = message;
return false;
} else{
nameerr.innerHTML ="";
}
if(theEmail=="") {
message = 'Email is required;';
document.form1.email.focus();
emailerr.innerHTML = message;
return false;
} else if (!myregex.test(theEmail)){
emailerr.innerHTML = "Your email entry is invalid;";
document.form1.email.focus();
return false;
} else {
emailer.innerHTML ="";
}
if(theMessage.value=="" || theMessage.value ==null || theMessage.value.indexOf('\n') > 0) {
message = 'Please enter your message;';
document.form1.message.focus();
messageerr.innerHTML = message;
return false;
} else {
messageerr.innerHTML = "";
}
}
</script>
</head>
<body>
<header><img src="images/simple-logo.png" alt=""</img> </header>
<nav>
<ul>
<li>Home</li>
<li>About</li>
<li>Contact</li>
<li>Gallery</li>
</ul>
</nav>
<h1> Contact me!</h1>
<?php
if(isset($_POST['send_email'])){
// collect the form values
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
// set the email properties
$to = 'email#email.com';
$subject = "Contact Form Submission";
$from = $email;
$headers = "From: $from";
// attempt to send the mail, catch errors if they occur
try {
mail($to, $subject, $message, $headers);
$msg = "<strong>Your mail was sent successfully!</strong>";
} catch(Exception $e) {
$msg = "An Exception was thrown: ".$e -> getMessage()."<br>";
}
}
?>
<table align="left">
<form name="form1" method="post" action="<?php $_SERVER['PHP_SELF']?>" onSubmit="return checkForm()">
<tr><th>Name:</th>
<td><input type="text" name="name" id="name" /><br><span style="color:red;" id="namespan"></span>
</td>
</tr>
<tr><th>Email:</th>
<td><input type="text" name="email" id="email" /><br><span style="color:red;" id="emailspan"></span>
</td>
</tr>
<tr><th>Message:</th>
<td><textarea name="message" id="message"></textarea><br><span style="color:red;" id="messagespan"></span>
</td>
</tr>
<tr><td></td><td><input type="submit" name="send_email" value="Send Email Message" /></td></tr>
</form>
</table>
<footer></footer>
</body>
</html>
And here is the CSS for the site
#charset "UTF-8";
/* CSS Document */
body{
font-size:16px;
cursor:default;
font-family:Georgia, serif;
background-color:#000000;
color: white;
}
header {
border-radius: 5px;
text-align: center;
margin-top: 12px;
height: 71px;
}
nav {
border-radius: 5px;
height: 20px;
width: auto;
display: block;
text-align:center;
padding-right: 35px;
color: #ffffff;
font-weight:bold;
background-color:#8000aa;
padding-top: .05px;
padding-bottom: 20px;
margin-top: 12px;
margin-bottom: 12px;}
nav li {
display: inline;
float: center;
}
nav a {
display: block, inline;
width: 60px;
}
/*link styles*/
a:link {
text-decoration: none;
}
a:visited {
text-decoration: underline;
color: white;
}
a:hover {
text-decoration: underline;
color: blue;
}
a:active {
text-decoration: underline;
}
/* end link styles */
/* main content */
h1 {
border-radius: 5px;
width: auto;
margin: 0 auto;
text-align: center;
margin-bottom: 12px;
background-color: #8000aa;}
table {
border-radius: 5px;
width: 36px;
height: 150px;
margin: 0 auto;
text-align: center;
padding-top:12px;
padding-bottom:12px;
margin-bottom: 12px;
background-color: #8000aa;
}
p {
border-radius: 5px;
width: auto;
height: auto;
margin: 0 auto;
text-align: center;
padding-top:12px;
padding-bottom:12px;
margin-bottom: 12px;
background-color: #8000aa;}
p a {
font-weight: bold;
}
/* end main content*/
footer {
border-radius: 5px;
clear: both;
text-align: center;
padding-top:12px;
padding-bottom:12px;
margin-bottom: 12px;
font-weight:bold;
background-color:#8000aa;}
Any help is appreciated!
Try removing the <p> and </p> from around the table you use for your form. While on my test system this didn't put an actual box, it certainly pushed the form part well down the page.
FYI, I used Google Chrome and right click and select Inspect Element and it's showed up quite quickly.

jQuery get keyup on current change on input and output live

I had attempted with the following code and a little stuck now but here is what I'm wanting to achieve:
enter value in input and update preview html below
once user is happy with preview output can click generate
once clicked generate it will actually write the preview HTML to a first_name-last_name.html file within that same folder and then redirect to the first_name-last_name.html file
jQuery / HTML form:
<html>
<head>
<title>Ambient Lounge - Create eSig</title>
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'>
<!-- Include JS File Here -->
<link href="http://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet" type="text/css">
<style type="text/css">
#import url('http://fonts.googleapis.com/css?family=Open+Sans');
body {
font-family: 'Open Sans', 'Helvetica Neue', Helvetica, sans-serif;
}
hr {
margin-bottom: 1.5em;
}
.error_wrapper {
color: #D8000C;
background-color: #FFBABA;
padding: 10px;
margin-bottom: 1em;
}
.success_wrapper {
color: #4F8A10;
background-color: #DFF2BF;
padding: 10px;
margin-bottom: 1em;
}
#main {
float: left;
width: 20%;
}
#preview {
float: left;
width: 80%;
}
form label {
display: none;
}
form input {
margin-bottom: 0.5em;
padding: 5px;
width: 80%;
}
</style>
<!-- Include JS File Here -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$(".error_wrapper, .success_wrapper").hide();
var v_first_name = $("#first_name").val();
var v_last_name = $("#last_name").val();
var v_title = $("#title").val();
var v_address = $("#address").val();
var v_phone = $("#phone").val();
var v_mobile = $("#mobile").val();
var v_email = $("#email").val();
var v_web = $("#web").val();
$(".input_change").keyup(function(){
$("#btn").attr("disabled", "disabled");
var current_input = $(this).attr("id");
console.log(current_input);
$("#p_" + current_input).html($("#" + current_input).val());
});
$("#verify").click(function() {
var has_error = false;
$('#first_name, #last_name, #title, #address, #email, #web').each(function() {
$(this).attr('style', 'border: 0;');
if ($(this).val() == '') {
$(".error_msg").html("<strong>Error(s):</strong> You are missing some enteries, please check and try again.");
$(".error_wrapper").show();
$(this).attr('style', 'border: 1px solid red;');
has_error = true;
}
});
if (has_error != true) {
$(".error_wrapper").hide();
alert("You have verified changes, please double check and if happy click create otherwise change values and verify again.");
$("#btn").removeAttr('disabled');
}
});
$("#btn").click(function() {
$.post("create_post.php", { // Data Sending With Request To Server
first_name:v_first_name,
last_name:v_last_name,
title:v_title,
address:v_address,
phone:v_phone,
mobile:v_mobile,
email:v_email,
web:v_web
}, function(response,status) { // Required Callback Function
alert("*----Received Data----*\n\nStatus : " + status);//"response" receives - whatever written in echo of above PHP script.
alert(response);
if(status == "success") {
$("#form")[0].reset();
} else {
}
});
});
});
</script>
</head>
<body>
<h2>Create e-mail signature</h2>
<hr>
<div class="error_wrapper">
<div class="error_msg"></div>
<ul></ul>
</div>
<div class="success_wrapper">
<div class="success_msg"><strong>Congraulations!</strong> You have successfully create your e-mail signature. You can view your e-mail signature by clicking here.</div>
</div>
<div id="main">
<form id="form" method="post">
<label>First Name</label>
<input type="text" name="first_name" id="first_name" class="input_change" placeholder="First name"/><br>
<label>Last Name</label>
<input type="text" name="last_name" id="last_name" class="input_change" placeholder="Last name"/><br>
<label>Title</label>
<input type="text" name="title" id="title" class="input_change" placeholder="Job title"/><br>
<label>Address</label>
<input type="text" name="address" id="address" class="input_change" placeholder="Business Address"/><br>
<label>Phone</label>
<input type="text" name="phone" id="phone" class="input_change" placeholder="Phone number"/><br>
<label>Mobile</label>
<input type="text" name="mobile" id="mobile" class="input_change" placeholder="Mobile number"/><br>
<label>Email</label>
<input type="text" name="email" id="email" class="input_change" placeholder="Email address"/><br>
<label>Web</label>
<input type="text" name="web" id="web" class="input_change" placeholder="Web address"/>
</form>
<button id="verify">Verify</button> <button id="btn" disabled>Create</button>
</div>
<div id="preview">
<!-- PREVIEW OF HTML EMAIL -->
<link href="http://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet" type="text/css">
<style type="text/css">
#import url('http://fonts.googleapis.com/css?family=Open+Sans');
.clear {
clear: both;
}
b {
font-weight: normal;
}
b.bold {
font-weight: bold;
}
.emailContent {
font-family:'Open Sans', 'Helvetica Neue', Helvetica, sans-serif;
width: 480px;
color: #767676;
}
.emailContent a {
color: #2A96B4;
text-decoration: none;
}
.emailName {
height: 62px;
}
.emailName img {
float: right;
margin-top: 1.2em;
margin-right: 0.8em;
}
.emailName p {
color: #767676;
font-size: 0.8em;
float: left;
}
.emailName p span {
color: #2A96B4;
font-weight: bold;
font-size: 1.2em;
}
.emailLogo {
height: 46px;
clear: both;
}
.emailLogo img {
float: left;
margin-top: 0.3em;
}
.emailLogo ul.socialList {
list-style: none;
border-left: 1px solid #aaaaaa;
padding-left: 1.5em;
margin: 0 0 0 1.5em;
float: left;
}
.emailLogo ul.socialList li {
display: inline-block;
}
.emailLogo ul.socialList li img {
margin: 0;
}
.emailDetails {
clear: both;
border-top: 5px solid #2A96B4;
margin-top: 1em;
}
.emailDetails p {
font-size: 12px;
margin: 0.3em 0;
}
.emailDetails p.larger {
font-size: 14px;
}
.emailDetails p span {
color: #2A96B4;
}
.emailNotice {
border-top: 1px solid #aaaaaa;
font-size: 0.6em;
padding-top: 0.8em;
margin-top: 2.5em;
}
</style>
<div class="emailContent">
<div class="emailName">
<p><span><b id="p_first_name" class="bold">James</b> <b id="p_last_name" class="bold">Brandon</b></span><br><b id="p_title">Global Technical Lead</b></p>
<img src="http://www.ambientlounge.com/emails/like-us-on-facebook.png" alt="Like us on Facebook" />
</div>
<div class="clear"></div>
<div class="emailLogo">
<img src="http://www.ambientlounge.com/emails/ambient-logo-email.png" alt="Ambient Lounge" />
<ul class="socialList">
<li><img src="http://www.ambientlounge.com/emails/icon-facebook.png" alt="Facebook" /></li>
<li><img src="http://www.ambientlounge.com/emails/icon-twitter.png" alt="Twitter" /></li>
<li><img src="http://www.ambientlounge.com/emails/icon-instagram.png" alt="Instagram" /></li>
</ul>
</div>
<div class="clear"></div>
<div class="emailDetails">
<p><span>a:</span> <b id="p_address">Old knows Factory, Unit 5C, Office 14, St Anns Hill Road, Nottingham, NG3 4GN</b></p>
<p><span>p:</span> <b id="p_phone">+44(0) 844 579 1112</b> | <span>m:</span> <b id="p_mobile">+44(0) 771 809 0 809</b></p>
<p class="larger"><span id="p_email">james#ambientlounge.com</b> | <b id="p_web">www.ambientlounge.co.uk</b></p>
</div>
<p class="emailNotice">This email and any files transmitted with it are confidential and intended solely for the use of the individual or entity to whom they are addressed. If you have received this email in error please notify the system manager. This message contains confidential information and is intended only for the individual named. If you are not the named addressee you should not disseminate, distribute or copy this e-mail. Please notify the sender immediately by e-mail if you have received this e-mail by mistake and delete this e-mail from your system. If you are not the intended recipient you are notified that disclosing, copying, distributing or taking any action in reliance on the contents of this information is strictly prohibited.</p>
</div>
</div>
</body>
</html>
Current PHP Post file:
<?php
if($_POST["first_name"]) {
$first_name = $_POST["first_name"];
$last_name = $_POST["last_name"];
$title = $_POST["title"];
$address = $_POST["address"];
$phone = $_POST["phone"];
$mobile = $_POST["mobile"];
$email = $_POST["email"];
$web = $_POST["web"];
$filePath == $first_name + "-" + $last_name + ".html";
if(file_exists($filePath)){
echo "Already exisits";
} else {
touch( $filePath ); //create file if it does not exist
fwrite( $file, '
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Ambient Lounge - e-Mail Signature (James Brandon)</title>
<link href="http://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet" type="text/css">
<style type="text/css">
#import url("http://fonts.googleapis.com/css?family=Open+Sans");
.clear {
clear: both;
}
.emailContent {
font-family:"Open Sans", "Helvetica Neue", Helvetica, sans-serif;
width: 480px;
color: #767676;
}
.emailContent a {
color: #2A96B4;
text-decoration: none;
}
.emailName {
height: 62px;
}
.emailName img {
float: right;
margin-top: 1.2em;
margin-right: 0.8em;
}
.emailName p {
color: #767676;
font-size: 0.8em;
float: left;
}
.emailName p span {
color: #2A96B4;
font-weight: bold;
font-size: 1.2em;
}
.emailLogo {
height: 46px;
clear: both;
}
.emailLogo img {
float: left;
margin-top: 0.3em;
}
.emailLogo ul.socialList {
list-style: none;
border-left: 1px solid #aaaaaa;
padding-left: 1.5em;
margin: 0 0 0 1.5em;
float: left;
}
.emailLogo ul.socialList li {
display: inline-block;
}
.emailLogo ul.socialList li img {
margin: 0;
}
.emailDetails {
clear: both;
border-top: 5px solid #2A96B4;
margin-top: 1em;
}
.emailDetails p {
font-size: 12px;
margin: 0.3em 0;
}
.emailDetails p.larger {
font-size: 14px;
}
.emailDetails p span {
color: #2A96B4;
}
.emailNotice {
border-top: 1px solid #aaaaaa;
font-size: 0.6em;
padding-top: 0.8em;
margin-top: 2.5em;
}
</style>
<div class="emailContent">
');
fwrite( $file, '
<div class="emailName">
<p><span>'.$first_name.' '.$last_name.'</span><br>'.$title.'</p>
<img src="http://www.ambientlounge.com/emails/like-us-on-facebook.png" alt="Like us on Facebook" />
</div>
<div class="clear"></div>
<div class="emailLogo">
<img src="http://www.ambientlounge.com/emails/ambient-logo-email.png" alt="Ambient Lounge" />
<ul class="socialList">
<li><img src="http://www.ambientlounge.com/emails/icon-facebook.png" alt="Facebook" /></li>
<li><img src="http://www.ambientlounge.com/emails/icon-twitter.png" alt="Twitter" /></li>
<li><img src="http://www.ambientlounge.com/emails/icon-instagram.png" alt="Instagram" /></li>
</ul>
</div>
<div class="clear"></div>
<div class="emailDetails">
<p><span>a:</span> '.$address.'</p>
<p><span>p:</span> '.$phone.' | <span>m:</span> '.$mobile.'</p>
<p class="larger">'.$email.' | '.$web.'</p>
</div>
');
fwrite( $file, '
<p class="emailNotice">This email and any files transmitted with it are confidential and intended solely for the use of the individual or entity to whom they are addressed. If you have received this email in error please notify the system manager. This message contains confidential information and is intended only for the individual named. If you are not the named addressee you should not disseminate, distribute or copy this e-mail. Please notify the sender immediately by e-mail if you have received this e-mail by mistake and delete this e-mail from your system. If you are not the intended recipient you are notified that disclosing, copying, distributing or taking any action in reliance on the contents of this information is strictly prohibited.</p>
</div>
</body>
</html>
');
$file = fopen( $filePath, "w" );
fwrite( $file, $data );
fclose( $file );
$data = file_get_contents( $filePath ); //do this after closing your writing
}
}
?>
You can write to a file with:
touch( $filePath ); //create file if it does not exist
$file = fopen( $filePath, "w" );
fwrite( $file, $data );
fclose( $file );
This will replace the entire file contents with what you fwrite().
You can check if a file already exists with
file_exists( $filePath );
You can define your custom file path in a manner like
$filePath = "whatever directory you want it to go to/". $firstnamevariable ."-". $lastnamevariable .".html";
You can keep a running $data variable that you write to the file at the end by appending to, like how $filePath above is appending. Or you can simply write to the file multiple time.
fwrite( $file, "<html><head></head><body>" );
fwrite( $file, "<div>First Name: ". $firstnamevaraible ."</div>" );
fwrite( $file, "<div>Last Name: ". $lastnamevariable ."</div>" );
fwrite( $file, "</body></html>" );
Once you've created your file, if you want to return the entire contents to the user you can do
$data = file_get_contents( $filePath ); //do this after closing your writing
Then you can echo $data to the user or if you want, just echo that function without the need for a variable.

Send values from one PHP file to another with JavaScript/AJAX

I have this form in a PHP file:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
function sendPushNotification(id){
var data = $('form#'+id).serialize();
// $('form#'+id).unbind('submit');
$.ajax({
url: "table_ready.php",
type: 'GET',
data: data,
beforeSend: function() {
},
success: function(data, textStatus, xhr) {
//$('.txt_message').val("");
},
error: function(xhr, textStatus, errorThrown) {
}
});
return false;
}
</script>
<style type="text/css">
.bigcontainer{
width: auto;
margin: 0 auto;
padding: 0;
}
h1{
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-size: 24px;
color: #777;
}
div.clear{
clear: both;
}
ul.devices{
margin: 0;
padding: 0;
list-style: none;
}
.smallcontainer {
border: 2px solid #ccc;
width: 300px;
height: 100px;
overflow-y: scroll;
}
ul.devices li{
float: left;
display: inline;
padding: 10px;
margin: 0 15px 25px 0;
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
color: #555;
}
ul.devices li label, ul.devices li span{
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-size: 12px;
font-style: normal;
font-variant: normal;
font-weight: bold;
color: #393939;
display: block;
float: left;
}
ul.devices li label{
height: 25px;
width: 150px;
}
ul.devices li .send_btn{
background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#0096FF), to(#005DFF));
background: -webkit-linear-gradient(0% 0%, 0% 100%, from(#0096FF), to(#005DFF));
background: -moz-linear-gradient(center top, #0096FF, #005DFF);
background: linear-gradient(#0096FF, #005DFF);
text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3);
border-radius: 3px;
color: #fff;
}
</style>
</head>
<body>
<div class="bigcontainer">
<?php
include_once 'include/DB_Functions.php';
$db = new DB_Functions();
$state = $db->checkTableState();
if ($state != false)
$no_of_state = mysql_num_rows($state);
else
$no_of_state = 0;
if ($no_of_state > 0) {
?>
<ul class="devices">
<?php
while ($staterow = mysql_fetch_array($state)) {
$items = $db -> displayTable($staterow["state"]);
?>
<li>
<form id="<?php echo $staterow["state"] ?>" name="" method="post" onsubmit="return sendPushNotification('<?php echo $staterow["state"] ?>')">
<h1>Τραπέζι: <?php echo $staterow["state"]; ?></h1>
<div class="smallcontainer">
<ul>
<?php
// $num_of_items = mysql_fetch_array($items);
while($row = mysql_fetch_array($items)){
$food = Array();
$quan = Array();
$food[] = $row['food'];
$quan[] = $row['uquantity'];
foreach( $food as $index => $f){
?>
<li>
<label>
<?php echo $f; ?> <?php echo $quan[$index]; }?>
</label>
</li>
<div class="clear"></div>
</form>
</li>
<?php
}
?>
</ul>
</div>
<div class="send_container">
<input type="hidden" name="table" value="<?php echo $staterow["state"] ?>"/>
<input type="submit" class="send_btn" value="Send" onclick=""/>
</div>
<?php
}
} else {
?>
<li>No Users Registered Yet!</li>
<?php
}
?>
</ul>
</div>
</body>
</html>
I am using this function to send the value with name table, to my table_ready.php file:
<script type="text/javascript">
function sendPushNotification(id){
var data = $('form#'+id).serialize();
// $('form#'+id).unbind('submit');
$.ajax({
url: "table_ready.php",
type: 'GET',
data: data,
beforeSend: function() {
},
success: function(data, textStatus, xhr) {
//$('.txt_message').val("");
},
error: function(xhr, textStatus, errorThrown) {
}
});
return false;
}
</script>
For some reason it doesn't work. My knowledge of JavaScript is very bad, and I can not figure out what I am doing wrong. The table_ready.php works fine but it doesn't accept the value and so it doesn't work. Any hint on what I am doing wrong?
I'm supposing you omitted part of the script (connection and query itself) and that is working correctly.
The second thing is the usage of jQuery serialize() (http://api.jquery.com/serialize/) it will convert form elements (input, textarea, select) to be sent, and your data is just inside <label>, try using some hidden fields so serialize will find and encode it to be sent to the other script.

Creating a Auto Updating <div></div> When Information Was Pasted on Mysql

It's my first day here, I thought you guys could help me. So, I'm working on this kind of chatting service for a friend. I want it to auto update anything inside the div tags that has an id of messages. I tried adding some javascript and stuff from other posts, but they just made it worse. So, if anyone could fix it and comment, or give me suggestions. I want it as soon as someone posted something, it updates the posts in the div tags with the id of messages.
<?php
session_start();
if(!isset($_SESSION['username']))
{
header("Location: /index.php");
}
?>
<html>
<head>
<title>
House Email System
</title>
<style>
body
{
background: #383838;
font-family: Arial;
color: #444444;
position: absolute;
top: 50%;
left: 50%;
margin-top: -75px;
margin-left: -150px;
}
form
{
background: #ffffff;
width: 270px;
border-radius: 15px;
box-shadow: 3px 3px 6px 1px #303030;
}
input
{
margin-left: 15px;
}
p
{
margin-left: 15px;
}
error
{
padding:2px 4px;
margin:0px;
border:solid 1px #FBD3C6;
background:#FDE4E1;
color:#CB4721;
font-size:14px;
font-weight:bold;
}
div
{
background: #f0f0f0;
}
hr
{
color: #d0d0d0;
background-color: #d0d0d0;
height: 3px;
border: 0px;
}
username
{
margin-left: 5px;
}
message
{
margin-left: 10px;
}
</style>
</head>
<body>
<?php
$connect = mysql_connect("localhost", "root", "*******");
mysql_select_db("*******");
$username = $_SESSION['username'];
$message = $_POST['message'];
$submit = $_POST['submit'];
if($submit)
{
if($message)
{
mysql_query("INSERT INTO messages VALUES('', '$username', '$message')");
}
else
{
?>
<center>
<error>Please enter a message to send.</error> <br />
</center>
<br />
<?php
}
}
?>
<form action="active.php" method="POST">
<br />
<p>Message</p>
<input type="text" name="message" /> <br />
<br />
<input type="submit" name="submit" value="Submit" /> <br />
<br />
<?php
$query = mysql_query("SELECT * FROM messages ORDER BY id DESC");
$num_rows = mysql_num_rows($query);
if($num_rows > 0)
{
while($row = mysql_fetch_assoc($query))
{
$username = $row['username'];
$message = $row['message'];
?>
<div id="messages">
<br /> <username><b><?php echo $username; ?></b></username>
<hr />
<message><?php echo $message; ?></message> <br />
<br /> </div> <br />
<?php
}
}
else
{
?>
<center>
<error>There are no messages to display.</error> <br />
</center>
<br />
<?php
}
?>
</form>
</body>
</html>
I hope you guys can help me, thank you.
First create a page message.php as:
<?php
session_start();
?>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#submit').click(function()
{
//alert("hello");
// ss=document.getElementById("message").value;
$.ajax({
type : 'POST',
url : 'active.php',
data: {
messages :$('#message').val()
},
success : function(data){
$('#messages').html(data);
}
});
});
});
</script>
<title>
House Email System
</title>
<style>
body
{
background: #383838;
font-family: Arial;
color: #444444;
position: absolute;
top: 50%;
left: 50%;
margin-top: -75px;
margin-left: -150px;
}
form
{
background: #ffffff;
width: 270px;
border-radius: 15px;
box-shadow: 3px 3px 6px 1px #303030;
}
input
{
margin-left: 15px;
}
p
{
margin-left: 15px;
}
error
{
padding:2px 4px;
margin:0px;
border:solid 1px #FBD3C6;
background:#FDE4E1;
color:#CB4721;
font-size:14px;
font-weight:bold;
}
div
{
background: #f0f0f0;
}
hr
{
color: #d0d0d0;
background-color: #d0d0d0;
height: 3px;
border: 0px;
}
username
{
margin-left: 5px;
}
message
{
margin-left: 10px;
}
</style>
</head>
<body>
<center>
<error>Please enter a message to send.</error> <br />
</center>
<br />
<form action="active.php" method="POST">
<br />
<p>Message</p>
<input type="text" name="message" id="message" /> <br />
<br />
<input type="button" id="submit" name="submit" value="Submit" /> <br />
</form>
<br />
<div id="messages">
</div>
</body>
</html>
<script language="JavaScript"><!--
// v3 compatible:
function doSomething() {
// do something here...
$.ajax({
type : 'POST',
url : 'active.php',
data: {
messages :$('#message').val()
},
success : function(data){
$('#messages').html(data);
}
});
setTimeout('doSomething()',3000);
}
setInterval('doSomething()',3000);
//--></script>
Then Create a page active.php as
<?php
session_start();
$connect = mysql_connect("localhost", "root", "");
mysql_select_db("test");
$username=$_SESSION['username'];
$message=$_POST['messages'];
if($message!="")
{
mysql_query("INSERT INTO messages VALUES('', '$username', '$message')");
}
$query = mysql_query("SELECT * FROM messages ORDER BY id DESC limit 1,0");
$num_rows = mysql_num_rows($query);
if($num_rows > 0)
{
while($row = mysql_fetch_assoc($query))
{
$username = $row['username'];
$message = $row['message'];
?>
<div>
<br /> <username><b><?php echo $username; ?></b></username>
<hr />
<message><?php echo $message; ?></message> <br />
<br /> </div>
<br />
<?php
}
}
else
{
echo"No message to show";
}
?>
This is very general chat.Now you need to change it according to your requirements.
I want it as soon as someone posted something, it updates the posts in the div tags with the id of messages.
You will have to use javacript for that part. Everything else can be done with PHP and MySQL.
I watched great youtube tutorial the other day on how to do this. Its is a "quick and dirty" solution but should give you something to build on. http://www.youtube.com/watch?v=FyXeOX-uYMc

Categories