PHP AJAX Load More - php

Hi i have a script that when user click load more button, ajax will request new content and
display to users, but i have issue where if all the content has been loaded and if user click load more button it cause bug and repeatedly show multiple load more button.Following is my code, need to know how to resolve this. If there is no content to load the button need to be disabled.Thanks guys !!
ajax_more.php
<?php
include("config.php");
if(isSet($_POST['lastmsg']))
{
$lastmsg=$_POST['lastmsg'];
$result=mysql_query("select * from messages where mes_id<'$lastmsg' limit 3");
$count=mysql_num_rows($result);
while($row=mysql_fetch_array($result))
{
$msg_id=$row['mes_id'];
$message=$row['msg'];
?>
<li>
<?php echo $message; ?>
</li>
<?php
}
?>
<div id="more<?php echo $msg_id; ?>" class="morebox">
more
</div>
<?php
}
?>
loadmore.php
<?php
include('config.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Twitter Style load more results.</title>
<link href="frame.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
//More Button
$('.more').live("click",function()
{
var ID = $(this).attr("id");
if(ID)
{
$("#more"+ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "ajax_more.php",
data: "lastmsg="+ ID,
cache: false,
success: function(html){
$("ol#updates").append(html);
$("#more"+ID).remove();
}
});
}
else
{
$(".morebox").html('The End');
}
return false;
});
});
</script>
<style>
body
{
font-family:Arial, 'Helvetica', sans-serif;
color:#000;
font-size:15px;
}
a { text-decoration:none; color:#0066CC}
a:hover { text-decoration:underline; color:#0066cc }
*
{ margin:0px; padding:0px }
ol.timeline
{ list-style:none}ol.timeline li{ position:relative;border-bottom:1px #dedede dashed; padding:8px; }ol.timeline li:first-child{}
.morebox
{
font-weight:bold;
color:#333333;
text-align:center;
border:solid 1px #333333;
padding:8px;
margin-top:8px;
margin-bottom:8px;
-moz-border-radius: 6px;-webkit-border-radius: 6px;
}
.morebox a{ color:#333333; text-decoration:none}
.morebox a:hover{ color:#333333; text-decoration:none}
#container{margin-left:60px; width:580px }
</style>
</head>
<body>
<div style="padding:4px; margin-bottom:10px; border-bottom:solid 1px #333333; "><h3>Tutorial Link Click Here</h3></div>
<div id='container'>
<ol class="timeline" id="updates">
<?php
$sql=mysql_query("select * from messages LIMIT 3");
while($row=mysql_fetch_array($sql))
{
$msg_id=$row['mes_id'];
$message=$row['msg'];
?>
<li>
<?php echo $message; ?>
</li>
<?php } ?>
</ol>
<div id="more<?php echo $msg_id; ?>" class="morebox">
more
</div>
</div>
</body>
</html>

<?php
include("config.php");
$count=0;
$done=false;
if(isSet($_POST['lastmsg']))
{
$lastmsg=$_POST['lastmsg'];
$result=mysql_query("select * from messages where mes_id<'$lastmsg' limit 3");
$check=mysql_result(mysql_query("select mes_id from messages ORDER BY mes_id ASC limit 1"));
$count=mysql_num_rows($result);
while($row=mysql_fetch_array($result))
{
$msg_id=$row['mes_id'];
$message=$row['msg'];
if($row['mes_id']==$check){$done=true;}
$count++;
?>
<li>
<?php echo $message; ?>
</li>
<?php
}
if($count>0 && !$done){
?>
<div id="more<?php echo $msg_id; ?>" class="morebox">
more
</div>
<?php
}
}
?>
Explanation: You were unconditionally outputting the more link. With the changes made, the script checks if more than 0 messages have been loaded from the table before outputting a more link. I have also updated it to check if the current batch is the last and not output the more div if it is.

try this code;
$.ajax({
**$("#load_buton").attr("disabled","disabled");**
type: "POST",
url: "ajax_more.php",
data: "lastmsg="+ ID,
cache: false,
success: function(html){
$("ol#updates").append(html);
$("#more"+ID).remove();
**$("#load_buton").removeAttr("disabled");**
});

In the php section, only display the More button if your returned row size count is greater than 0
Edge cases:
If your database table size increases by n rows, you will repeat n
records each time you hit More
As above, but if records are removed, you will miss out records
Security issues:
SQL injection by sending "0'; truncate messages;--" in the last message post field
Cross site scripting - if users can submit messages with HTML/JavaScript they will be returned in the content without escaping.
In both cases above, use. MySQL escape string ( http://php.net/manual/en/function.mysql-real-escape-string.php ), or use mysqli, and use htmlentities ( http://php.net/manual/en/function.htmlentities.php )

Related

How to do editing and deleting function in auto generated table in php ,mysql

Actually am new in php, i created one fetching page in php. Where am fetching data from the database and will display on the auto generated table. I added two button also. One for Delete the specific row from database and another one for edit the details from the database. In database email_id column is unique. So both the Delete Edit operation will do by email_id. Can Any one tell me , how i write Ajax function for editing and deleting. Code is given below
<html>
<head>
<meta name="keywords" content="" />
<meta name="description" content="" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title><!--Dquip--></title>
<link href="http://fonts.googleapis.com/css?family=Abel|Arvo" rel="stylesheet" type="text/css" />
<link href="style.css" rel="stylesheet" type="text/css" media="screen" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.dropotron-1.0.js"></script>
<script type="text/javascript" src="jquery.slidertron-1.0.js"></script>
<style>
label
{
display:inline-block;
width:150px;
margin-right:10px;
text-align:;
}
table,tr,th,td
{
border: 2px solid dodgerblue;
border-collapse: separate;
}
table
{
width:75%;
margin-top: 8%;
}
th,td
{
height: 50px;
}
td
{
text-align:center;
vertical-align: middle;
}
.button
{
width:75px;
height: 25px;
background-color:dodgerblue;
color:white;
border:1px solid transparent;
}
</style>
<center>
<script>
function deleteABC()
{
}
function editABC()
{
}
</script>
</head>
<body>
<h4 align="right">Logout</h4>
<body>
<div id="wrapper">
<div id="header-wrapper">
<div id="header">
<div id="logo">
<h1>..</h1>
</div>
</div>
<div id="menu-wrapper">
<ul id="menu">
<li class="current_page_item"><span>Homepage</span></li>
<li><span>Blog</span>
<ul>
<li class="first"> About US </li>
<li> Function Area </li>
<li class="last"> Contact US </li>
</ul>
</li>
<li><span>Photos</span></li>
<li><span>About</span></li>
<li><span>Datas</span>
<ul>
<li class="first"> Add Details </li>
<li> Map view </li>
<li class="last"> view Details </li>
</ul>
</li>
<li><span>Contact</span></li>
</ul>
<script type="text/javascript">
$('#menu').dropotron();
</script>
</div></br>
<h1><font color="white">Enter the dates to retrieve the data</font></h1></br></br>
<form method="POST" action="fetchinghome.php">
<label>Role ID:</label><input type="text" name="role" placeholder="Enter the starting date">
<input type="submit" id="submit" name="submit" value="Go" class="button">
</form>
<?php
//include "loginpage.php";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if(isset($_POST['submit']))
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "calender";
$role=$_REQUEST['role'];
$conn = mysqli_connect($servername, $username, $password, $dbname);
if(! $conn )
{
die('Could not connect: ' . mysqli_error());
}
if ($role == 'admin')
{
$sql="SELECT * FROM registration";
}
elseif($role=="M%")
{
$sql="SELECT * FROM registration where reporting_manager='$role' or role='$role'";
}
else
{
$sql="SELECT * FROM registration WHERE role='$role'";
}
// $sql="SELECT * FROM registration where reporting_manager='$role'";
$retval = mysqli_query( $conn,$sql );
if(! $retval )
{
die('Could not get data: ' . mysqli_error($conn));
}
$arr;
$i=0;
while($row = mysqli_fetch_assoc($retval))
{
$arr[$i]=$row;
$i++;
/*
echo "<tr><td>";
echo $row[0]."</td><td>";
echo $row[1]."</td><td>";
echo $row[2]."</td><td>";
echo $row[3]."</td><td>";
echo $row[4]."</td>";
echo "</tr>";
*/
}
$str='';
for($i=0;$i<count($arr);$i++)
{
$brn='<input type="button" value="Delete" onClick="deleteABC('.$arr[$i]['email_id'].')">';
$brn1='<input type="button" value="Edit" onClick="editABC('.$arr[$i]['email_id'].')">';
$str=$str . '<tr><td>'. $arr[$i]['name'].'</td><td>'.$arr[$i]['email_id'].'</td><td>'.$arr[$i]['mobile_no'].'</td><td>'.$arr[$i]['address'].'</td><td>'.$arr[$i]['role'].'</td><td>'.$brn.'</td><td>'.$brn1.'</td></tr>';
}
echo "<table id='example' class='display' cellspacing='0' width='100%'>
<tr>
<th>Name</th>
<th>Email</th>
<th>Mobile Number</th>
<th>Address</th>
<th>Role</th>
<th>Delete</th>
<th>Edit</th>
</tr>".$str."</table>";
}
echo "Fetched data successfully\n";
mysqli_close($conn);
}
?>
</body>
</html>
Please help me to write the Ajax function for those.
Thanks in advance
function deleteABC(email_id)
{
if(confirm("Are you sure you want to delete..!"))
{
$.ajax
({
url: "your url here",
type: 'POST',
data: {email_id: email_id},
success: function (data)
{
//your success code if deleted..
}
});
}
}
function editABC(email_id)
{
$.ajax
({
url: "your url here",
type: 'POST',
data: {email_id: email_id},
success: function (data)
{
//your success code if edited
}
});
}

How to load values to page while scrolling the page

I have a table named "User" with more than 3k rows in MySql database.I want to fetch the database while scrolling the page(As like Facebook news feeds). I surfed for a long time but I can't get it. hoping positive response as soon as possible.
thank you!
If I understood what did you mean:
Database Table
CREATE TABLE messages(
mes_id INT PRIMARY KEY AUTO_INCREMENT,
msg TEXT);
load_data.php
When we are scrolling down a webpage, the script($(window).scroll) finds that you are at the bottom and calls the last_msg_funtion(). Take a look at $.post("") eg: $.post("load_data.php?action=get&last_msg_id=35")
<?php
include('config.php');
$last_msg_id=$_GET['last_msg_id'];
$action=$_GET['action'];
if($action <> "get")
{
?>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
function last_msg_funtion()
{
var ID=$(".message_box:last").attr("id");
$('div#last_msg_loader').html('<img src="bigLoader.gif">');
$.post("load_data.php?action=get&last_msg_id="+ID,
function(data){
if (data != "") {
$(".message_box:last").after(data);
}
$('div#last_msg_loader').empty();
});
};
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
last_msg_funtion();
}
});
});
</script>
</head>
<body>
<?php
include('load_first.php'); //Include load_first.php
?>
<div id="last_msg_loader"></div>
</body>
</html>
<?php
}
else
{
include('load_second.php'); //include load_second.php
}
?>
load_first.php
Contains PHP code to load 20 rows form the message table.
<?php
$sql=mysql_query("SELECT * FROM messages ORDER BY mes_id DESC LIMIT 20");
while($row=mysql_fetch_array($sql))
{
$msgID= $row['mes_id'];
$msg= $row['msg'];
?>
<div id="<?php echo $msgID; ?>" class="message_box" >
<?php echo $msg; ?>
</div>
<?php
}
?>
load_second.php
Contains PHP code to load 5 rows less than last_msg_id form the message table.
<?php
$last_msg_id=$_GET['last_msg_id'];
$sql=mysql_query("SELECT * FROM messages WHERE mes_id < '$last_msg_id' ORDER BY mes_id DESC LIMIT 5");
$last_msg_id="";
while($row=mysql_fetch_array($sql))
{
$msgID= $row['mes_id'];
$msg= $row['msg'];
?>
<div id="<?php echo $msgID; ?>" class="message_box" >
<?php echo $msg;
?>
</div>
<?php
}
?>
CSS
body
{
font-family:'Georgia',Times New Roman, Times, serif;
font-size:18px;
}
.message_box
{
height:60px;
width:600px;
border:dashed 1px #48B1D9;
padding:5px ;
}
#last_msg_loader
{
text-align: right;
width: 920px;
margin: -125px auto 0 auto;
}
.number
{
float:right;
background-color:#48B1D9;
color:#000;
font-weight:bold;
}
Take a look at live demo and scroll down.
Regards,
Ivan
Check out http://jscroll.com/ or just google for "jQuery load content while scrolling" or "jQuery infinite scroll" for other alternatives.

