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');
:)
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);
}
I'm trying to redirect using PHP header/even a JavaScript work around call inside php to my clients.php webpage.
The problem is that PHP header/the work around loads the webpage flawlessly but the Javascript still isn't ran.
Additional notes is that after the header or even Javascript redirect to the page, trying to refresh the page won't have the Javascript load. Only switching between a webpage and coming back to clients.php does the Javascript actually run.
I have also tried this: JavaScript not loading after PHP header() redirect
but to no avail.
Here are parts of my code segmented, just because its quite lengthy.
clients.php
<!-- Bootstrap core JavaScript-->
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- Core plugin JavaScript-->
<script src="vendor/jquery-easing/jquery.easing.min.js"></script>
<!-- Page level plugin JavaScript-->
<script src="vendor/chart.js/Chart.min.js"></script>
<script src="vendor/datatables/jquery.dataTables.js"></script>
<script src="vendor/datatables/dataTables.bootstrap4.js"></script>
<!-- Custom scripts for all pages-->
<script src="js/sb-admin.min.js"></script>
<!-- Custom scripts for this page-->
<script src="js/sb-admin-datatables.min.js"></script>
<script src="js/sb-admin-charts.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" ty pe="text/javascript"></script>
<link href="../../css/toastr.css" rel="stylesheet"/>
<script src="../../js/toastr.js"></script>
<script type="text/javascript">
var tmp = "<?php $tmp = $_SESSION['message_success']; echo "$tmp"; ?>";
alert(tmp + " h");
$( document ).ready(function() {
<?php
if($_SESSION['sysLogin'] == "success") {
$_SESSION['sysLogin'] = "";
$user = $_SESSION['user'];
echo "toastr.success('Welcome $user', 'User has logged in');";
}
if($_SESSION['message_success'] != "") {
$msg = $_SESSION['message_success'];
$_SESSION['message_success'] = "";
echo "toastr.success('$msg', 'Success!');";
}
if($_SESSION['message_error'] != "") {
$msg = $_SESSION['message_error'];
$_SESSION['message_error'] = "";
echo "toastr.error('$msg', 'Error!');";
}
if($_SESSION['message_warning'] != "") {
$msg = $_SESSION['message_warning'];
$_SESSION['message_warning'] = "";
echo "toastr.warning('$msg', 'Warning!');";
}
?>
});
</script>
</div>
</body>
</html>
script.php
if($update_statement) {
$_SESSION['message_success'] = "$_membername's Careplan has been successfully updated.";
echo "<script type='text/javascript'>window.location.href = '../clients.php';</script>";
//header("Location:". $redirect);
//exit();
}
Note that clients.php and script.php are not in the same file.
Per Riggs request
<?php
session_start();
$message="";
if(isset($_POST["login"])) {
$redirect = NULL;
if($_POST['redirect'] != '') {
$redirect = $_POST['redirect'];
}
if(empty($_POST['username']) || empty($_POST['password'])) {
$message = "Both fields must be filled out.";
$_SESSION['sysLogin'] = "$message";
header("location: ../login.php?redirect=" . urlencode($redirect));
} else {
require('server_connection.inc');
$connection = connect_to_db(DB_SERVER, DB_UN, DB_PWD, DB_NAME);
$user=mysqli_real_escape_string($connection, $_POST['username']);
$pass=mysqli_real_escape_string($connection, $_POST['password']);
$statement = "select * from Credentials where UserName='$user' AND Password='$pass';";
$result = $connection->query($statement);
if($result->num_rows == 1) {
// lets determine the type of user that logged in
// if not employee but CEO, Manager, ETC, its an Admin
$employeeid = ($result->fetch_assoc())["EmployeeID"];
$check = "select Employees.Position, Employees.Name, Employees.ID from Credentials, Employees where (Credentials.EmployeeID = Employees.ID) AND Employees.ID = '$employeeid';";
$result_two = $connection->query($check);
if($result->num_rows == 1) {
$the_row = $result_two->fetch_assoc();
if($the_row["Position"] == "Employee") {
$name = $the_row["Name"];
$the_id = $the_row['ID'];
$_SESSION['logon'] = true;
$_SESSION['user'] = "$name";
$_SESSION['type'] = "employee";
$_SESSION['sysLogin'] = "success";
$_SESSION['user_id'] = $the_id;
mysqli_close($conection);
if($redirect) {
header("Location:". $redirect);
} else {
header("location: ../index.php");
}
exit();
} else if($the_row["Position"] == "CEO" || $the_row["Position"] == "Manager") {
$name = $the_row["Name"];
$the_id = $the_row['ID'];
$_SESSION['logon'] = true;
$_SESSION['user'] = "$name";
$_SESSION['type'] = "admin";
$_SESSION['sysLogin'] = "success";
$_SESSION['user_id'] = $the_id;
mysqli_close($conection);
if($redirect) {
header("Location:". $redirect);
} else {
header("location: ../index.php");
}
exit();
}
} else {
$message = "Unable to Parse Employee. Please contact your sites Administrator.";
$_SESSION['sysLogin'] = "$message";
mysqli_close($conection);
header("location: ../login.php?redirect=" . urlencode($redirect));
}
} else if($result->num_rows == 0){
$message = "Incorrect username or password";
$_SESSION['sysLogin'] = "$message";
mysqli_close($conection);
header("location: ../login.php?redirect=" . urlencode($redirect));
} else {
$message = "Database Login Error. Too many retrieved accounts. Please contact your sites Administrator.";
$_SESSION['sysLogin'] = "$message";
mysqli_close($conection);
header("location: ../login.php?redirect=" . urlencode($redirect));
}
}
}
function write_to_log($message) {
$file = fopen("logfile.txt", "w") or die("Unable to open file!");
fwrite($file, "$message\n");
fclose($file);
}
function connect_to_db($server, $username, $pwd, $dbname) {
$conn = mysqli_connect($server, $username, $pwd);
if(!$conn) {
echo "" . mysqli_error($conn);
exit;
}
$dbh = mysqli_select_db($conn, $dbname);
if(!$dbh) {
echo "" . mysqli_error($conn);
exit;
}
return $conn;
}
?>
This script merely links session while also checking for the login validity of the user
The message passing does indeed work with headers to another file 'dashboard.php' but redirecting from script.php to dashboard.php doesn't yield the message, thus an implication still arises.
The tmp JavaScript variable is not being defined since you haven't started the session. Include session_start(); at the top of your code.
<?php session_start(); ?>
<!-- Bootstrap core JavaScript-->
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- Core plugin JavaScript-->
<script src="vendor/jquery-easing/jquery.easing.min.js"></script>
<!-- Page level plugin JavaScript-->
<script src="vendor/chart.js/Chart.min.js"></script>
<script src="vendor/datatables/jquery.dataTables.js"></script>
<script src="vendor/datatables/dataTables.bootstrap4.js"></script>
<!-- Custom scripts for all pages-->
<script src="js/sb-admin.min.js"></script>
<!-- Custom scripts for this page-->
<script src="js/sb-admin-datatables.min.js"></script>
<script src="js/sb-admin-charts.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" ty pe="text/javascript"></script>
<link href="../../css/toastr.css" rel="stylesheet"/>
<script src="../../js/toastr.js"></script>
<script type="text/javascript">
var tmp = "<?php $tmp = $_SESSION['message_success']; echo "$tmp"; ?>";
alert(tmp + " h");
$( document ).ready(function() {
<?php
if($_SESSION['sysLogin'] == "success") {
$_SESSION['sysLogin'] = "";
$user = $_SESSION['user'];
echo "toastr.success('Welcome $user', 'User has logged in');";
}
if($_SESSION['message_success'] != "") {
$msg = $_SESSION['message_success'];
$_SESSION['message_success'] = "";
echo "toastr.success('$msg', 'Success!');";
}
if($_SESSION['message_error'] != "") {
$msg = $_SESSION['message_error'];
$_SESSION['message_error'] = "";
echo "toastr.error('$msg', 'Error!');";
}
if($_SESSION['message_warning'] != "") {
$msg = $_SESSION['message_warning'];
$_SESSION['message_warning'] = "";
echo "toastr.warning('$msg', 'Warning!');";
}
?>
});
</script>
</div>
</body>
</html>
To my surprise, the issue wasn't with the Javascript at all nor positioning like the thread posted suggested. Rather the issue seemed to have been with my PHP and calling $_membersname.
For advice to trouble shoot this later on, make sure no errors are outputted, even if PHP doesn't find any. This is from a variable that hasn't be declared.
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!";
}
Hello I'm a beginner in Ajax and PHP so sorry if my question is useless or stupid. But I am trying to do a live search with ajax and I have looked over and over internet but nothing could help me... so here I am! :-) I have 4 files one for the html, one to connect to the database, one for jQuery and the last one for the script in php. I have looked on the console with chrome and I can see that the ajax works but there is no output and I have no idea why... I'll leave you the code below and an early thank you! Also there might be some French in the code but it's just the variables and I will secure my connection to the database later. Thank you again.
Html :
<html>
<head>
<meta charset="utf-8" />
<title>live search test</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" src="search.js"></script>
</head>
<body>
<h1>LIVE SEARCH WITH AJAX TEST</h1>
<div class="search">
<input type="search" name="search" id="recherche">
</div>
<br>
<div class="resultat" id="resultat">
</div>
</body>
</html>
PHP to connect to the database:
<?php
$host="localhost";
$user="root";
$password="";
$db="smartphone";
$conn=mysqli_connect($host,$user,$password,$db);
?>
jQuery:
$(document).ready(function(){
$("#recherche").keyup(function(){
var recherche = $(this).val();
var data = 'motclef = ' + recherche;
if (recherche.length > 1) {
$.ajax({
type : "GET",
url : "fetch.php",
data : data,
success : function(server_response){
$("#resultat").html(server_response).show();
}
});
}
});
});
And the script in PHP:
include'connect.php';
if (isset($_GET['motclef'])) {
$motclef = $_GET['motclef'];
$q = array('motclef' => $motclef. '%');
$sql = "SELECT name FROM smartphone WHERE name LIKE :motclef";
$req = $conn ->prepare($sql);
$req -> execute($q);
$count = $req->rowCount($sql);
if ($count == 1) {
while ($result = $req -> fetch(PDO::FETCH_OBJ)) {
echo 'Smartphone :'.$result ->title.' ';
}
}else {
echo "Aucun resultat trouvé pour:". $motclef;
}
}
?>
Remove whitespace from 'motclef = '
var data = 'motclef= ' + recherche;
Other wise put underscore $_GET['motclef_'] in your PHP code(if you don't remove space then)
if (isset($_GET['motclef_'])) {
$motclef = $_GET['motclef_'];
$q = array('motclef' => $motclef. '%');
$sql = "SELECT name FROM smartphone WHERE name LIKE :motclef";
$req = $conn->prepare($sql);
$req->execute($q);
$count = $req->rowCount($sql);
if ($count == 1) {
while ($result = $req->fetch(PDO::FETCH_OBJ)) {
echo 'Smartphone :'.$result->title.' ';
}
}else {
echo "Aucun resultat trouvé pour:". $motclef;
}
}
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!";
}
?>