PHP XmlHttpRequest error with simple to-do list - javascript

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!";
}

Related

I want to change or remove my html element by getting URL parameters that I set after successful register

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

How to refresh data in table using ajax?

I'm new to ajax. I just want to simply view my table from the database using ajax. I have 2 files listbarang.html and showlist.php.
Here's my code
PHP (showlist.php)
<?php
$link = #mysqli_connect("localhost", "root", "","projekpweb");
if($link->connect_errno)
{
echo "Failed to connect. " . $link->connect_error;
}
$sql = "SELECT * FROM `barang`";
$result = mysqli_query($link, $sql);
if(!$result)
{
die("SQL GAK KONEK : " . mysqli_error($link));
}
echo "<table>
<tr>
<th>idbarang</th>
<th>nama</th>
<th>harga</th>
<th>ekstensi_gambar</th>
</tr>";
while ($row = mysqli_fetch_array($result))
{
echo " <tr>
<td>".$row["idbarang"]."</td>
<td>".$row["nama"]."</td>
<td>".$row["harga"]."</td>
<td>".$row["ekstensi_gambar"]."</td>
</tr>";
}
echo "</table>"; ?>
HTML (listbarang.html)
<!DOCTYPE html>
<html>
<head>
<title>LIST BARANG</title>
<script type="text/javascript">
function showList()
{
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200)
{
document.getElementById("tblList").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","showlist.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="tblList">
<script type="text/javascript">
showlist();
</script>
</div>
</body>
</html>
I wonder why the #tblList doesnt have the content of the the table.
Thanks in advance

Login function not working

Okay so i made a login button and this is the function code, But it keeps showing the error " Login unsuccessful, Please try again... "
Thank you in advance...
I didn't really get what you were asking for so i put almost all the code in cause i am trying and trying and can't figure it out...
<?php
include_once ("php_includesss121/check_login_statusopop.php");
// If user is already logged in, header that user away
if ($user_ok == true)
{
header("location: user.php?u=" . $_SESSION["username"]);
exit();
}
?><?php
// AJAX CALLS THIS LOGIN CODE TO EXECUTE
if (isset($_POST["e"]))
{
// CONNECT TO THE DATABASE
include_once ("php_includesss121/db_conxx12.php");
// GATHER THE POSTED DATA INTO LOCAL VARIABLES AND SANITIZE
$e = mysqli_real_escape_string($db_conx, $_POST['e']);
$p = md5($_POST['p']);
// GET USER IP ADDRESS
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
// FORM DATA ERROR HANDLING
if ($e == "" || $p == "")
{
echo "login_failed";
exit();
}
else
{
// END FORM DATA ERROR HANDLING
$sql = "SELECT id, username, password FROM users WHERE email='$e' AND activated='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
$db_id = $row[0];
$db_username = $row[1];
$db_pass_str = $row[2];
if ($p != $db_pass_str)
{
echo "login_failed";
exit();
}
else
{
// CREATE THEIR SESSIONS AND COOKIES
$_SESSION['userid'] = $db_id;
$_SESSION['username'] = $db_username;
$_SESSION['password'] = $db_pass_str;
setcookie("id", $db_id, strtotime('+30 days') , "/", "", "", TRUE);
setcookie("user", $db_username, strtotime('+30 days') , "/", "", "", TRUE);
setcookie("pass", $db_pass_str, strtotime('+30 days') , "/", "", "", TRUE);
// UPDATE THEIR "IP" AND "LASTLOGIN" FIELDS
$sql = "UPDATE users SET ip='$ip', lastlogin=now() WHERE username='$db_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
echo $db_username;
exit();
}
}
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Log In</title>
<link rel="icon" href="favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="style/style.css">
<script src="js/mainopop.js"></script>
<script src="js/ajaxopop.js"></script>
<script>
function emptyElement(x){
_(x).innerHTML = "";
}
function login(){
var e = _("email").value;
var p = _("password").value;
if(e == "" || p == ""){
_("status").innerHTML = "Fill out all of the form data";
} else {
_("loginbtn").style.display = "none";
_("status").innerHTML = 'Please wait...';
var ajax = ajaxObj("POST", "login.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "login_failed"){
_("status").innerHTML = "Login unsuccessful, Please try again...";
_("loginbtn").style.display = "block";
} else {
window.location = "user.php?u="+ajax.responseText;
}
}
}
ajax.send("e="+e+"&p="+p);
}
}
</script>
</head>
<body>
<?php
include_once ("template_pageTopLoginPageopop.php"); ?>
<div id="pageMiddle">
<h2>Welcome ...</h2>
<h3>Log In Here</h3>
<!-- LOGIN FORM -->
<form id="loginform" onsubmit="return false;">
<div>Email Address:</div>
<input type="text" id="email" onfocus="emptyElement('status')" maxlength="300">
<div>Password:</div>
<input type="password" id="password" onfocus="emptyElement('status')" maxlength="100">
<br />
<br />
<button id="loginbtn" onclick="login()">Log In</button>
<p id="status"></p>
Forgot Your Password?
</form>
<!-- LOGIN FORM -->
</div>
<?php
include_once ("template_pageBottomopop.php");
?>
</body>
</html>
And Javascript file ajaxopop.js:
function ajaxObj(meth, url) {
var x = new XMLHttpRequest();
x.open(meth, url, true);
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x) {
if (x.readyState == 4 && x.status == 200) {
return true;
}
}
Please note that password in DB Table should be md5
encrypted as in PHP, you are encrypting it to match further. If not, just remove md5 encryption from PHP Code.