How to use ajax and update img src and call php function?

There is a list of checkboxes. User clicks on image of a "unchecked checkbox". Ajax sends request to php script which updates database and echo's new image source of a "checked checkbox". This works fine, and is below:
HTML:
<img src="<?php echo ( $box->complete == 1 ) ? "/images/checkbox-filled.png" : "/images/checkbox-empty.png" ?>" id="checkbox-<?php echo $box->id ?>" />
markBox.js:
$.ajax( {
type: "POST",
url: "/scripts/markBox.php",
data: data,
cache: false,
success: function( imageSource ) {
image.attr( 'src', imageSource );
}
} );
markBox.php:
//Return result
if ( $box->complete == 1 )
echo "/images/checkbox-filled.png";
else
echo "/images/checkbox-empty.png";
exit;
The challenge is that I have php function that is called earlier, above the list of checkboxes, to display to user how boxes are checked and how many are not. I want this box to be called and refresh as the image does. How do I rerun the php function to run again once the ajax comes back?
HTML:
<div class="markBox"><?php echo $results->getCountComplete() ?> Complete</div>
<div class="markBox"><?php echo $results->getCountNotComplete() ?> Incomplete</div>
you don't need ajax at all: (unless you don't want to store your data to a database or a file): I hope this helps:
http://jsfiddle.net/teeEx/
HTML:
<span class="checked"> </span>
<span class="unchecked"> </span>
<span class="unchecked"> </span>
<div id="result"></div>
CSS:
a{
text-decoration: none;
}
span{
display: block;
width: 30px;
height: 30px;
margin: 20px;
}
span.checked{
background: green;
}
span.unchecked{
background: black;
}
JS:
$('a').click(function(){
var a_obj = $(this);
var obj = a_obj.children('span');
if( obj.is('.checked')){
obj.removeClass('checked').addClass('unchecked');
} else {
obj.removeClass('unchecked').addClass('checked');
}
var all = a_obj.parent();
var countChecked = all.find('span.checked').length;
var countunChecked = all.find('span.unchecked').length;
$('#result').html('checked '+countChecked+'; unckecked: '+countunChecked);
});

