jQuery $.post() and MySQL problem - php

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();
}

Related

Alert always says "Please Fill up All Fields" in my login form regardless if the input is wrong or right in Php

A newbie IT student here trying to code my subject requirement which is a ecommerce web app. The problem that im having rn is with the login form that is written in Php. Regardless if the input that I type is right or wrong, the alert still displays "Please fill up all fields".
This is my Php Login Form
<?php
$conn = mysql_connect("localhost","root","1234");
if(!$conn)
{
die('Could not connect: ' . mysql_error());
}mysql_select_db("registration", $conn);
$email=$_POST["email"];
$pwd=md5($_POST["password"]);
$query = mysql_query("SELECT * FROM tbl_reg where password='$pwd' AND email='$email'",$conn);
$rows = mysql_num_rows($query);
if(!$email|| !$pwd)
{
echo"<script>alert(\"please fill up fields\");window.location='sign-in.html'</script>";
}
if ($rows == 1)
{
echo"<script>alert(\"login Succes\");window.location='index2.html'</script>";
}
else
{
$error = "Username or Password is invalid";
}
if ($rows == 0)
{
echo"<script>alert(\"Username or Password is Incorrect\");window.location='login.php'</script>";}
mysql_close($conn);
?>
Here is basically my HTML Login Form
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
<meta name="generator" content="Hugo 0.104.2">
<title>Log in Form</title>
<link rel="canonical" href="https://getbootstrap.com/docs/5.2/examples/sign-in/">
<link href="assets/css/bootstrap.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
<style>
.bd-placeholder-img {
font-size: 1.125rem;
text-anchor: middle;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
}
#media (min-width: 768px) {
.bd-placeholder-img-lg {
font-size: 3.5rem;
}
}
.b-example-divider {
height: 3rem;
background-color: rgba(0, 0, 0, .1);
border: solid rgba(0, 0, 0, .15);
border-width: 1px 0;
box-shadow: inset 0 .5em 1.5em rgba(0, 0, 0, .1), inset 0 .125em .5em rgba(0, 0, 0, .15);
}
.b-example-vr {
flex-shrink: 0;
width: 1.5rem;
height: 100vh;
}
.bi {
vertical-align: -.125em;
fill: currentColor;
}
.nav-scroller {
position: relative;
z-index: 2;
height: 2.75rem;
overflow-y: hidden;
}
.nav-scroller .nav {
display: flex;
flex-wrap: nowrap;
padding-bottom: 1rem;
margin-top: -1px;
overflow-x: auto;
text-align: center;
white-space: nowrap;
-webkit-overflow-scrolling: touch;
}
</style>
<!-- Custom styles for this template -->
<link href="assets/css/signin.css" rel="stylesheet">
</head>
<body class="text-center">
<main class="form-signin w-100 m-auto">
<form method="post" action="login.php">
<img class="mb-4" src="../assets/brand/bootstrap-logo.svg" alt="" width="72" height="57">
<h1 class="h3 mb-3 fw-normal">Please sign in</h1>
<div class="form-floating">
<input type="email" class="form-control" id="floatingInput" placeholder="name#example.com" name="email">
<label for="floatingInput">Email address</label>
</div>
<div class="form-floating">
<input type="password" class="form-control" id="floatingPassword" placeholder="Password" name="password">
<label for="floatingPassword">Password</label>
</div>
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me" > Remember me
</label>
</div>
<button class="w-100 btn btn-lg btn-primary" type="submit">Sign in</button>
<p class="mt-5 mb-3 text-muted">© 2017–2022</p>
</form>
<center>
<p class="mt-5 mb-3 text-muted" id="q">©</p>
</center>
</main>
<script>
var category = 'happiness'
$.ajax({
method: 'GET',
url: 'https://api.api-ninjas.com/v1/quotes?category=' + category,
headers: { 'X-Api-Key': 'ToCfG0A/2Y9rS7AiwSj0BA==5YvMUReDisFAtJ0P'},
contentType: 'application/json',
success: function(result) {
console.log(result);
var q=result;
var quote=result[0].quote;
console.log(quote);
let q1 = document.getElementById("q")
q1.textContent =quote
},
error: function ajaxError(jqXHR) {
console.error('Error: ', jqXHR.responseText);
}
});
</script>
</body>
</html>
I have a pretty shitty Prof. who just posted the syntax in a Ppt. file without any kind of information. Just pure hard code. Nothing more. nothing less. without even a sliver of teaching. I tried everything from rewriting my code to dropping my database or deleting my Table but to no avail. I even tried to rewrite everything even the HTML form one. Please i need help because our midterms are just at the end of the month and i really need help.
In support of the comments made above, perhaps the following will be of help.
<?php
# start & maintain session variables for all pages
session_start();
# enable error reporting
error_reporting( E_ALL );
mysqli_report( MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT );
# create the mysql connection - the OO format is much less verbose!
$conn = new mysqli('localhost','root','1234','registration)';
# test that the request is a POST request and you have important variables set ( using `isset` )
if( $_SERVER['REQUEST_METHOD']=='POST' && isset(
$_POST['email'],
$_POST['password']
)){
# create the basic sql and construct the `prepared statement`
$sql='select `password` from `tbl_reg` where `email`=?';
$stmt=$conn->prepare( $sql );
# bind the placeholder(s) to variables
$stmt->bind_param('s', $_POST['email'] );
$stmt->bind_result( $hash );
$stmt->execute();
# if the stored hash matches the value generated by `password_verify` that is a success
if( password_verify( $_POST['password'], $hash ) ){
# OK - set a session variable to be propagated throughout entire session.
$_SESSION['username']=$_POST['email'];
# redirect to a PHP page that maintains the session
exit( header( 'Location: index.php' ) );
}else{
# FAIL
exit( header( 'Location: login.php' ) );
}
}
?>
And an example of using password_hash when adding your users.
/* to add the user and password - probably will have more columns/values in actual sql */
$sql='insert into `tbl_reg` ( `email`, `password` ) values ( ?, ? )';
$stmt=$conn->prepare( $sql );
$hash=password_hash( $_POST['password'], PASSWORD_DEFAULT );
$stmt->bind_param('ss', $_POST['email'], $hash );
$stmt->execute();
Make Some Few Changes in Your Code and Check if your code works.
Update Code In Html File
Delete Below Line :
<button class="w-100 btn btn-lg btn-primary" type="submit">Sign in</button>
And Add here below line
<input type="submit" name="submit" value="Submit">
Update Code in Login.php File
if (isset($_POST['submit'])) {
$email=$_POST["email"];
$pwd=md5($_POST["password"]);
$query = mysql_query("SELECT * FROM tbl_reg where password='$pwd' AND email='$email'",$conn);
$rows = mysql_num_rows($query);
if(!$email|| !$pwd)
{
echo"<script>alert(\"please fill up fields\");window.location='sign-in.html'</script>";
}
elseif ($rows == 1)
{
echo"<script>alert(\"login Succes\");window.location='index2.html'</script>";
}
elseif ($rows == 0)
{
echo"<script>alert(\"Username or Password is Incorrect\");window.location='login.php'</script>";
}
else
{
echo $error = "Username or Password is invalid";
}
}
mysql_close($conn);
Note : If it still showing alert box with message "please fill up fields". Then, somehow login.php not getting input value of email & password from html file when you were submitting your form from html file.
Without Checking All this thing, i cant fix that problem by writing here..
if is there any way to continiously chat with your, then i can help your you to solve your problem.

javascript effect only works on the first element but not on others?

I am echoing records from the database which are wrapped with html tags and was trying to put some effect on the echoed data. When I click the edit link, the textfield should shake. It works on the first element but when I click the edit link of the next element, the first textfield still shakes and not the other one.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Wallpost</title>
<style>
.wallpost input[type="text"]{
width: 500px;
height: 20px;
}
.wallpost input[type="submit"]{
height: 26px;
}
.user{
font-weight: bold;
font-size: 20px;
}
.post{
font-family: Arial;
}
a{
text-decoration: none;
}
</style>
</head>
<body>
<?php
require_once 'dbconfig.php';
$user = $_SESSION['user'];;
echo '<form action="post.php" method="post" class="wallpost"><input
type="text" name="post" size="50"><input type="submit" name="wallpost"
value="Post"></form>';
$query = $con->query("SELECT * FROM statuspost ORDER BY id DESC");
while($i = $query->fetch_object()){
//echo $i->post.' '.$i->id.' <a href="wallpost.php?type=post&
id='.$i->id.'" >Remove</a>'.'<br/>';
echo '<span class="user">'.$i->user.'</span>'.'<br>'.'<span
class="post">'.$i->post.'</span>'.' <form action="editpost.php?type=post&
id='.$i->id.'" method="post"><span id="edit"><input type="text"
name="edit">
<br/><input type="submit" value="Edit"></span><a href="#"
onclick="showEdit();">Edit </a><a href="remove.php?type=post&
id='.$i->id.'" >Remove</a></form> '.'<br/><br/>';
//echo '<div id="post">'.$i->post.' '.$i->id.'<a href="#"
id="anchor" class="',$i->id,'" onclick="del();">Remove</a></div>
<br/>';
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.2.0
/prototype.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/scriptaculous/1.9.0
/scriptaculous.js"></script>
<script>
function showEdit(){
Effect.Shake('edit');
}
</script>
</body>
</html>
Replace <span id="edit"> by something like <span id="edit'.$i->id.'"> to have different ids on each elements. Then of course, showEdit() must know which id it has to shake, so it has to take a parameter. Or even simpler: replace onclick="showEdit();" by onclick="Effect.Shake(\'edit'.$i->id.'\');"
Scriptaculous effects take either an ID or a JavaScript reference to a DOM element as their first argument, so if you add a classname to your multiple elements, you can shake all of them at once like this:
<span class="shake-me">...</span>
<span class="shake-me">...</span>
<span class="shake-me">...</span>
Inside an enumerator:
$$('.shake-me').each(function(elm){
Effect.Shake(elm);
});

Want two dynamically created input values to be saved in one mysql row using php

what i want is when a user clicks a link it should automatically create two text box's at a time and from which we can click and create unlimited numbers of textboxs which when submitted it should save all the dynamically created textbox two text box's in a row.
meaning textboxA textboxB
in this manner......
I found a code on net which works very similar to that how i wanted...but instead of two textboxs it creates only one textbox at a time when clicked the link First i'll give u the full original code...
1) index.php
<?php
//Include the database class
require("classes/db.class.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>jQuery</title>
<script type="text/javascript" src="js/jquery.js"></script>
<link rel="stylesheet" type="text/css" href="css/css.css" />
<script type="text/javascript">
var count = 0;
$(function(){
$('p#add_field').click(function(){
count += 1;
$('#container').append(
'<strong>Link #' + count + '</strong><br />'
+ '<input id="field_' + count + '" name="fields[]' + '" type="text" /><br />' );
});
});
</script>
<body>
<?php
//If form was submitted
if (isset($_POST['btnSubmit'])) {
//create instance of database class
$db = new mysqldb();
$db->select_db();
//Insert static values into users table
$sql_user = sprintf("INSERT INTO users (Username, Password) VALUES ('%s','%s')",
mysql_real_escape_string($_POST['name']),
mysql_real_escape_string($_POST['password']) );
$result_user = $db->query($sql_user);
//Check if user has actually added additional fields to prevent a php error
if ($_POST['fields']) {
//get last inserted userid
$inserted_user_id = $db->last_insert_id();
//Loop through added fields
foreach ( $_POST['fields'] as $key=>$value ) {
//Insert into websites table
$sql_website = sprintf("INSERT INTO websites (Website_URL) VALUES ('%s')",
mysql_real_escape_string($value) );
$result_website = $db->query($sql_website);
$inserted_website_id = $db->last_insert_id();
//Insert into users_websites_link table
$sql_users_website = sprintf("INSERT INTO users_websites_link (UserID, WebsiteID) VALUES ('%s','%s')",
mysql_real_escape_string($inserted_user_id),
mysql_real_escape_string($inserted_website_id) );
$result_users_website = $db->query($sql_users_website);
}
} else {
//No additional fields added by user
}
echo "<h1>User Added, <strong>" . count($_POST['fields']) . "</strong> website(s) added for this user!</h1>";
//disconnect mysql connection
$db->kill();
}
?>
<?php if (!isset($_POST['btnSubmit'])) { ?>
<h1>New User Signup</h1>
<form name="test" method="post" action="">
<label for="name">Username:</label>
<input type="text" name="name" id="name" />
<div class="spacer"></div>
<label for="name">Password:</label>
<input type="text" name="password" id="password" />
<div class="spacer"></div>
<div id="container">
<p id="add_field"><span>» Add your favourite links.....</span></p>
</div>
<div class="spacer"></div>
<input id="go" name="btnSubmit" type="submit" value="Signup" class="btn" />
</form>
<?php } ?>
</body>
</html>
2) db.class.php
<?php
class mysqldb {
/*
FILL IN YOUR DATABASE DETAILS BEFORE RUNNING THE EXAMPLE
*/
var $hostname = "localhost";
var $username = "root";
var $password = "mypassword";
var $database = "unlimited";
function db_connect() {
$result = mysql_connect($this->hostname,$this->username,$this->password);
if (!$result) {
echo 'Connection to database server at: '.$this->hostname.' failed.';
return false;
}
return $result;
}
function select_db() {
$this->db_connect();
if (!mysql_select_db($this->database)) {
echo 'Selection of database: '.$this->database.' failed.';
return false;
}
}
function query($query) {
$result = mysql_query($query) or die("Query failed: $query<br><br>" . mysql_error());
return $result;
mysql_free_result($result);
}
function fetch_array($result) {
return mysql_fetch_array($result);
}
function num_rows($result) {
return mysql_num_rows($result);
}
function last_insert_id() {
return mysql_insert_id();
}
function kill() {
mysql_close();
}
}
?>
3) css.css
html, input {font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 0.8em;}
body { width: 500px; margin: 50px auto 0 auto; display: block;}
h1 { font-size: 1.5em; color: #333; }
input { font-size: 0.9em; padding: 5px; border: 1px solid #ccc; margin: 0; display: block;}
a { text-decoration: none; color: #666; font-weight: bold; }
a:hover { color: #ff0000; }
#divTxt { width:400px; padding: 5px; }
p a img { border: none; vertical-align: middle; }
.spacer {clear: both; height: 10px; }
.btn { width: 90px; font-weight: bold; }
#container { border: 1px solid #ccc; padding: 2px; }
.clear {overflow: hidden;width: 100%;
}
4) JQUERY.js
With this code i am only allowed to dynamically create one textbox when clicked the link as i said earlier, so to make it for my use as i wanted to have two textbox's i have edited the jquery part in the index.php page as below...
<script type="text/javascript">
var count = 0;
$(function(){
$('p#add_field').click(function(){
count += 1;
$('#container').append(
'<strong>Link #' + count + '</strong><br />'
+ '<label for="fields[]' + '">Colour</label><input id="field_' + count + '" name="fields[]' + '" type="text" /><label for="fields2[]' + '">Quantity</label><input id="field2_' + count + '" name="fields2[]' + '" type="text" /><br />');
});
});
</script>
Till here i am successfull... but the main problem is I cannot save them both the two textbox's in a row in mysql table..
Please review this code and reply me if u get any answers.....
I'll surely click the green arrow for the working answer as accepted answer..
Please HELP guys......
Try this
jQuery
<script type="text/javascript">
var count = 0;
$(function(){
$('p#add_field').click(function(){
count += 1;
$('#container').append(
'<strong>Link #' + count + '</strong><br />'
+ '<label for="field_'+count+'_1">Name</label><input id="field_'+count+'_1" name="fields[]['name']" type="text" /><label for="field2_'+count+'_2">URL</label><input id="field2_'+count+'_2" name="fields[]['url']" type="text" /><br />');
});
});
</script>
PHP
//Insert into websites table
$sql_website = sprintf("INSERT INTO websites (Website_Name,Website_URL) VALUES ('%s','%s')",
mysql_real_escape_string($value['name']),
mysql_real_escape_string($value['url']) );
$result_website = $db->query($sql_website);
$inserted_website_id = $db->last_insert_id();
I am assuming that the 1st column is Website_Name and the 2nd column is Website_URL
P.S. : You've said it creates two text boxes, which means there should be two table fields where you want to add those two values. But in your MySQL query, there is only one column insert.
"INSERT INTO websites (Website_URL) VALUES ('%s')"
Specify the 2nd column name to answer your question correctly.

PHP AJAX Load More

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 )

New to JavaScript, jQuery and Ajax

I've figured out how to use a jQuery drag-drop sortable ui. I've also figured out how to populate the jQuery list with time data from my table. But... I'm up against another brick wall.
Following is the script for test.php
<?php
session_start();
// include database connection file, if connection doesn't work the include file will throw an error message
include '../schedule/include/db_connect.php';
$date1 = "10/01/2012";
echo $date1;
// strtotime() will convert nearly any date format into a timestamp which can be used to build a date with the date() function.
$timestamp = strtotime($date1);
$start_date = date("Y-m-d", $timestamp);
$result="SELECT DATE_FORMAT(List_Dates.DB_Date, '%m/%d/%Y') as newdate, DATE_FORMAT(List_Time.TFM_Time,'%h:%i %p') as newtime
FROM List_Dates, List_Time
WHERE DATE(DATE_FORMAT(List_Dates.DB_Date,'%Y-%m-%d')) LIKE '" . $start_date . "%'
ORDER BY List_Time.TFM_Time";
$answer = mysql_query($result);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Sortable - Connect lists</title>
<link rel="stylesheet" type="text/css" href="../schedule/include/formats.css"/>
<link rel="stylesheet" href="../jquery/themes/custom-theme/jquery.ui.all.css">
<script src="../jquery/jquery-1.7.1.js"></script>
<script src="../jquery/ui/jquery.ui.core.js"></script>
<script src="../jquery/ui/jquery.ui.widget.js"></script>
<script src="../jquery/ui/jquery.ui.mouse.js"></script>
<script src="../jquery/ui/jquery.ui.sortable.js"></script>
<script src="../jquery/ui/jquery.ui.selectable.js"></script>
<style>
#sortable1, #sortable2 { list-style-type: none; margin: 0; padding: 0 0 2.5em; float: left; margin-right: 10px; }
#sortable1 li, #sortable2 li { margin: 0 5px 5px 5px; padding: 5px; font-size: 1.2em; width: 120px; }
</style>
<script>
$(function() {
$( "#sortable1, #sortable2" ).sortable({
connectWith: ".connectedSortable"
}).disableSelection();
});
</script>
</head>
<body>
<div>
<ul name="timelist" id="sortable1" class="connectedSortable">
<?php
while($row = mysql_fetch_array($answer))
{
echo "<li class='ui-state-default'>". $row['newtime'] ."</li>";
}
?>
</ul>
<ul name="blocklist" id="sortable2" class="connectedSortable">
<li id="blocked" type="date" class="ui-state-highlight"></li>
</ul>
</div>
</body>
</html>
As I mentioned earlier, the script is successfully populating a sortable drag-drop list with times from my database. I can drag and drop one time from the left side timelist to the right side blocklist. Now I need to extract an array from the blocklist. I found the following:
<script>
$('ul#myList li').each(function(){
var number = $(this).find('span:first-child').text();
var fruit = $(this).find('span:first-last').text();
});
</script>
For my application it makes sense to change the syntax as follows:
<script>
$('ul#sortable2 li').each(function(){
var btime = $(this).find('span:first-child').text();
});
</script>
But... I can't figure out how to successfully use it and echo the results. Everything I've tried results in failure. Any advice is welcome.
Check the jQuery UI documentation there is a method called toArray which you can call on your sortable element to get, well, an array.
http://jqueryui.com/demos/sortable/#method-toArray

Categories