How to echo style and script tags using php

hello i have a php page that is to output results in my html page using div through an ajax request medium,
i intend outpiting this results using listviews as my application targets mobile phones and tablets, so i am making use of the jquery mobile framework.
i have outputed my results successfully with this
<?php header('Access-Control-Allow-Origin: *'); ?>
<?php
$users = ($_GET['users']);
$user = ($_GET['user']);
$con = mysqli_connect('localhost','whitech3_manage','famakin','whitech3_manage');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"whitech3_manage");
$sql="SELECT * FROM data WHERE fromwhere = '".$users."' and towhere = '".$user."'";
$result = mysqli_query($con,$sql);
echo '<head>';
echo "<link rel='stylesheet' href='themes/transport.min.css' />";
echo "<link rel='stylesheet' href='themes/jquery.mobile.icons.min.css' />";
echo "<link rel='stylesheet' href='themes/jquery.mobile.structure-1.4.2.min.css' />";
echo "<script src='themes/jquery-1.10.2.min.js'></script>";
echo "<script src='themes/jquery.mobile-1.4.2.min.js'></script>";
echo '</head>';
while($row = mysqli_fetch_array($result)) {
echo "<div data-role='collapsible' data-theme='b' data-content-theme='b'>";
echo "<ul data-role='listview' data-filter='true'>";
echo "<li><a href='#'>". $row['fromwhere'] . "</a></li>";
echo "<li><a href='#'>". $row['towhere'] . "</a></li>";
echo "<li><a href='#'>". $row['details'] . "</a></li>";
echo "<li><a href='#'>". $row['time frame'] . "</a></li>";
echo "</ul>";
echo "</div>";
}
mysqli_close($con);
?>
but whenever my results are displayed they r not formatted properly to look like a listview, hence i knw i am supposed to load my style sheets and javascript tags to make sure the listview is displayed properly.
i have tried and tried to echo the links to my stylesheets and js using echo statements, but it dosent seem to make my listview show up properly.
this is what i have tried
echo '<head>';
echo "<link rel='stylesheet' href='themes/transport.min.css' />";
echo "<link rel='stylesheet' href='themes/jquery.mobile.icons.min.css' />";
echo "<link rel='stylesheet' href='themes/jquery.mobile.structure-1.4.2.min.css' />";
echo "<script src='themes/jquery-1.10.2.min.js'></script>";
echo "<script src='themes/jquery.mobile-1.4.2.min.js'></script>";
echo '</head>';
function showUser() {
if (showUser == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
var usersvalue=encodeURIComponent(document.getElementById("users").value)
var uservalue=encodeURIComponent(document.getElementById("user").value)
xmlhttp.open("GET","http://whitechapelandpartners.com/getuserwrong.php?users="+usersvalue+"&user="+uservalue, true);
xmlhttp.send();
}
}
<div id="txtHint"><b>Person info will be listed here.</b></div><br /><br /><br /><br />
</div>
any suggestion please, by logic i was hoping the echo statement would work
Here is my suggestion
<?php header('Access-Control-Allow-Origin: *'); ?>
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' href='themes/transport.min.css' />
<link rel='stylesheet' href='themes/jquery.mobile.icons.min.css' />
<link rel='stylesheet' href='themes/jquery.mobile.structure-1.4.2.min.css' />
<script type="text/javascript" src='themes/jquery-1.10.2.min.js'></script>
<script type="text/javascript" src='themes/jquery.mobile-1.4.2.min.js'></script>
<script type="text/javascript">
function showUser(user) { // how do you call this? You need to pass it a user too
if (user == "") {
$("#txtHint").empty();
return;
}
var usersvalue=encodeURIComponent($"#users").val()),
uservalue=encodeURIComponent($("#user").val());
// assuming you are accessing the same origin
$.get("/getuserwrong.php?users="+usersvalue+"&user="+uservalue,
function(data) {
$("#txtHint").html(data);
}
);
}
</script>
</head>
<body>
<?php
$users = ($_GET['users']);
$user = ($_GET['user']);
// I think you do not want to show your userID and password here on this site
$con = mysqli_connect('localhost','...','...','...');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"whitech3_manage");
$sql="SELECT * FROM data WHERE fromwhere = '".$users."' and towhere = '".$user."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
echo <<<EOT
<div data-role='collapsible' data-theme='b' data-content-theme='b'>
<ul data-role='listview' data-filter='true'>
<li><a href='#'>$row['fromwhere']</a></li>
<li><a href='#'>$row['towhere']</a></li>
<li><a href='#'>$row['details']</a></li>
<li><a href='#'>$row['time frame']</a></li>
</ul>
</div>
EOT;
}
mysqli_close($con);
?>
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>
try this :
function showUser() {
if (showUser == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var collapsible = xmlhttp.responseText;
document.getElementById("txtHint").innerHTML = $(collapsible).collapsible();
}
}
var usersvalue=encodeURIComponent(document.getElementById("users").value)
var uservalue=encodeURIComponent(document.getElementById("user").value)
xmlhttp.open("GET","http://whitechapelandpartners.com/getuserwrong.php?users="+usersvalue+"&user="+uservalue, true);
xmlhttp.send();
}
}
<div id="txtHint"><b>Person info will be listed here.</b></div><br /><br /><br /><br />
</div>
I hope this works. :D

AJAX, jQuery, javascript for a chatroom

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');
:)

Categories

Resources