Toggle Panels With PHP

I wonder whether someone may be able to help me please.
From some demos and tutorials I've found, I've put together this page which adds toggle panes to a page using values from a mySQL database to populate the fields.
The problem I'm having is that at each layer only the first out of multiple records is shown.
e.g. The screen currently shows 16/03/2012 as the only record, there should be one other record for the 23/02/2012.
Then within the 16/03/2012, the next level should show two items, whereas it is only showing one.
I've been working on this for a while now but I can't seem to find the solution of how to show the correct number of records.
I just wondered whether someone could perhaps have a look at this please and let me know where I'm going wrong.
I've added the full script below for reference.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Panel Test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery(".content").hide();
//toggle the componenet with class msg_body
jQuery(".heading").click(function()
{
jQuery(this).next(".content").slideToggle(500);
});
});
</script>
<style type="text/css">
body {
margin: 20px auto;
font: 12px Verdana,Arial, Helvetica, sans-serif;
}
.layer1 {
margin: 0;
padding: 0;
width: 500px;
}
.heading {
margin: 1px;
color: #fff;
padding: 3px 10px;
cursor: pointer;
position: relative;
background-color:#c30;
}
.content {
padding: 5px 10px;
background-color:#fafafa;
}
p { padding: 5px 0; }
</style>
</head>
<?php
mysql_connect("hostname", "username", "password")or
die(mysql_error());
mysql_select_db("database");
$result = mysql_query("SELECT userdetails.userid, finds.dateoftrip, detectinglocations.locationname, finds.userid, finds.locationid, detectinglocations.locationid, finds.findname, finds.finddescription FROM userdetails, finds, detectinglocations WHERE finds.userid=userdetails.userid AND finds.locationid=detectinglocations.locationid AND finds.userid = 1 ORDER BY dateoftrip DESC");
if (mysql_num_rows($result) == 0)
// table is empty
echo 'There are currently no finds recorded for this location.';
else
{
while ($row = mysql_fetch_array($result))
{
$dateoftrip = $row['dateoftrip'];
$findname = $row['findname'];
{
}
}
}
?>
<body>
<div class="layer1">
<p class="heading"><input name="dateoftrip" id="dateoftrip" type="text" value="<?php echo $dateoftrip;?>" disabled="disabled"/></p>
<div class="content">
<input name="findname" id="findname" type="text" value="<?php echo $findname;?>" disabled="disabled"/>
</div>
</div>
</body>
</html>
Many thanks and kind regards
You are fetching all the records but using only the last one.
You should put this:
<div class="layer1">
<p class="heading"><input name="dateoftrip" id="dateoftrip" type="text" value="<?php echo $dateoftrip;?>" disabled="disabled"/></p>
<div class="content">
<input name="findname" id="findname" type="text" value="<?php echo $findname;?>" disabled="disabled"/>
</div>
</div>
in the while loop which fetch the data:
while ($row = mysql_fetch_array($result))
{
$dateoftrip = $row['dateoftrip'];
$findname = $row['findname'];
So it will look like this:
while ($row = mysql_fetch_array($result))
{
$dateoftrip = $row['dateoftrip'];
$findname = $row['findname'];
echo '<div class="layer1">
<p class="heading"><input name="dateoftrip" id="dateoftrip" type="text" value="'.$dateoftrip.'" disabled="disabled"/></p>
<div class="content">
<input name="findname" id="findname" type="text" value="'.$findname.'" disabled="disabled"/>
</div>
</div>';
}
You need to put your output inside your loop. Also you may have to modify your javascript to account for the multiple content ids.
You should also make the form controls into arrays so you'll be able to parse them if needed (see below).
For example, this is how to modify the form.
?>
<body>
<div class="layer1">
<?php
while ($row = mysql_fetch_array($result))
{
$dateoftrip = $row['dateoftrip'];
$findname = $row['findname'];
$i++;
?>
<p class="heading"><input name="dateoftrip[]" id="dateoftrip" type="text" value="<?php echo $dateoftrip;?>" disabled="disabled"/></p>
<div class="content">
<input name="findname[]" id="findname" type="text" value="<?php echo $findname;?>" disabled="disabled"/>
<?php
{
}
}
}
?>
</div>
</div>

