I got the plugin from the net and made some required changes. But I think PHP is not responding.
exp1.html code
<html>
<head>
<meta charset="UTF-8">
<title>AutoSuggestion using Ajax, Jquery and PHP</title>
<link rel="stylesheet" href="exp1.css">
</head>
<body>
<div class="serch-wrap">
<div class="form-wrapper cf">
<input type="text" class="abhijitscript" name="search_word">
<input type="submit" value="Search">
</div>
<div class="autodropdown">
<ul class="suggestresult"></ul>
</div>
</div>
</body>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="exp1.js"></script>
</html>
exp1.php
<?php
$host="localhost";
$user="root";
$password="jatin";
$link=mysqli_connect($host,$user,$password);
if(#mysqli_select_db($link,'books')){
// echo "Database connected..<br>";
}
else
echo mysqli_connect_error();
if(isset($_POST['name']))
{
$name = mysqli_real_escape_string($link,trim($_POST['name']));
$sql = "SELECT `name` FROM `books` WHERE `name` LIKE 'l%'";
$myquery = mysqli_query($link,$sql) or die(mysql_error());
if(mysqli_num_rows($myquery) !=0)
{
while(($row = mysqli_fetch_array($myquery)) !== false)
{
echo '<li>'.$row['name'].'</li>';
}
}
else
{
echo '<li>Not Found</li>';
}
} else{
echo "not set!";
}
?>
exp1.js
$(document).ready(function(){
$('.abhijitscript').keyup(function(){
var query_string = $(this).val();
$.ajax({
type: "POST",
url: "exp1.php",
data: { name:query_string },
success: function(data)
{ console.log(data);
$('.suggestresult').html(data);
$('.suggestresult li').click(function(){
var return_value = $(this).text();
$('.abhijitscript').attr('value', return_value);
$('.abhijitscript').val(return_value);
$('.suggestresult').html('');
});
}
});
});
});
Console also not showing any error, which points to some mistake in php code. I have provided complete code. Thank you!
I edited your code a bit and it is working fine for me now.
<?php
$host="localhost";
$user="root";
$password="jatin";
$link=#mysqli_connect($host,$user,$password);
if( !$link || !#mysqli_select_db($link,'books')){
echo mysqli_connect_error();
exit ;
}
if(isset($_POST['name'])) {
$name = mysqli_real_escape_string($link,trim($_POST['name']));
$sql = "SELECT DISTINCT(`name`) FROM `books` WHERE `name` LIKE '%{$name}%'";
$myquery = mysqli_query($link,$sql) or die(mysql_error());
if(mysqli_num_rows($myquery) !=0) {
while(($row = mysqli_fetch_array($myquery)) !== NULL) {
echo '<li>'.$row['name'].'</li>';
}
} else {
echo '<li>Not Found</li>';
}
} else {
echo "not set!";
}
?>
Related
First of all I must say that I'm very new to website design and coding so please make your answer simple thanks a lot .
So I have my file register.php that contains my form .
I have my action file named register-controller.php that gets the data from user , checks it and inserts it to database .
What I need is that whenever the register is success , my form gets hidden or removed and my new div shows up that contains 'register successful' . ( On the same page "register.php" )
Can I use the variable that I passed to header "register=success" to do this action ? Should I use AJAX ? JSON ? what should I do ? Please give me the simplest answer thank you all .
MY "register.php" file contains these :
<?php
require_once "../DB/users-database.php";
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/Header.CSS">
<link rel="stylesheet" href="/Style.CSS">
<link rel="stylesheet" href="/Footer.CSS">
<script src="https://kit.fontawesome.com/38b3678073.js" crossorigin="anonymous"></script>
<script src="../JS/main.js" async></script>
<title>ثبت نام | PCGA</title>
</head>
<body>
<?php include '../header.php' ?>
<div class="register-container">
<form action="../controllers/register-controller.php" method = "POST">
<label class = "email-label" for="email">ایمیل</label>
<input type="text" id="email" name="email" placeholder="example#example.com" value = '<?php if(isset($_REQUEST['email'])){echo $_REQUEST['email'];}else{echo '';} ?>'>
<?php
if (isset($_REQUEST['error']) && $_REQUEST['error'] == 'emptyEmail'){
echo "<span class = 'empty-email'>فیلد نباید خالی باشد *</span>";
}
else if (isset($_REQUEST['error']) && $_REQUEST['error'] == 'invalidEmailFormat') {
echo "<span class = 'formaterr-email'>فرمت ایمیل نادرست است*</span>";
}
?>
<label class = "phone-label" for="phone">شماره موبایل</label>
<input type="text" id="phone" name="phone" placeholder="09xxxxxxxxx" value = '<?php if(isset($_REQUEST['phone'])){echo $_REQUEST['phone'];}else{echo '';} ?>'>
<?php if (isset($_REQUEST['error']) && $_REQUEST['error'] == 'emptyPhone'){
echo "<span class = 'empty-phone'>فیلد نباید خالی باشد *</span>";
}
else if (isset($_REQUEST['error']) && $_REQUEST['error'] == 'invalidPhoneNumber') {
echo "<span class = 'formaterr-phone'>شماره موبایل حداکثر 11 عدد است و حروف قابل قبول نیست*</span>";
}
?>
<label class = "user-label" for="username">نام کاربری</label>
<input type="text" id="username" name="username" placeholder="Username" value = '<?php if(isset($_REQUEST['username'])){echo $_REQUEST['username'];}else{echo '';} ?>'>
<?php if (isset($_REQUEST['error']) && $_REQUEST['error'] == 'emptyUsername'){
echo "<span class = 'empty-user'>فیلد نباید خالی باشد *</span>";
}
else if (isset($_REQUEST['error']) && $_REQUEST['error'] == 'invalidUserName') {
echo "<span class = 'formaterr-user'>فرمت نام کابری نادرست است*</span>";
}
?>
<label class="pass-label" for="password">رمز عبور</label>
<input type="password" id = "password" name = "password" placeholder = "Password" >
<?php if (isset($_REQUEST['error']) && $_REQUEST['error'] == 'emptyPass'){
echo "<span class = 'empty-pass'>فیلد نباید خالی باشد *</span>";
}
?>
<div class="checkbox-container">
<input type="checkbox" class = 'checkbox-style' name = 'rules-check'>
<label for="checkbox" class="checkbox-label">من قوانین فروشگاه را کامل مطالعه کرده ام و با آن موافق هستم</label>
<?php if (isset($_REQUEST['rules'])){
echo "<span class = 'rules-error'>قبول قوانین اجباری است و آن را حتما مطالعه کنید *</span>";
}
?>
</div>
<button type="submit" name = "submit" id="submit">ثبت نام</button>
</form>
</div>
<?php
if (isset($_REQUEST['register'])){
echo "<div class = 'register-success'>
<span class = 'register-success-span'>ثبت نام با موفقیت انجام شد</span>
</div>" ;
}
?>
<?php include '../footer.php' ?>
</body>
</html>
MY "register-controller.php" file contains these :
<?php
require "../DB/users-database.php";
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (isset($_POST['submit']) && $_POST['rules-check']) {
$email = test_input($_POST["email"]);
$phone = test_input($_POST["phone"]);
$username = test_input($_POST["username"]);
$pass = test_input($_POST["password"]);
if (empty($username)){
header("Location: ../page/register.php?error=emptyUsername&username=".$username."&email=".$email."&phone=".$phone);
exit();
}
elseif (empty($phone)){
header("Location: ../page/register.php?error=emptyPhone&username=".$username."&email=".$email."&phone=".$phone);
exit();
}
elseif (empty($pass)){
header("Location: ../page/register.php?error=emptyPass&username=".$username."&email=".$email."&phone=".$phone);
exit();
}
elseif (empty($email)){
header("Location: ../page/register.php?error=emptyEmail&username=".$username."&email=".$email."&phone=".$phone);
exit();
}
elseif (!filter_var($email , FILTER_VALIDATE_EMAIL)) {
header("Location: ../page/register.php?error=invalidEmailFormat&username=".$username."&phone=".$phone);
exit();
}
elseif (!preg_match("/^[a-z\d_]{2,20}$/i" , $username)){
header("Location: ../page/register.php?error=invalidUserName&email=".$email."&phone=".$phone);
exit();
}
elseif (!preg_match("/^[0-9]{11}+$/" , $phone)){
header("Location: ../page/register.php?error=invalidPhoneNumber&email=".$username."&phone=".$phone);
exit();
}
else {
$sql = "SELECT username FROM registered WHERE username = ?";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt , $sql)){
header("Location: ../page/register.php?error=SQLcheckUser");
exit();
}
else {
mysqli_stmt_bind_param($stmt , "s" , $username);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$rowcount = mysqli_stmt_num_rows($stmt);
if($rowcount > 0 ) {
header("Location: ../page/register.php?error=UserNameTaken");
exit();
}
else {
$sql = "INSERT INTO registered(email,phone,username,password) VALUES(?,?,?,?)";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt , $sql)){
header("Location: ../page/register.php?error=SQLInsert");
exit();
}
else {
$hased_pass = password_hash($pass , PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt , "ssss" , $email , $phone , $username , $hased_pass);
mysqli_stmt_execute($stmt);
header("Location: ../page/register.php?register=success");
exit();
}
}
}
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
elseif (isset($_POST['submit']) && !isset($_POST['rules-check'])) {
$email = test_input($_POST["email"]);
$phone = test_input($_POST["phone"]);
$username = test_input($_POST["username"]);
$pass = test_input($_POST["password"]);
header("Location: ../page/register.php?rules=notChecked&username=".$username."&email=".$email."&phone=".$phone);
exit();
}
else {
header("Location: ../page/register.php?access=denied");
exit();
}
?>
You can render the part of the page you prefer depending on your URL parameters by doing
<?php
if ($_GET['success']) { ?>
<-- YOUR HTML SUCCESS CODE -->
<?php } else { ?>
<-- YOUR HTML FORM CODE -->
<?php }
?>
Ajax is the best solution for me (it can be difficult to understand but the code is clean), here an example of Ajax with your situation :
Extras is the ID of all the input in the form
Page is the PHP page to be executed (register-controller.php)
Origin is the ID where you want to put the result, Origin can be null.
(To have something in the return, you have to put an echo in the php file you specified in Page)
static Ajax(origin,Extras,page)
{
var xhr = new XMLHttpRequest();
let formData = new FormData();
for(var element in Extras)
{
if(document.getElementById(element))
{
formData.append(element,document.getElementById(element));
}
else
{
let checkbox = document.getElementsByName(element);
if(checkbox)
{
//Checkbox don't work with an ID so put instead a name
for(let i=0;i<checkbox.length;i++)
{
if(checkbox[i].checked)
{
formdata.append(element+i,"1")
}
else
{
formdata.append(element+i,"0")
}
}
}
}
}
xhr.open('POST',page);
xhr.addEventListener('readystatechange', function () {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
let i= xhr.responseText;
if(origin!=null)
{
if(document.getElementById(origin) && xhr.responseText!="")
// the result document.getElementById(origin).innerHTML=xhr.responseText;
}
finish(i);
}
else if (xhr.readyState === XMLHttpRequest.DONE && xhr.status != 200) {
// error message XHR,
let textError = "Ajax Error : " + xhr.status + ", " + xhr.statusText + ", ";
alert(textError);
}
});
// send
xhr.send(formData);
}
Being new to PHP and ajax XmlHttpRequest calls altogether, I am struggling to figure out what is wrong with my code. Gone through the documentation but it seems I'm struggling to put the db row names into an array. I ideally want to asynchronously display an innerHTML below the input to indicate whether the item is in db or not. Right now it is showing 'undefined' as seen below until I type the last item in the db. it's only responding to the last item in the db meaning there's probably an issue with my loop. Any help is welcome.
index.php
<?php
include 'db.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="http://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<link href="css/main.css" rel="stylesheet">
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous">
</script>
<script src="js/todo.js" type="text/javascript"></script>
<script>
</script>
</head>
<body onload="process()">
<div class="list">
<h1 class="header">My To Do</h1>
<form>
<ul class="items">
<?php
$sql = "SELECT * FROM items ORDER BY items.id ASC";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_assoc($result)){
echo "<li><input type='checkbox' /><label>";
echo $row['name'];
echo "</label></li><br>";
}
} else {
echo "There are no to-dos!";
}
echo "<br/><br/>";
echo "<li><input type='checkbox' /><label>Mark all as completed</label></li>";
?>
</ul><br />
</form>
</div>
<div class="list">
<form class="item-add" method="post">
<input type="text" id="name" name="name" placeholder="Enter new item" class="input" autocomplete="off" required>
<input name="myBtn" type="submit" value="Add Item">
<div id="status"></div>
</form>
</div>
</body>
item.php
<?php
include 'db.php';
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql = "SELECT * FROM items ORDER BY items.id ASC";
$result = mysqli_query($conn, $sql);
$itemArray = array();
$rowNum = mysqli_num_rows($result);
//is this the correct way to add db items to an array?
if($rowNum > 0){
while ($row = mysqli_fetch_assoc($result)){
for ($x = 0; $x <= $rowNum; $x++) {
$itemArray[$x] = $row['name'];
}
}
} else {
echo "There are no to-dos!";
}
$entry = $_GET['name'];
if(in_array($entry, $itemArray))
echo 'Item ' .$entry. ' already exists! Please enter a new item...';
elseif ($name == '')
echo "Please enter an item...";
else {
//code for insertion
echo "Successfully Inserted";
}
echo '</response>';
?>
item.js
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject() {
var xmlHttp;
if(window.ActiveXObject) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
xmlHttp = false;
}
} else {
try {
xmlHttp = new XMLHttpRequest();
} catch(e) {
xmlHttp = false;
}
}
if(!xmlHttp) {
alert("cant create that object hoss");
} else {
return xmlHttp;
}
}
function process() {
if (xmlHttp.readyState==0 || xmlHttp.readyState==4) {
name = encodeURIComponent(document.getElementById('name').value);
xmlHttp.open("GET", "item.php?name="+name, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
} else {
setTimeout('process()', 1000);
}
}
function handleServerResponse(){
if(xmlHttp.readyState==4) {
if(xmlHttp.status==200){
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
console.log(xmlResponse.documentElement);
message = xmlDocumentElement.firstChild.data;
document.getElementById('status').innerHTML =
'<span style="color:blue">' + message + '</span>';
setTimeout('process()', 1000);
} else {
alert('Something went wrong!');
}
}
}
$name is not defined in your PHP file , Shouldnt it be $entry that you are checking in the elseif condition below
$entry = $_GET['name'];
if(in_array($entry, $itemArray))
echo 'Item ' .$entry. ' already exists! Please enter a new item...';
elseif ($entry == '')
echo "Please enter an item...";
else {
//code for insertion
echo "Successfully Inserted";
}
also the correct way to assign a DB column to an array should be like below .
if($rowNum > 0){
while ($row = mysqli_fetch_assoc($result)){
$itemArray[] = $row['name'];
}
} else {
echo "There are no to-dos!";
}
Here is my codes-
client.php
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<style>
#show{
background:red;
}
</style>
</head>
<body>
<?php
<div id="show"></div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
$('#show').load('api.php')
});
});
</script>
</body>
</html>
api.php
<?php
$conn = new mysqli('localhost', 'root', '', 'ajax01');
if ($conn->connect_error) {
die("Connection error: " . $conn->connect_error);
}
$result = $conn->query("SELECT name FROM variables");
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo $row['name'] . '<br>';
}
}
?>
These codes are giving me the results like-
Result of above codes
I am getting the values from database and it is fetching all the data. Therefore, I need a pagination with these value. Need help.
Based on your comments,
I want a pagination that will show only one value and next page will show another...second result will show after click on next>
There are few things you need to consider here,
Instead of setInterval() and load() functions, simply use an AJAX request to implement your pagination functionality
Use prepared statements because that will help you in preventing SQL injection. Also, read about how you can prevent SQL injection in PHP.
Based on these above points and your below comments, the solution would be like this:
client.php:
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<style>
#show{
background:red;
}
</style>
</head>
<body>
<div id="show">
<?php
$conn = new mysqli('localhost', 'root', '', 'ajax01');
if ($conn->connect_error) {
die("Connection error: " . $conn->connect_error);
}
// prepare query statement
if($stmt = $conn->prepare("SELECT name FROM variables LIMIT 0, 1")){
// execute statement
$stmt->execute();
// bind result variables
$stmt->bind_result($name);
// fetch values
$stmt->fetch();
// display name and pagination link
if(isset($name) && !empty($name)){
echo $name . '<br />';
?>
<div id='link-div' style='background-color:#ffffff'>
<a href='' class='showmore' id='1'>Next »</a>
</div>
<?php
}
// close statement
$stmt->close();
}
?>
</div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(document).on('click','.showmore',function(event){
event.preventDefault();
var offset = $(this).attr('id');
$.ajax({
type: 'POST',
url: 'api.php',
cache: 'false',
data: {offset: offset},
beforeSend: function(){
$('#link-div').html('<span>Loading...</span>');
},
success: function(data){
$('#link-div').remove();
$('#show').html(data);
},
error: function(jqXHR, textStatus, errorThrown){
// error
}
});
});
});
</script>
</body>
</html>
api.php:
<?php
if(isset($_POST['offset'])){
$offset = $_POST['offset'];
$prev = $offset - 1; // Previous link in the pagination series
$next = $offset + 1; // Next link in the pagination series
$conn = new mysqli('localhost', 'root', '', 'ajax01');
if ($conn->connect_error) {
die("Connection error: " . $conn->connect_error);
}
// prepare query statement
if($stmt = $conn->prepare("SELECT COUNT(name) FROM variables")){
// execute statement
$stmt->execute();
// bind result variables
$stmt->bind_result($total_rows);
// fetch values
$stmt->fetch();
// close statement
$stmt->close();
}
// prepare query statement
if($stmt = $conn->prepare("SELECT name FROM variables LIMIT ?, 1")){
// bind parameter
$stmt->bind_param('i', $offset);
// execute statement
$stmt->execute();
// bind result variables
$stmt->bind_result($name);
// fetch values
$stmt->fetch();
// display name and pagination link
if(isset($name) && !empty($name)){
echo $name . '<br />';
?>
<div id='link-div' style='background-color:#ffffff'>
<?php
if($offset > 0){
?>
<a href='' class='showmore' id='<?php echo $prev; ?>'>«Prev </a>
<?php
}
if($offset < $total_rows - 1){
?>
<a href='' class='showmore' id='<?php echo $next; ?>'>Next »</a>
<?php
}
?>
</div>
<?php
}
// close statement
$stmt->close();
}
}
?>
I want to delete files from a directory using check-box for selecting files and button event for deleting selected ones.
so basically I want it looks like this:
the problem, I retrieve the files via php but I put this checkbox via jquery
and I dont know how to relate these elements with each other
How can I delete these selected files?
My code is down here:
$dir = 'C:\directory\of\files\here';
$files1 = scandir($dir);
$cnt = count($files1);
//var_dump($cnt);
echo "<h1><u> delete files from directory </u></h1>";
echo "<div class='container'>";
for($n=0; $n< $cnt; $n++)
{
if ( ($files1[$n])!= '.' && $files1[$n] != '..')
{
print_r("<input type='checkbox' />".($files1[$n])."<br/> ");
}
}
echo "</br>";
echo " <button>DELETE</button>";
echo "</div>";
?>
<html>
<head>
<script>
$(function() {
$( "input[type=submit], a, button" )
.button()
.click(function( event ) {
event.preventDefault();
});
</script>
</head>
<body>
</body>
</html>
Here is your main file
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8/>
<title>delete</title>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js"></script>
</head>
<body>
<form id="myform">
<?php
$filesss = array_diff(scandir(__DIR__), array('..', '.'));
foreach ($filesss as $file) {
echo "<label>";
echo "<input type='checkbox' name='file[]' value='$file'>";
echo "$file </label><br>";
}
?>
<button type="submit">delete</button>
</form>
<script>
$(document).ready(function () {
$("#myform").submit(function (event) {
$.ajax({
type: 'POST',
url: 'delete.php',
data: $(this).serialize(),
success: function () {
alert("success");
}
});
event.preventDefault();
});
});
</script>
</body>
</html>
and your delete file
<?php
foreach ($_POST['file'] as $file) {
if (file_exists($file)) {
unlink($file);
}
}
Basically what you do with this code is that you collect file paths from the page and you send via ajax to delete.php what deletes the files (with unlink).
But ALWAYS use form and input validation especially when you want do delete files!
You'll need to set a <form> tag, which creates a form.
Then you'll need to set a name and value to the checkboxes.
Last but not least, when the form is submitted, PHP checks if $_POST['filenames'] is set, if yes, it loops the array and deletes all the files that are selected.
<?php
$dir = 'C:\directory\of\files\here';
if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
if( isset( $_POST['filesnames'] ) ) {
foreach( $_POST['filesnames'] as $key => $file ) {
unlink( $dir . '\\' . $file );
}
echo 'Files deleted';
}
else {
echo 'No files selected';
}
}
$files1 = scandir($dir);
$cnt = count($files1);
//var_dump($cnt);
echo "<h1><u> delete files from directory </u></h1>";
echo "<div class='container'>";
echo "<form action='".$_SERVER['PHP_SELF']."' method='post'>";
for($n=0; $n< $cnt; $n++)
{
if ( ($files1[$n])!= '.' && $files1[$n] != '..')
{
print_r("<input name='filesnames[]' value='".($files1[$n])."' type='checkbox' />".($files1[$n])."<br/> ");
}
}
echo "</br>";
echo " <submit>DELETE</submit>";
echo "</form>";
echo "</div>";
?>
you can do something like this
<?php
$dir = 'C:\directory\of\files\here';
if($_SERVER['REQUEST_METHOD'] == 'POST') {
foreach($_POST['files'] as $file) {
$file = addslashes($file);
if(is_readable($file)) {
unlink($file);
}
}
} else {
$files = scandir($dir);
}
?>
<html>
<head>
<script>
$(document).ready(function() {
$('#deleteFiles').on('submit', function(e) {
e.preventDefault();
$.ajax({
url: location.href,
}).done(function() {
alert('Done !!!');
});
})
});
</head>
<body>
<h1><u> delete files from directory </u></h1>
<div class="container">
<form action="#" method="post" id="deleteFiles">
<?php foreach($files as $file): ?>
<?php if($file === '.' || $file === '..') { continue; } ?>
<lable>
<input type="checkbox" name="files[]" value="<?php echo $file; ?>">
$<?php echo $file; ?>
</lable>
<?php endforeach; ?>
<input type="submit" value="Delete">
</form>
</body>
</html>
So I was following a tutorial and I came across the current problem. This is my first time using the ajax method. I copied and saved jQuery version 1.7.2.min.js in a folder. My php code seems to be working fine, the only thing that seems off is the code for the ajax part.
This code is in a folder called "includes"
<div id="messages">
<!--Javascript-->
<script type= "text/javascript" src= "script/jquery-1.7.2.min.js"></script>
<script type= "text/javascript" src= "script/auto_chat.js"></script>
</div><!-- Messages -->
This is the javascript in a folder called "script" named auto_chat
$(document).ready(function() {
var interval = setInterval(function() {
$.ajax({
url: 'script/Chat.php' ,
success: function(data) {
$('#messages').html(data);
}
});
}, 1000);
});
There is a file called Chat.php containing code that links to the database.
When it runs it should show all the messages inside of the database. Instead it gives me blank and not even errors. Can someone tell me whats wrong with my method?
This is the my Chat.php
<?php
require('../includes/database/connect.db.php')
function get_msg(){
$query = "SELECT `Sender`,`Message` FROM `chat`.`chat` ORDER BY `Msg_ID` DESC";
$run = mysql_query($query);
$messages = array();
while($message = mysql_fetch_assoc($run)){
$messages[] = array('sender' => $message['Sender'],
'message' => $message['Message']);
}
return $messages;
}
function send_msg($sender, $message) {
if(!empty($sender) && !empty($message)) {
$sender = mysql_real_escape_string($sender);
$message = mysql_real_escape_string($message);
$query = "INSERT INTO `chat` . `chat` VALUES (null,'{$sender}','$message')";
if ($run = mysql_query($query)){
return true;
}else{
return false;
}
}else {
return false;
}
}
if(isset($_POST['send'])){
if(send_msg($_POST['sender'],$_POST['message'])){
echo 'Message Sent';
}else{
echo 'Message Failed to sent';
}
}
$messages = get_msg();
foreach($messages as $message) {
echo '<strong>' . $message['sender'] .' Sent</strong><br />';
echo $message['message']. '<br /><br />';
}
?>
And this is all of my index.php
<!DOCTYPE html>
<?php
require('includes/core.inc.php');
function get_msg(){
$query = "SELECT `Sender`,`Message` FROM `chat`.`chat` ORDER BY `Msg_ID` DESC";
$run = mysql_query($query);
$messages = array();
while($message = mysql_fetch_assoc($run)){
$messages[] = array('sender' => $message['Sender'],
'message' => $message['Message']);
}
return $messages;
}
function send_msg($sender, $message) {
if(!empty($sender) && !empty($message)) {
$sender = mysql_real_escape_string($sender);
$message = mysql_real_escape_string($message);
$query = "INSERT INTO `chat` . `chat` VALUES (null,'{$sender}','$message')";
if ($run = mysql_query($query)){
return true;
}else{
return false;
}
}else {
return false;
}
}
if(isset($_POST['send'])){
if(send_msg($_POST['sender'],$_POST['message'])){
echo 'Message Sent';
}else{
echo 'Message Failed to sent';
}
}
?>
<html lang = "en">
<head>
<!--Page TItle --!>
<title>Chat Application </title>
<link type="text/css" rel= "stylesheet" href= "includes/main.css" />
</head>
<body>
<div id="input">
<form action = "index.php" method = "post">
<label>Enter Name:<input type = "text" name = "sender"/></label>
<label>Enter Message:<input type = "text" name = "message"/></label><br />
<input type = "submit" name = "send" value = "Send Message"/>
</form>
</div>
<div id="messages">
<?php
$messages = get_msg();
foreach($messages as $message) {
echo '<strong>' . $message['sender'] .' Sent</strong><br />';
echo $message['message']. '<br /><br />';
}
?>
<!--Javascript-->
<script type= "text/javascript" src= "script/jquery-1.7.2.min.js"></script>
<script type= "text/javascript" src= "script/auto_chat.js"></script>
</div><!-- Messages -->
</body>
</html>
After a lot of trial and error, we found out that the problem was a simple missing semicolon on chat.php:
require('../includes/database/connect.db.php');
:)