jQuery $.ajax is not triggering anything to happen - javascript

I am trying to create a text box and whenever a user enters a message and clicks on send, the ajax should be activated and what's on insertMessage.php should get triggered. However, whenever i click on send it doesn't work. here is my chatbox.php file
<?php
session_start();
$conn = new mysqli("localhost", "root", "", "events");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$user=$_SESSION['userid'];
$sql="SELECT * FROM `users` WHERE `Email`='$user'";
$res= mysqli_query($conn,$sql);
$user=mysqli_fetch_assoc($res);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<title></title>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-md-4">
<p>Hi <?php echo $user["FullName"]; ?></p>
<input type="text" id="fromUser" value=<?php echo $user["Email"]; ?> hidden />
<p>Send Message To:</p>
<ul>
<?php
$msgs=mysqli_query($conn,"SELECT * FROM users");
while($msg=mysqli_fetch_assoc($msgs))
{
echo '<li>'.$msg["FullName"].'</li>';
}
?>
</ul>
<--Back
</div>
<div class="col-md-4">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"><?php
if(isset($_GET["toUser"]))
{
$user=$_GET["toUser"];
$email=mysqli_query($conn,"SELECT * FROM users WHERE Email='$user'");
$emails=mysqli_fetch_assoc($email);
echo '<input type="text" value='.$user.' id="toUser" hidden/>';
echo $emails["Email"];
}
else{
$email=mysqli_query($conn,"SELECT * FROM users");
$emails=mysqli_fetch_assoc($email);
$_SESSION['toUser']=$emails['Email'];
echo '<input type="text" value='.$_SESSION['toUser'].' id="toUser" hidden/>';
echo $emails["Email"];
}
?></h5>
</div>
<div class="model-body" id="msgBody" style="height:400px; overflow-y:scroll; overflow-x:hidden;">
<?php
if(isset($_GET["toUser"]))
{
$chats=mysqli_query($conn,"SELECT * FROM `message` WHERE (`Receiver`='".$_SESSION["userid"]."' AND `Sender`='".$_GET["toUser"]."') OR (`Receiver`='".$_GET["toUser"]."' AND `Sender`='".$_SESSION["userid"]."')");
}
else{
$chats=mysqli_query($conn,"SELECT * FROM `message` WHERE (`Sender`='".$_SESSION["userid"]."' AND `Receiver`='".$_GET["toUser"]."') OR (`Sender`='".$_GET["toUser"]."' AND `Receiver`='".$_SESSION["userid"]."')");
}
while($chat=mysqli_fetch_assoc($chats))
{
if($chat["Sender"]==$_SESSION["userid"])
{
echo "<div style='text-align:right;'>
<p style='background-color:lightblue; word-wrap:break-word; display:inline-block; padding:5px; border-radius:10px; max-width:70%;'>
".$chat["Message"]."</p>
</div>";
}
else{
echo "<div style='text-align:left;'>
<p style='background-color:yellow; word-wrap:break-word; display:inline-block; padding:5px; border-radius:10px; max-width:70%;'>
".$chat["Message"]."</p>
</div>";
}
}
?>
</div>
<div class="model-footer">
<textarea id="message" class="form-control" style="height:43px;max-width:80%;float:left;">
</textarea>
<button id="send" class="btn btn-primary" style="height:70%;float:left;">Send</button>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-4">
</div>
</div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#send').on('click', function(e) {
e.preventDefault();
$.ajax({
url:"insertMessage.php",
method:"POST",
data:{
fromUser: $("#fromUser").val();
toUser:$("#toUser").val();
message:$("#message").val();
},
dataType:"text",
success:function(data){
$("#message").val("");
}
});
e.preventDefault();
});
});
</script>
</html>
and here is my insertMessage.php file
<?php
session_start();
$conn = new mysqli("localhost", "root", "", "events");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$fromUser=$_POST["fromUser"];
$toUser=$_POST["toUser"];
$message=$_POST["message"];
$output="";
$sql="INSERT INTO `message`(`Sender`, `Receiver`, `Message`) VALUES ('$fromUser','$toUser','$message')";
if($connect->query($sql)){
$output.="";
}
else{
$output.="Error. Please Try Again.";
}
echo $output;
?>
I don't know what to do i tried to find the issue so much but I couldn't. I am new to ajax so I don't know..