jQuery $.post() and MySQL problem

I'm using jQuery and $.post(). My code snippet is as follows for chat .php :
<?php
$msg=$_POST['msg'];
mysql_connect("localhost","root");
mysql_select_db("user");
mysql_query("INSERT INTO space (name,msg,serial) VALUES('Test','$msg','1')");
?>
and here is the code for my HTML file :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Shout!</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
var status=1;
function action() {
if(status==1) {
$("#Layer1").hide("slow");
$("#Layer3").hide("fast");
$("#Layer4").hide("slow");
$("#close").attr("src","open.jpg");
status=0;
}
else if(status==0) {
status=1;
$("#Layer1").show("slow");
$("#Layer3").show("fast");
$("#Layer4").show("slow");
$("#close").attr("src","close.jpg");
}
}
function sendline() {
var msg=$("#msg").val();
$.post("chat.php",{msg:msg});
$("#msg").val(" ");
}
function typeyo() {
var text=$("#msg").val();
$("#Layer6").html(text);
}
</script>
<style type="text/css">
<!--
body {
background-color: #000000;
}
#Layer1 {
position:absolute;
width:200px;
height:115px;
z-index:1;
left: 199px;
top: 3px;
}
#Layer2 {
position:absolute;
width:69px;
height:64px;
z-index:2;
left: 570px;
top: 543px;
}
#Layer3 {
position:absolute;
width:131px;
height:91px;
z-index:3;
left: 487px;
top: 327px;
}
.style1 {
color: #FFFFFF;
font-family: "Segoe UI";
font-weight: bold;
}
#Layer4 {
position:absolute;
width:99px;
height:38px;
z-index:4;
left: 744px;
top: 485px;
}
#Layer5 {
position:absolute;
width:274px;
height:70px;
z-index:5;
left: 422px;
top: 62px;
}
#Layer6 {
width:638px;
height:356px;
z-index:5;
left: 352px;
top: 105px;
}
-->
</style></head>
<body>
<div class="style1" id="Layer3">
<textarea name="textarea" cols="30" rows="5" id="msg" ></textarea>
</div>
<div id="Layer1">Hello World!<img src="body.jpg" width="842" height="559" /></div>
<div id="Layer2"><img src="close.jpg" alt="Go Online/Offline" name="close" width="63" height="64" id="close" OnClick="action()"/></div>
<div id="Layer4">
<input type="button" value="Send Line" onclick="sendline()" /></div>
<div id="Layer6" style="color:white;font-family:Segoe UI;font-size:16px;width:500px; height:400px; overflow:auto;"></div>
</body>
</html>
Now,there seems to be some problem posting the variable msg.Im using chat.php for $.post() on the HTML code that i've provided.
There seems to be a problem with sending the "msg" here . The chat.php file is fine since if we run it directly ,and not thorugh a $.post() call it works perfectly
Kindly Help! thank you!
Your msg variable that you try to send via POST is not initialized,
add the following line at the beginning of your sendline function:
var msg = $("#msg").val();
Note: you have a big/huge security issue inserting variables from POST in MySQL queries without prior treatment.
update: I suggest you use a javascript debugger, set a breakpoint at the beginning of function sendline() and step through the code. Which one to use depends on your browser(s).
Firefox -> e.g. Firebug
IE7 -> e.g. IE Developer Toolbar
IE8+ -> just press F12 to open the developer tools that are shipping with IE.
In addition to darma's answer: Your php script is prone to sql injections (intentional/malicious as well as unintentional ones). Either use prepared, parametrized statements or escape the data properly.
working example:
test.html:
<html>
<head><title>test.html</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function sendline() {
var msg = $('#msg').val();
// --- add some tests on msg here, e.g. msg=="" ---
$.post(
"chat.php",
{'msg':msg},
function(data, textStatus, req) { $('#reply').text('reply: ' + data); }
);
}
</script>
</head>
<body>
<div>
<textarea id="msg" rows="5" cols="30" name="textarea"></textarea>
<button onclick="sendline()">send line</button>
</div>
<div id="reply"> </div>
</body>
</html>
chat.php:
<?php
// --- add some tests on $_POST['msg'] here
// e.g. isset($_POST['msg']) and 0<strlen(trim($_POST['msg'])) ---
// you might want to use a slightly more sophisticated error handling than "or die(mysql_error())" ...but this is only an example.
$mysql = mysql_connect("localhost","localonly", "localonly") or die(mysql_error());
mysql_select_db("test", $mysql) or die(mysql_error());
$msg=mysql_real_escape_string($_POST['msg'], $mysql);
$sql = "INSERT INTO space (name,msg,serial) VALUES('Test','$msg','1')";
// mysql_query($sql, $mysql) or die(mysql_error());
echo htmlspecialchars($sql);
update2: You still don't have any error handling in your php script. Any of the mysql_* function can fail for various reasons; test the results. You need to "see" those errors, e.g. by writing them to a log file or something...
Try
<?php
define('LOGERRORS', 1);
function dbgLog($text) {
if (LOGERRORS) {
error_log(date('Y-m-d H:i:s : ').$text."\n", 3, 'error.log');
}
}
if ( !isset($_POST['msg']) ) {
dbgLog('script called without post parameter "msg"');
die();
}
$mysql = mysql_connect("localhost","root");
if ( !$mysql ) {
dbgLog('database connection failed: '.mysql_error());
die();
}
$result = mysql_select_db("user", $mysql);
if ( !$result ) {
dbgLog('database selection failed: '.mysql_error($mysql));
die();
}
$msg=mysql_real_escape_string($_POST['msg'], $mysql);
$sql = "INSERT INTO space (name,msg,serial) VALUES('Test','$msg','1')";
dbgLog('sending query: '.$sql);
$result = mysql_query($sql, $mysql);
if ( !$result ) {
dbgLog('query failed: '.mysql_error($mysql));
die();
}

Categories