refresh on ajax shoutbox input - php

Hello I have been building a shout box and i am so close - i just cant get the fetched data to refresh on input.
the fetched data refreshes on interval but when i press submit i have to wait for it to refresh by that interval i would like it to be instant on submit
sql
CREATE TABLE IF NOT EXISTS `shoutbox` (
`msgid` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`message` text DEFAULT NULL,
PRIMARY KEY (`msgid`)
) ENGINE=MyISAM;
index.php
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap 5 Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<p id="shoutbox"></p>
<form id='contactForm1' name='contactForm1' action='postshout.php' method='post'>
<div class="row">
<div class="col-md-12">
<input id="message" class="form-control shoutbox_msgbox" type='text' size='100%' name="message">
</div>
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
var frm = $('#contactForm1');
frm.submit(function (e) {
e.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
console.log('Submission was successful.');
console.log(data);
},
complete: function(){
$("#message").focus().val('');
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
});
});
</script>
<script>
function updateShouts(){
// always refresh #shoutbox
$('#shoutbox').load('getshout.php');
}
setInterval( "updateShouts()", 15000 );
updateShouts();
</script>
</body>
</html>
getshout.php
<?php
$servername = "localhost";
$username = "dbusername";
$password = "dbpassword";
try {
$conn = new PDO("mysql:host=$servername;dbname=dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$sth = $conn->prepare("SELECT * FROM shoutbox ORDER BY `msgid` DESC");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
$result = $sth->fetchAll();
foreach ($result as $row) {
echo "$row[message]<br>";
}
postshout.php
<?php
$servername = "localhost";
$username = "dbusername";
$password = "dbpassword";
try {
$conn = new PDO("mysql:host=$servername;dbname=dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$data = [
'message' => $_POST['message'],
];
$sql = "INSERT INTO shoutbox (message) VALUES (:message)";
$stmt= $conn->prepare($sql);
$stmt->execute($data);

Related

Why header('location: ') is not working in php using ajax but session is working? [duplicate]

This question already has an answer here:
Redirect after POST using the Location header with jQuery
(1 answer)
Closed 2 years ago.
I am using ajax to post in the login part and create session. the session is working but in there header('location: chat.php') is not working(not redirected). while I am trying to log in session is created but not redirected to chat.php. I checked jQuery and ajax is working and successful to create a session and log in but not redirected to chat.php. Can any help me plz
jQuery('.userlogin').submit(function(){
var email = jQuery("input[name='email_address']").val();
var password = jQuery("input[name='password']").val();
$.ajax({
'url' : 'login.php',
'type' : 'POST',
'data' : {
'loginajax' : '',
'email' : email,
'password' : password
},
'success' : function(output){
jQuery('.ama-input').val('');
}
});
});
<?php
session_start();
require_once('functions.php');
if(isset($_POST['loginajax'])){
$email=$_POST['email'];
$password=$_POST['password'];
$query = mysqli_query($connection, "SELECT * FROM users WHERE email='$email'");
$info = mysqli_fetch_assoc($query);
$pass= $info['password'];
if($pass==md5($password)){
$_SESSION['login'] = "successful";
header('location: chat.php');
}
die();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Log In</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="box">
<h2 class="heading">Log In</h2>
<form action="" method="POST" class="userlogin">
<input class="ama-input" type="email" name="email_address" placeholder="Email Address" />
<input class="ama-input" type="password" name="password" placeholder="Password" />
<input type="submit" name="login" value="Log In" />
</form>
<a class="registration" href="register.php">Create an account</a><br />
</div>
<script src="js/jquery-3.5.1.min.js"></script>
<script src="js/script.js"></script>
</body>
</html>
PHP redirection won’t work because you are making a ajax call.
Try returning the result and redirect from your script like this.
$(function () {
jQuery('.userlogin').submit(function(e){
e.preventDefault();
var email = jQuery("input[name='email_address']").val();
var password = jQuery("input[name='password']").val();
$.ajax({
'url': 'login.php',
'type': 'POST',
'data': {
'loginajax': '',
'email': email,
'password': password
},
'success': function (output) {
console.log(output);
if (output.status == 'success') {
window.location.href = "your url here";//<- your url here
}
}
});
});
});
Your PHP code should look something like this:
<?php
session_start();
require_once 'functions.php';
if (filter_input(INPUT_POST, 'loginajax')) {
$result['status'] = 'unsuccessful';
$result['message'] = 'login unsuccessful.';
$email = filter_input(INPUT_POST, 'email_address');
$password = filter_input(INPUT_POST, 'password');
$sql = "SELECT id,email,password FROM users WHERE email=?";
$stmt = mysqli_prepare($connection, $sql);
mysqli_stmt_bind_param($stmt, "s", $email);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password);
if (mysqli_stmt_fetch($stmt)) {
if (password_verify($password, $hashed_password)) {
$_SESSION['login'] = "successful";
$result['status'] = "success";
$result['message'] = "login successful.";
}
}
mysqli_stmt_close($stmt);
header('Content-Type: application/json'); // <-- header declaration
echo json_encode($result, true);
}

if isset with multiple variables when submitting form

I made this typical form which shows a fade in message when submitting it! It works perfectly with up to 2 variables, but when i'm trying to change my code and insert a third variable or more a problem comes up when submitting.
The html code is:
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Basic Form</title>
<meta name="description" content="A basic fade in form">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<head>
<title>Enable Disable Submit Button Based on Validation</title>
<style>
body{width:50%;min-width:200px;font-family:arial;}
#frmDemo {background: #98E6DB;padding: 40px;overflow:auto;}
#btn-submit{padding: 10px 20px;background: #555;border: 0;color: #FFF;display:inline-block;margin-top:20px;cursor: pointer;font-size: medium;}
#btn-submit:focus{outline:none;}
.input-control{padding:10px;width:100%;}
.input-group{margin-top:10px;}
#error_message{
background: #F3A6A6;
}
#success_message{
background: #CCF5CC;
}
.ajax_response {
padding: 10px 20px;
border: 0;
display: inline-block;
margin-top: 20px;
cursor: pointer;
display:none;
color:#555;
}
</style>
</head>
<body>
<h1>jQuery Fade Out Message after Form Submit</h1>
<form id="frmDemo" action="post-form.php" method="post">
<div class="input-group">Name </div>
<div>
<input type="text" name="name" id="name" class="input-control" />
</div>
<div class="input-group">Message </div>
<div>
<textarea name="comment" id="comment" class="input-control"></textarea>
</div>
<div class="input-group">Lastname </div>
<div>
<input type="text" name="lastname" id="lastname" class="input-control" />
</div>
<div style="float:left">
<button type="submit" name="btn-submit" id="btn-submit">Submit</button>
</div>
<div id="error_message" class="ajax_response" style="float:left"></div>
<div id="success_message" class="ajax_response" style="float:left"></div>
</form>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$("#frmDemo").submit(function(e) {
e.preventDefault();
var name = $("#name").val();
var comment = $("#comment").val();
var lastname = $("#lastname").val();
if(name == "" || comment == "" || lastname == "" ) {
$("#error_message").show().html("All Fields are Required");
} else {
$("#error_message").html("").hide();
$.ajax({
type: "POST",
url: "form4.php",
data: { name:name, comment:comment, lastname:lastname }, // *** Modify this
success: function(data){
$('#success_message').fadeIn().html(data);
setTimeout(function() {
$('#success_message').fadeOut("slow");
}, 2000 );
}
});
}
})
</script>
</body>
</html>
and the php code is:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "form4";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['name']) && isset($_POST['comment']) && isset($_POST['lastname'])) { // **Change this
$name = $_POST['name'];
$comment = $_POST['comment'];
$lastname = $_POST['lastname'];
$sql = "INSERT INTO step4 (name, comment, lastname) VALUES ('{$name}', '{$comment}' '{$lastname}')";
if ($conn->query($sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
} else {
echo "Either Name or Comment field not set"; // **Change this
}
$conn->close();
?>
I suppose that the problem has to do with some error in my php code in the if isset POST method, because it can handle 2 variables but no more...
You muss a comma in SQL query - but, if You setup default values in database, it will not throw an error.
I think, the problem is in JSON object in 'data' field in AJAX options.
Try to change syntax:
$.ajax({
type: "POST",
url: "form4.php",
data: "name="+name+"&comment="+comment+"&lastname="+lastname,
success: function(data){
$('#success_message').fadeIn().html(data);
setTimeout(function() {
$('#success_message').fadeOut("slow");
}, 2000 );
}
});
You have syntax in your query, you forgot about comma:
$sql = "INSERT INTO step4 (name, comment, lastname) VALUES ('{$name}', '{$comment}' '{$lastname}')";
between '{$comment}' '{$lastname}'.
Put it there as follows:
{$comment}', '{$lastname}
so your code should look as follows:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "form4";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['name']) && isset($_POST['comment']) && isset($_POST['lastname'])) { // **Change this
$name = $_POST['name'];
$comment = $_POST['comment'];
$lastname = $_POST['lastname'];
$sql = "INSERT INTO step4 (name, comment, lastname) VALUES ('{$name}', '{$comment}', '{$lastname}')"; // here the problem occurs
if ($conn->query($sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
} else {
echo "Either Name or Comment field not set"; // **Change this
}
$conn->close();
?>
In error you can look inside your query:
Error: INSERT INTO step4 (name, comment, lastname) VALUES ('aths',
'as' 'asa') Column count doesn't match value count at row 1
which says your query doesn't have comma between values as and asa

autocomplete jquery does not return expected results

I am developing a simple jquery autocomplete using php. It works just fine for the most part... but when I do certain searches, it does not detect specific entries. For example, when I search for "Si" I get a list including "Simon", but when I search for "Jo" there is nothing.
Here are the two files I have:
index.php
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Search</title>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/themes/base/minified/jquery-ui.min.css" type="text/css" />
</head>
<body>
<form action='' method='post'>
<p><label>Name:</label><input type='text' name='Name' value='' class='auto'></p>
</form>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript">
$(function() {
//autocomplete
$(".auto").autocomplete({
source: "search.php",
minLength: 2
});
});
</script>
</body>
</html>
search.php
<?php
define('DB_SERVER', 'localhost');
define('DB_USER', 'xxx');
define('DB_PASSWORD', 'xxx');
define('DB_NAME', 'xxx');
if (isset($_GET['term'])){
$return_arr = array();
try {
$conn = new PDO("mysql:host=".DB_SERVER.";port=8889;dbname=".DB_NAME, DB_USER, DB_PASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT Name FROM People WHERE Name LIKE :term');
$stmt->execute(array('term' => '%'.$_GET['term'].'%'));
while($row = $stmt->fetch()) {
$return_arr[] = $row['Name'];
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
/* Return results as json encoded array. */
echo json_encode($return_arr);
}
?>
Might this have something to do with an exception list? Or have I made an error with the code?
As a newbie I am in awe of the great help from this site!

Need help to compare and add value to DB with PHP, $_POST not working..?

I am trying to compare the text that is written in the input field with the "UserID" in the database to know where to add 1 pts on the button click. Adding a new user to the DB is not a problem, but then when I want to "UPDATE" the DB nothing happends, it seems like I cant get the $_POST['UserID']; to work in my addPts.php ?
Here is an example from my code:
blabla.html
<html>
<head>
<script type="text/javascript" src="blabla.js"></script>
</head>
<body>
<nav>
<li>
<form action="addToDB.php" method="post" target="hidden-form">
<input type="text" id="UserID" name="UserID" placeholder="Your ID Here" style="width:290px"/>
<input type="submit" id="submit" name="submit" value="Add to DB"/>
</form>
</li>
</nav>
<section id="mainframe">
<iframe src="blabla2.html" name="myIFRAME"></iframe>
</section>
<iframe style="display:none" name="hidden-form"></iframe>
<button><a id="theLink" href="http://www.stackoverflow.com" target="myIFRAME">Press me for 1pts</a></button>
</body>
</html>
blabla2.html
<html>
<head>
</head>
<body>
Start message in iFrame
</body>
</html>
blabla.js
$(function (){
$('#theLink').click(function(){
var request = $.ajax({
type: "POST",
url: "../bla/addPts.php"
});
request.done(function( msg ) {
alert('1 Point added');
return;
});
request.fail(function() {
alert( "Request failed.. " );
});
});
});
addToDB.php
<?php
$localhost = "localhost";
$dbuser = "blabla";
$dbpass = "blablabla";
$dbname = "bla";
$connect = mysql_connect($localhost, $dbuser, $dbpass);
mysql_select_db("$dbname", $connect);
$UserID = $_POST['UserID'];
$checkIDLenght = strlen($UserID);
$messageNewMember = "WELCOME! New User!";
$messageOldMember = "Welcome back!";
$insert = 'INSERT into membersBLA(UserID) VALUES("'.$UserID.'")';
$query = mysql_query("SELECT UserID FROM membersBLA WHERE UserID='".$UserID."'");
if (mysql_num_rows($query) != 0)
{
echo "<script type='text/javascript'>alert('$messageOldMember');</script>";
}
else {
mysql_query($insert);
echo "<script type='text/javascript'>alert('$messageNewMember');</script>";
}
?>
addPts.php
<?php
$localhost = "localhost";
$dbuser = "blabla";
$dbpass = "blablabla";
$dbname = "bla";
$connect = mysql_connect($localhost, $dbuser, $dbpass);
mysql_select_db("$dbname", $connect);
$user = $_POST['UserID'];
mysql_query("UPDATE membersBLA SET UserPts = UserPts + 1 WHERE UserID='".$user."'");
?>
It works to "UPDATE" the DB if I type in the " WHERE UserID='Name'"); " manually, then it update the "UserPts" for the name I wrote.. but Getting the typed name from the input to compare does not seems to work?
Try this
//Retrieve value of userid and use data paremeter of jQuery.ajax()
$(function (){
$('#theLink').click(function(){
var UserID=jQuery("#UserID").val();
var request = $.ajax({
type: "POST",
url: "../bla/addPts.php",
data:{'UserID': UserID},
});
request.done(function( msg ) {
alert('1 Point added');
return;
});
request.fail(function() {
alert( "Request failed.. " );
});
});
});

Attempting to write a livesearch script

I am attempting a bit of ajax for the first time. I'm trying to write a live search where on every character entered a search of a MySQL database is run.
This is my code so far:
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<script type="text/javascript">
function getStates(value){
$.post(
"getstates.php",
{partialState:value},
function(data){
$("#results").html(data);
});
}
</script>
</head>
<body>
<input type="text" name="input" onkeyup="getStates(this.value)" /><br />
<div id="results"></div>
</body>
</html>
getStates.php
//test the connection
try{
//connect to the database
$dbh = new PDO("mysql:host=127.0.0.1;dbname=livesearch","root", "usbw");
//if there is an error catch it here
} catch( PDOException $e ) {
//display the error
echo $e->getMessage();
}
$partialState = $_POST['partialState'];
$query = $dbh->prepare("SELECT state_name FROM tbl_state WHERE state_name LIKE '%$partialSate%'");
$query->execute();
$result = $query->fetchAll();
foreach($result AS $state){
echo '<div>'.$state['state_name'].'</div>';
}
The mySQL database is constructed correctly using the correct table names etc.
Why is it not returning the resulting states from the database?
The problem is that you have made a typo in your query:
$query = $dbh->prepare("SELECT state_name
FROM tbl_state
WHERE state_name
LIKE '%$partialSate%'");
^^^^Missing t
Should be
$query = $dbh->prepare("SELECT state_name
FROM tbl_state
WHERE state_name
LIKE '%$partialState%'");
But you should also use prepared query's correctly:
Fixed code:
<?php
if(isset($_POST['partialState'])){
//test the connection
try{
//connect to the database
$dbh = new PDO("mysql:host=127.0.0.1;dbname=livesearch","root", "usbw");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
//if there is an error catch it here
} catch( PDOException $e ) {
//display the error
echo $e->getMessage();
}
$query = $dbh->prepare("SELECT state_name
FROM tbl_state
WHERE state_name
LIKE :like");
$query->execute(array(':like'=>'%'.$_POST['partialState'].'%'));
$result = $query->fetchAll();
foreach($result AS $state){
echo '<div>'.$state['state_name'].'</div>';
}
die();
}
?>
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
function getStates(value){
$.post("index.php", { "partialState":value },
function(data){
$("#results").html(data);
});
}
</script>
</head>
<body>
<input type="text" name="input" onkeyup="getStates(this.value)" /><br />
<div id="results"></div>
</body>
</html>

Categories