I am not sure what your exact problem is but there is one issue in your jQuery code, it takes an object as a value of data, like below :
data: {
fromUser: $("#fromUser").val(),
toUser: $("#toUser").val(),
message: $("#message").val()
},
dataType: "text",
Replace your semicolon (;) with a comma(,)

Put all your form elements inside a <form> in order to receive a data from your $_POST.
<form method="post" action="insertMessage.php">
/* your form elements here */
</form>
Don't forget to include method="post" in your form element, put name="fieldName" on your input elements (text, button, textarea) and a submit button.

Your data seems to have issues:
So, please change:
data:{
fromUser: $("#fromUser").val();
toUser:$("#toUser").val();
message:$("#message").val();
},
To:
data:{
fromUser: $("#fromUser").val(),
toUser:$("#toUser").val(),
message:$("#message").val()
},
Explanation:
Semi colons(;)are for closing a statement.
And the fromUser and others are properties of object data. So, they should be comma separated and it is one statement.
Also, as a suggestion:
<input type="text" id="fromUser" value=<?php echo $user["Email"]; ?> hidden />
The above field definition should have double quotes("") around value.
It creates issues(without semi-colons) when there are spaces in our value.
And hidden makes no meaning at all with above, is it of type="hidden" or is it class="hidden"?

Related

CRUD application create working, but not update or delete

I tried getting the CRUD app to work from Tutorial Republic. I can create rows, but canโ€™t read, update, or delete them.
I uploaded index, create, read, update, delete, config, and error.php. It loads index.php fine but when I try to update, read, or delete, all I get is a blank page. Please help. Hereโ€™s the code.
config.php
<?php
/* Database credentials. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'user');
define('DB_PASSWORD', 'secret');
define('DB_NAME', 'demo');
/* Attempt to connect to MySQL database */
$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
?>
read.php
<?php
// Check existence of id parameter before processing further
if(isset($_GET["id"]) && !empty(trim($_GET["id"]))){
// Include config file
require_once "config.php";
// Prepare a select statement
$sql = "SELECT * FROM employees WHERE id = ?";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "i", $param_id);
// Set parameters
$param_id = trim($_GET["id"]);
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
$result = mysqli_stmt_get_result($stmt);
if(mysqli_num_rows($result) == 1){
/* Fetch result row as an associative array. Since the result set
contains only one row, we don't need to use while loop */
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
// Retrieve individual field value
$name = $row["name"];
$address = $row["address"];
$salary = $row["salary"];
} else{
// URL doesn't contain valid id parameter. Redirect to error page
header("location: error.php");
exit();
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
// Close connection
mysqli_close($link);
} else{
// URL doesn't contain id parameter. Redirect to error page
header("location: error.php");
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>View Record</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
.wrapper{
width: 600px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<h1 class="mt-5 mb-3">View Record</h1>
<div class="form-group">
<label>Name</label>
<p><b><?php echo $row["name"]; ?></b></p>
</div>
<div class="form-group">
<label>Address</label>
<p><b><?php echo $row["address"]; ?></b></p>
</div>
<div class="form-group">
<label>Salary</label>
<p><b><?php echo $row["salary"]; ?></b></p>
</div>
<p>Back</p>
</div>
</div>
</div>
</div>
</body>
</html>
update.php
<?php
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$name = $address = $salary = "";
$name_err = $address_err = $salary_err = "";
// Processing form data when form is submitted
if(isset($_POST["id"]) && !empty($_POST["id"])){
// Get hidden input value
$id = $_POST["id"];
// Validate name
$input_name = trim($_POST["name"]);
if(empty($input_name)){
$name_err = "Please enter a name.";
} elseif(!filter_var($input_name, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z\s]+$/")))){
$name_err = "Please enter a valid name.";
} else{
$name = $input_name;
}
// Validate address address
$input_address = trim($_POST["address"]);
if(empty($input_address)){
$address_err = "Please enter an address.";
} else{
$address = $input_address;
}
// Validate salary
$input_salary = trim($_POST["salary"]);
if(empty($input_salary)){
$salary_err = "Please enter the salary amount.";
} elseif(!ctype_digit($input_salary)){
$salary_err = "Please enter a positive integer value.";
} else{
$salary = $input_salary;
}
// Check input errors before inserting in database
if(empty($name_err) && empty($address_err) && empty($salary_err)){
// Prepare an update statement
$sql = "UPDATE employees SET name=?, address=?, salary=? WHERE id=?";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "sssi", $param_name, $param_address, $param_salary, $param_id);
// Set parameters
$param_name = $name;
$param_address = $address;
$param_salary = $salary;
$param_id = $id;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Records updated successfully. Redirect to landing page
header("location: index.php");
exit();
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// Close connection
mysqli_close($link);
} else{
// Check existence of id parameter before processing further
if(isset($_GET["id"]) && !empty(trim($_GET["id"]))){
// Get URL parameter
$id = trim($_GET["id"]);
// Prepare a select statement
$sql = "SELECT * FROM employees WHERE id = ?";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "i", $param_id);
// Set parameters
$param_id = $id;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
$result = mysqli_stmt_get_result($stmt);
if(mysqli_num_rows($result) == 1){
/* Fetch result row as an associative array. Since the result set
contains only one row, we don't need to use while loop */
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
// Retrieve individual field value
$name = $row["name"];
$address = $row["address"];
$salary = $row["salary"];
} else{
// URL doesn't contain valid id. Redirect to error page
header("location: error.php");
exit();
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
// Close connection
mysqli_close($link);
} else{
// URL doesn't contain id parameter. Redirect to error page
header("location: error.php");
exit();
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Update Record</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
.wrapper{
width: 600px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<h2 class="mt-5">Update Record</h2>
<p>Please edit the input values and submit to update the employee record.</p>
<form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control <?php echo (!empty($name_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $name; ?>">
<span class="invalid-feedback"><?php echo $name_err;?></span>
</div>
<div class="form-group">
<label>Address</label>
<textarea name="address" class="form-control <?php echo (!empty($address_err)) ? 'is-invalid' : ''; ?>"><?php echo $address; ?></textarea>
<span class="invalid-feedback"><?php echo $address_err;?></span>
</div>
<div class="form-group">
<label>Salary</label>
<input type="text" name="salary" class="form-control <?php echo (!empty($salary_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $salary; ?>">
<span class="invalid-feedback"><?php echo $salary_err;?></span>
</div>
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<input type="submit" class="btn btn-primary" value="Submit">
Cancel
</form>
</div>
</div>
</div>
</div>
</body>
</html>
delete.php
<?php
// Process delete operation after confirmation
if(isset($_POST["id"]) && !empty($_POST["id"])){
// Include config file
require_once "config.php";
// Prepare a delete statement
$sql = "DELETE FROM employees WHERE id = ?";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "i", $param_id);
// Set parameters
$param_id = trim($_POST["id"]);
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Records deleted successfully. Redirect to landing page
header("location: index.php");
exit();
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
// Close connection
mysqli_close($link);
} else{
// Check existence of id parameter
if(empty(trim($_GET["id"]))){
// URL doesn't contain id parameter. Redirect to error page
header("location: error.php");
exit();
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Delete Record</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
.wrapper{
width: 600px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<h2 class="mt-5 mb-3">Delete Record</h2>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="alert alert-danger">
<input type="hidden" name="id" value="<?php echo trim($_GET["id"]); ?>"/>
<p>Are you sure you want to delete this employee record?</p>
<p>
<input type="submit" value="Yes" class="btn btn-danger">
No
</p>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
error.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Error</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
.wrapper{
width: 600px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<h2 class="mt-5 mb-3">Invalid Request</h2>
<div class="alert alert-danger">Sorry, you've made an invalid request. Please go back and try again.</div>
</div>
</div>
</div>
</div>
</body>
</html>

can't send messages and $username isn't displayed

I made a chat service in php. When you get to the chat, it says "Welcome, --Username--." My problem is I added a login field, now I can't send messages and the username isn't displayed. I've looked everywhere but it seems since my code is so "unique", nothing seems to be helping. --i didn't make this all on my own, I used someone else's code for the login and someone's code for the service itself.
login.php
<?php
session_start();
echo isset($_SESSION['login']);
if(isset($_SESSION['login'])) {
header('LOCATION:admin.php'); die();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>Login</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h3 class="text-center">Login</h3>
<?php
if(isset($_POST['submit'])){
$username = $_POST['username']; $password = $_POST['password'];
if($username === 'admin' && $password === 'password'){
$_SESSION['login'] = true; header('LOCATION:admin.php'); die();
} {
echo "<div class='alert alert-danger'>Username and Password do not match.</div>";
}
if($username === 'admon' && $password === 'password'){
$_SESSION['login'] = true; header('LOCATION:admin.php'); die();
} {
echo "<div class='alert alert-danger'>Username and Password do not match.</div>";
}
}
?>
<form action="" method="post">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username" name="username" required>
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" name="password" required>
</div>
<button type="submit" name="submit" class="btn btn-default">Login</button>
</form>
</div>
</body>
</html>
admin.php
<?php
session_start();
if(!isset($_SESSION['login'])) {
header('LOCATION:login.php'); die();
}
if(isset($_GET['logout'])){
//Simple exit message
$logout_message = "<div class='msgln'><span class='left-info'>User <b class='user-name-left'>". $_SESSION['name'] ."</b> has left the chat session.</span><br></div>";
file_put_contents("log.html", $logout_message, FILE_APPEND | LOCK_EX);
session_destroy();
header("Location: login.php"); //Redirect the user
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>English Pricks</title>
<meta name="description" content="A Group Chat." />
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="wrapper">
<div id="menu">
<p class="welcome">Welcome, <b><?php echo $username['username']; ?></b>&period; Image Dump&period;&period;&period;</p>
<p>Emoji's โ†’ </p>
<button id="emoji-button" style="border: none;">๐Ÿ˜€</button>
<p class="logout"><a id="exit" href="#">Leave</a></p>
</div>
<div id="chatbox">
<?php
if(file_exists("log.html") && filesize("log.html") > 0){
$contents = file_get_contents("log.html");
echo $contents;
}
?>
</div>
<form name="message" action="">
<input name="usermsg" type="text" id="usermsg" style="outline: none;" spellcheck="true"/>
<input name="submitmsg" type="submit" id="submitmsg" value="โ†‘" />
</form>
</div>
<script type="text/javascript" src="./jquery.min.js"></script>
<script src="emoji.js"></script>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function () {
var picker = new EmojiButton();
var button = document.querySelector('#emoji-button');
button.addEventListener('click', function () {
picker.showPicker(button);
picker.on('emoji', emoji => {
document.querySelector('#usermsg').value += emoji;
});
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$("#submitmsg").click(function(){
var clientmsg = $.trim($("#usermsg").val());
if(clientmsg.length >= 1){ // Prevents Spamming the Enter Key
$.post("post.php", {text: clientmsg});
$("#usermsg").val("");
}else{
}
return false;
});
function loadLog() {
var oldscrollHeight = $("#chatbox")[0].scrollHeight - 20; //Scroll height before the request
$.ajax({
url: "log.html",
cache: false,
success: function (html) {
$("#chatbox").html(html); //Insert chat log into the #chatbox div
//Auto-scroll
var newscrollHeight = $("#chatbox")[0].scrollHeight - 20; //Scroll height after the request
if(newscrollHeight > oldscrollHeight){
$("#chatbox").animate({ scrollTop: newscrollHeight }, 'normal'); //Autoscroll to bottom of div
}
}
});
}
setInterval (loadLog, 1000);
$("#exit").click(function () {
var exit = confirm("Are you sure you want to leave?");
if (exit == true) {
window.location = "index.php?logout=true";
}
});
});
</script>
</body>
</html>
In login.php file else was missing in if blocks and in order to see username you should add it to $_SESSION in the same way as you did with
$_SESSION['login'], cause i don't see anything else which can serve as temp storage in provided code. Another issue is that you placed header() function with login and password check right inside html code. This will trigger warning on a runtime that headers were already sent. In order to avoid that place your checking code in the top of the file and also check if there are no spaces before or after <?php php opening tag.
Example of fixed login.php file you can find below.
<?php
session_start();
function setSessionData($name, $value) {
$_SESSION[$name] = $value;
}
function redirectWithData($username = '') {
setSessionData('login', true);
setSessionData('username', $username);
header('Location:admin.php');
die();
}
if(isset($_SESSION['login'])) {
header('Location:admin.php'); die();
}
if(isset($_POST['submit'])) {
$username = $_POST['username']; $password = $_POST['password'];
if($username === 'admin' && $password === 'password'){
redirectWithData($username);
} elseif($username === 'admon' && $password === 'password'){
redirectWithData($username);
} else {
echo "<div class='alert alert-danger'>Username and Password do not match.</div>";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>Login</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h3 class="text-center">Login</h3>
<form action="" method="post">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username" name="username" required>
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" name="password" required>
</div>
<button type="submit" name="submit" class="btn btn-default">Login</button>
</form>
</div>
</body>
</html>
On admin page you can then display username
Welcome, <b><?php echo $_SESSION['username']; ?>
Regarding admin.php functionality. Logic for adding messages according to JavaScript code located in post.php file.
$.post("post.php", {text: clientmsg});
So, why its adding or not adding it is hard to answer for obvious reasons )
And btw, in your logout logic in admin.php file change
window.location = "index.php?logout=true"; -> window.location = "?logout=true"; it will fallback to the same page on which you already have redirect logic.

ajax and php - my code is somehow duplicate the elements

i am new in ajax and i try to learn it.
i got this code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/js/bootstrap.bundle.min.js" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
<script>
$(document).ready(function(){
/**Add Ajax**/
$("#add-car-form").submit(function (evt) {
evt.preventDefault();//prevent form to be submitted as null
var postData=$(this).serialize();//get all the data from the form
var url=$(this).attr('action');//the url is the action attribute
$.post(url, postData, function(php_table_data){//send back the data from the url
$("#car-result").html(php_table_data);
});
});
});//End Document Ready
</script>
</head>
<body>
<div id="container" class="col-xs-6 col-xs-offset-3">
<div class="row">
<h2>Search our Database</h2>
<input class="form-control" type="text" name="search" id="search" placeholder="search our inventory">
<br>
<br>
<h2 class="bg-success" id="result"></h2>
</div>
<div class="row">
<form method="post" id="add-car-form" action="add_cars.php" class="col-xs-6">
<div class="form-group">
<input type="text" name="car_name" class="form-control">
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="add car">
</div>
</form>
<div class="col-xs-6">
<div id="car-result">
</div>
</div>
</div>
</div>
</body>
</html>
and i got the add_car.php
<?php
include "../db.php";
if(isset($_POST['car_name'])){
$car_name=$_POST['car_name'];
$query="INSERT INTO cars(cars) VALUES('{$car_name}')";
$query_car_name=mysqli_query($connection,$query);
if(!$query_car_name){
die("QUERY FAILED".mysqli_error($connection));
}
header("Location: index.html");
}
?>
now, when i click submit in the form the sql statemant is working but some how i got a dublicate form as a result
here is a picture before insert data:
enter image description here
and here is a result after insterting data:
enter image description here
In add_car.php
Change your code like this
<?php
include "../db.php";
if(isset($_POST['car_name'])){
$car_name=$_POST['car_name'];
$query="INSERT INTO cars(cars) VALUES('{$car_name}')";
$query_car_name=mysqli_query($connection,$query);
if(!$query_car_name){
die("QUERY FAILED".mysqli_error($connection));
}
$table="<table><thead><tr><th>ID</th><th>Car Name</th></tr></thead><tbody>";
$query="Select * From cars ORDER BY id DESC";
$result=mysqli_query($connection,$query);
if($result){
while($row = $result->fetch_assoc()) {
$table.="<tr><td>" . $row["id"]. "</td><td>" . $row["cars"]."</td></tr>";
}
}
$table.="</tbody></table>";
echo $table;
}
?>

Ajax call is inserting data on page in some other place

I am making use of ajax call to insert data in starting of my page. this is more like a wall post script. Whenever user posts something, the latest post is shown in the top of the posts page.
I am using JS, PHP and an HTML page.
here is my js code:
$(function() {
$("#tweet_submit").click(function()
{
var tweet = $("#tweet").val();
var x = $('.preview').attr('id');
if(x)
var z= x;
else
var z=0;
var dataString = 'tweet='+ tweet+ '&z=' +z;
if(tweet=='')
{
alert('Please type your tweet here');
}
else
{
alert('into post');
$.ajax({
type: "POST",
url: "WallPost/post_tweet1.php",
data: dataString,
cache: false,
success: function(html){
$("#tweet").val('');
$("#preview").hide();
$("#content").prepend(html);
}
});
}return false;
});
});
This is my PHP page:
post_tweet.php
<?php
include("includes/db.php");
include("session.php");
include_once 'includes/time_stamp.php';
//echo "request sent to post";
if($_POST)
{
$tweet=$_POST['tweet'];
$upload_id=$_POST['z'];
$time=time();
$query = "INSERT INTO tweets(tweet,time,upload_id,uid_fk) VALUES ('$tweet','$time','$upload_id','$uid')";
if (!mysqli_query($con,$query))
{
die('Error: ' . mysqli_error($con));
}
else
{
$msg ="<br> 1 record added";
}
echo "<br>".$msg;
$sql=mysqli_query($con,"select T.tid, T.tweet, T.time, T.upload_id, U.username, U.fullname, U.email FROM tweets T, users U WHERE T.uid_fk=U.uid and T.uid_fk='$uid' order by T.tid DESC LIMIT 1");
//$show_result=mysqli_query($sql);
while($row=mysqli_fetch_row($sql))
{
echo "data start here";
$tid= "$row[0]";
$tweet= "$row[1]";
$time = "$row[2]";
$img_id= "$row[3]";
$username="$row[4]";
$fullname = "$row[5]";
$email = "$row[6]";
$lowercase = strtolower($email);
$imagecode = md5( $lowercase );
$image_sql=mysqli_query($con,"select image_name from uploads where upload_id='$img_id'");
while($data=mysqli_fetch_row($image_sql))
{
$image_name="$data[0]";
$chars = 7;
$text = $image_name." ";
$text = substr($text,0,$chars);
$imgtext = "pic.twitter/".$text."...";
}
//echo "<div class='center'>";
echo "<div class='tweet_box' id='$tid'>";
echo "<div class='tweet_user'><img class='user_img' src='http://www.gravatar.com/avatar/$imagecode?s=50'></div>";
echo "<div class='tweet_body'>";
?>
<div class='tweet_time'><?php time_stamp($time);?></div>
<?php
echo "<div><b><a href='http://twitter.com/$username'>$fullname</a></b> <span class='uname'>#$username</span></div>";
echo "<div class='tweet_text'>$tweet ";
if($img_id!=0)
{
echo "<a href=''/>$imgtext</a></div>";
}
else
{
echo "</div>";
}
echo "<div class='tweet_options'><div class='first_option'><a href='#'>Expand</a> </div><div class='sub_options'> <a href='#'>Reply</a> <a href='#'>Retweet</a> <a href='#'>Favourite</a></div></div>";
if($img_id!=0)
{
?>
<div class="tweet_image" id="tweetimage<?php echo $tid; ?>">
<center><img src="uploads/<?php echo $image_name; ?>" class="image_show"/></center></div>
<?php
}
echo "</div></div>";
?>
<div class="tweet_reply_box" id="replybox<?php echo $tid;?>">
<div><textarea rel="<?php echo $tid;?>" id="replytext<?php echo $tid;?>" class="reply" name="reply"
maxlength="140">#<?php echo $username;?> </textarea></div>
<div class="reply_button_bar" id="replybutton<?php echo $tid;?>">
<div><input type="submit" value=" Reply " class="reply_btn" id="<?php echo $tid;?>"/></div>
</div>
</div>
<div id="reply_load<?php echo $tid;?>" class="reply_load">
</div>
<?php
}
}
else { }
?>
And this is my HTML page:
Wallpost.php
<!doctype html>
<html>
<head>
<title>Design Modo - Code-pal | eCommerce Website Template - Dead Stocker</title>
<link rel="shortcut icon" href="http://www.code-pal.com/wp-content/themes/codpeal-new/favicon.ico">
<link rel="stylesheet" type="text/css" href="css/check_style.css" />
<link rel="stylesheet" href="css/wallpost/wtfdiary.css">
<link rel="stylesheet" href="css/wallpost/tipsy_title.css">
<script type="text/javascript" src="WallPost/js/jquery.min.js"></script>
<script type="text/javascript" src="WallPost/js/jquery.tipsy.js"></script>
<script src="WallPost/js/twitter.js"></script>
<script type="text/javascript" src="WallPost/js/jquery.form.js"></script>
</head>
<body>
<div class="page-wrap">
<div class="clear"></div>
<?php include("header.php"); ?>
<div class="clear"></div>
<div class="body-contents">
<?php include("left-body1.php"); ?>
<div class="center">
<br>
<div class="txthead"><strong>Share thoughts here</strong></div>
<?php
include("WallPost/index.php");
?>
</div>
</div>
<?php include("right-body.php"); ?>
<div class="clear"></div>
</div>
<!-- eo .body-content -->
<?php include("footer.php"); ?>
</div><!-- eo .page-wrap-->
Here is the code where i post tweet:
index.php under WallPost folder:
<?php
include("includes/db.php");
include("session.php");
include("includes/time_stamp.php");
?>
<html>
<head>
<link rel="stylesheet" href="css/wtfdiary.css">
<link rel="stylesheet" href="css/tipsy_title.css">
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.tipsy.js"></script>
<script type="text/javascript" src="js/twitter.js"></script>
<script type="text/javascript" src="js/jquery.form.js"></script>
</head>
<body>
<div id="container">
<div id="sidebar_container">
<div id="sidebar">
<div id='logo'><img src='images/1.png'></div>
<div id="box">
<div><textarea id="tweet" name="tweet" placeholder="Compose new Tweet..."></textarea></div>
<div id='preview'></div>
<div id="button_bar">
<div id="icons">
<div class="filebutton" title="Image Upload">
<form id="imageform" method="post" enctype="multipart/form-data" action='ajax_image.php'>
<span><input type="file" name="photoimg" id="photoimg"/></span>
</form>
</div>
</div>
<div><input type="submit" value=" Tweet " class="btn" id="tweet_submit"/></div>
</div>
</div>
</div>
</div>
<!-- <div id="main"> -->
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div id='heading'>Tweets</div>
<div id='content'>
<?php include("loads_tweets1.php");?>
<!-- </div> -->
</div>
</div>
</body>
</html>
So after i make use of all these code, Post is shown in my page, but the way it is shown is not correct.
The post is inserted at some random place. (I couldn't attach image due to less reputation)
Can someone please tell what is going wrong, and i am not able to get this data in correct place where my other posts are listed.
Thanks in advance!!!
Your input helped me and i was able to solve it. Content was being called at two places, and ajax inserted the data on first location and i was not getting it placed where i needed it.
Thanks.

ajax code200 error can't connect to the url

I am using ajax to run a test id, but it does not work with code: 200 error.
And since ajax is not returning a value, it keeps getting error and prints "failed"
The id of add_user.html is checked in real time through the ajax of id_check.js.
However, memid_check.php, which sends data from id_check.js, does not seem to run.
to confirm
memid_check.php
echo "<script> alert('test!!!'); </script>";
.....
But did not run.
All files are in one folder, so the path seems to be fine
id_check.js
$(function(){
var id = $('.id_tbox');
var pwd =$('.pwd_tbox');
var name =$('.name_tbox');
var email =$('.email_tbox');
var idCheck = $('.idCheck');
$(".memcheck_button").click(function(){
console.log(id.val());
$.ajax({
type: 'post',
dataType: 'json',
url: "memid_check.php",
data:{id:id.val()},
success: function(json){
if(json.res == 'good'){
console.log(json.res);
alert("์‚ฌ์šฉ๊ฐ€๋Šฅํ•œ ์•„์ด๋””");
idCheck.val('1');
}
else{
alert("๋‹ค๋ฅธ ์•„์ด๋”” ์ž…๋ ฅ");
id.focus();
}
},
error:function(request,status,error){
alert("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error);
console.log("failed");
}
});
});
});
memid_check.php
<?php
echo "<script> alert('test!!!'); </script>";
include "db_c.php";
$id = $_POST['id'];
$sql = "SELECT * FROM add_user WHERE id = '{$id}'";
$res = $database -> query($sql);
if( res->num_rows >= 1){
echo json_encode(array('res'=>'bad'));
}
else{
echo json_encode(array('res'=>'good'));
}
?>
add_user.html
<?php
include "database.php";
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, target-densitydpi=medium-dpi">
<link rel="stylesheet" href="add_user_style.css">
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="js/default.js"></script>
<link href="https://fonts.googleapis.com/css?family=Nothing+You+Could+Do&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Cinzel|Permanent+Marker|Rajdhani&display=swap" rel="stylesheet">
<script type="text/javascript" src="id_check.js"></script>
</head>
<body>
<div class="aus_portrait"></div>
<div class ="aus_form" align ="center">
<div class="aus_box">Sign Up</div>
<form action="loginP.php" method="post">
<p class = "id">ID</p><input type="text" name="id" class="id_tbox">
<p class = "pwd">PASSWORD</p><input type="text" name="pwd" class="pwd_tbox">
<p class = "name">MAIL</p><input type="text" name="email" class="email_tbox">
<p class = "email">NAME</p><input type="text" name="name" class="name_tbox">
<input type="submit" class="sub_button" value="Submit">
<input type="button" class="exit_button" value="Cancel">
<input type="hidden" name="idCheck" class="idCheck">
<div class="memcheck_button">์ค‘๋ณตํ™•์ธ</div>
</form>
</div>
</body>
</html>
<script>
$(document).ready(function() { $(".exit_button").on("click", function(){ location.href="login.html"});}); </script>

Categories