I have tried many ways to build a commenting system for my website with php jquery,ajax but problem with inserting comments in data base what is the problem with my code
Html
<div id="comments" class="cmt">
<form method="post" >
<textarea class="textinput"id="comment" rows="5" name="comments" placeholder="Comment Here......"></textarea><br>
<button type="button" id="comq"name="compost" class="butn2" >post comment</button>
</form>
</div>
Jquery and ajax
$(document).ready(function()
{
$("#comq").click(function() {
var comment=$("#comment").val();
$.ajax({
cache:false,
type:"post",
url:"pnf.php",
data:{comments:comment},
success:function(data)
{
$('.cmt').html(data);
}
});
});
});
Php (pnf.php)
if(isset($_POST["compost"])){
$comment=$_POST['comments'];
{
$reslt_user= mysqli_query($connection,"SELECT * FROM tbl_users,`queries` where id='".$_SESSION['id']."' AND qid= '".$qid."' ");
$row_lat_lng= mysqli_fetch_array($reslt_user);
$stmt = mysqli_query($connection,"INSERT INTO comments set uid='".$_SESSION['id']."',comments='".$comment."',reply='".$reply."' ,
qid= '".$qid."' ");
}
if($stmt)
{
echo "hello world";
}
}
Try this:
HTML
<div id="comments" class="cmt">
<textarea class="textinput" id="comment" rows="5" name="comments" placeholder="Comment Here......"></textarea><br>
<button type="button" id="comq"name="compost" class="butn2" >post comment</button>
</div>
For PHP:
if(isset($_POST["comments"])){
$comment = $_POST['comments'];
$reslt_user= mysqli_query($connection,"SELECT * FROM tbl_users,`queries` where id='".$_SESSION['id']."' AND qid= '".$qid."' ");
$row_lat_lng= mysqli_fetch_array($reslt_user);
$stmt = mysqli_query($connection,"INSERT INTO comments set
uid='".$_SESSION['id']."',comments='".$comment."',reply='".$reply."' ,
qid= '".$qid."' ");
if($stmt)
{
echo "hello world";
}
}
You have an error in type:
if(isset($_POST["compost"])){
$comment=$_POST['comments'];
I mean $_POST["compost"] and $_POST["compost"] are different variables
first just isset the $_POST Comment to check if you have you comment value
if(isset($_POST["comments"])){
$comment=$_POST['comments'];
$reslt_user= mysqli_query($connection,"SELECT * FROM tbl_users,`queries` where id='".$_SESSION['id']."' AND qid= '".$qid."' ");
$row_lat_lng= mysqli_fetch_array($reslt_user);
$stmt = mysqli_query($connection,"INSERT INTO comments set uid='".$_SESSION['id']."',comments='".$comment."',reply='".$reply."' ,qid= '".$qid."' ");
if($stmt)
{
return true;
}
}
second you can id to your form to reset after the ajax call success
<form id="myForm"> // add ID to your form
success:function(data){
if(data == true){
$('#myForm')[0].reset(); //to reset your form after success
$('.cmt').html(data);
} else{
//do the error msg
}
}
I'm sharing working code snippets.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js" ></script>
</head>
<body>
<div id="comments" class="cmt">
<form method="post" onsubmit="submitComment(); return false;">
<textarea class="textinput" id="comment" rows="5" name="comments" placeholder="Comment Here......"></textarea><br>
<button type="submit" id="comq"name="compost" class="butn2" >post comment</button>
</form>
<p id="message" ></p>
</div>
<script>
function submitComment() {
var comment = $("#comment").val();
$.ajax({
cache: false,
type: "post",
url: "pnf.php",
data:{
comment:comment
},
success:function(data) {
$('#message').html(data);
}
});
return false;
}
</script>
</body>
</html>
and PHP script
<?php
$connection = mysqli_connect("localhost","my_user","my_password","my_db");
if(mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST["comment"])) {
$comment = mysqli_real_escape_string($connection, $_POST['comment']);
$sql = "INSERT INTO `comments` (`comment`) VALUES ('".$comment."')";
$res = mysqli_query($connection, $sql);
if($res) {
echo "success";
} else {
echo "error";
}
}
Related
I have textarea with save and cancel buttons for updating textarea text in mysql DB.
Initially my MYSQL db
ID text
1 NULL
If i enter some text in textarea i'm updating my mysql db text with entered value currently i'm able to achieve it but my requirment is once i entered text in textarea it should update my db and that text value should display with EDIT and DELETE buttons.
on clicking EDIT button it should open up textarea with save and cancel buttons. can somebody aid me out how to achieve it Thanks!
http://jsfiddle.net/a32yjx0k/
HTML
<div id="b_news">
<form method="post" action="">
</div>
<div class="breaking_news_content">
<div>
<form method="post" action="">
<div>
<div>
<textarea id="breaking_news_text" class="breaking_news_text" rows="6" cols="50" placeholder="Add text here..." required></textarea>
</div>
</div>
<div>
<input type="submit" class=" save_breaking_news" value="Save Changes"/>
<input type="submit" value="Cancel" class=" breaking_news_cancel">
</div>
</form>
</div>
</div>
</form>
</div>
JQUERY
$(function(){
$(".save_breaking_news").click(function(){
var textcontent = $('.breaking_news_text').val();
if(textcontent == '')
{
alert("Enter Some Text...");
$('.breaking_news_text').focus();
}
else
{
$.ajax({
type: "POST",
url: "index.php",
data:{
textcontent:textcontent
},
success:function(response){
alert('breaking news successfully updated');
}
});
}
return false;
});
});
PHP
<?php
if(isset($_POST['textcontent']))
{
$breaking_news = mysqli_real_escape_string($con, $_POST['textcontent']);
$sql = "update breakingnews set text='".$breaking_news."'";
$result = mysqli_query($con, $sql);
}
?>
$(function(){
$(".save_breaking_news").click(function(){
var textcontent = $('.breaking_news_text').text();
if(textcontent == '')
{
alert("Enter Some Text...");
$('.breaking_news_text').focus();
}
else
{
$.ajax({
type: "POST",
url: "index.php",
data:{
textcontent:textcontent
},
success:function(response){
alert('breaking news successfully updated');
}
});
}
return false;
});
});
To get textbox use (class/id).text();
Your DIV
<div id="b_news">
<form method="post" action="">
</div>
<div class="breaking_news_content">
<div>
<form method="post" action="">
<div>
<div>
<textarea id="breaking_news_text" class="breaking_news_text" rows="6" cols="50" placeholder="Add text here..." required></textarea>
</div>
</div>
<div>
<input type="hidden" id="post_ID" value="2"/>
<input type="button" class=" save_breaking_news" value="Save Changes"/>
<input type="button" value="Cancel" class=" breaking_news_cancel">
</div>
</form>
</div>
</div>
</form>
</div>
YOUR SCRIPT SHOULD BE LIKE THIS
$(function(){
$(".save_breaking_news").click(function(){
var textcontent = $('.breaking_news_text').text();
if(textcontent == '')
{
alert("Enter Some Text...");
$('.breaking_news_text').focus();
}
else
{
var postID=$("#post_ID").val();
$.ajax({
url: 'index.php',
type: 'post',
data: 'textcontent=' + drvNo+"id="+postID,
success:function(response){
alert('breaking news successfully updated');
}
});
}
return false;
});
});
YOUR PHP CODE FOR UPDATE
<?php
if(isset($_POST['textcontent']))
{
$breaking_news = mysqli_real_escape_string($con, $_POST['textcontent']);
$sql = "update breakingnews set text='".$breaking_news."' Where id='".$_POST['id']."'";
$result = mysqli_query($con, $sql);
}
?>
AND IF YOU WANT TO INSERT POST YOUR CODE SHOULD BE LIKE THIS:
<?php
if(isset($_POST['textcontent']) && !isset($_POST['id']))
{
$breaking_news = mysqli_real_escape_string($con, $_POST['textcontent']);
$sql = "insert into <TBL NAME> `text` values ('".$_POST['textcontent']."')";
$result = mysqli_query($con, $sql);
}
?>
Your code everything is fine. Instead of calling function use .keyup() function in Jquery.
$("#breaking_news_text").keyup(function(){
var textcontent = $('.breaking_news_text').val();
if(textcontent == '')
{
alert("Enter Some Text...");
$('.breaking_news_text').focus();
}
else
{
alert(textcontent);
$.ajax({
type: "POST",
url: "index.php",
data:
{
textcontent:textcontent
},
success:function(response)
{
alert('breaking news successfully updated');
}
});
}
return false;
});
and when you going to cancel please use input type="reset"
<input type="reset" value="Cancel" class=" breaking_news_cancel">
I'm a newbie in the world of php and I was trying to learn it with a simple page.
I've created an html form and I want to send data using ajax but it still
POST http://localhost/Home.php 500 (Internal Server Error)
In particular I want to create a button for every table in a database which I'm using for testing, when I push a button it will show all lines from the database (I've not implemented it yet, I'm only trying to understend how php and ajax communicate)
This is my form (Home.php)
<?php
session_start();
if(!isset($_SESSION['login'])) {
header("Location: Login.php");
unset($_REQUEST);
}
else echo "<span class=\"welcome\"><strong>Benvenuto</strong> <em>" . $_SESSION['username'] . "</em></span>";
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src='jquery-1.11.3.js'></script>
<script src='Script.js'></script>
</head>
<body>
<div id="functions">
<button id="createTable">CREATE</button>
<button id="displayTable">DISPLAY</button>
</div>
<div id="createForm">
<form id="queryForm" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input class ="text" name="query" type="text" size="50">
<input type="submit" class="submit" name="createQuery">
</form>
</div>
<div id="displayForm">
<form method="post" id="selectForm">
<?php
include ("Database.php");
$Database = new Database( "localhost", "root", "1234");
$Database->connectToServer();
$Database->connectToDatabase("test");
$Tables = $Database->countTable();
foreach($Tables as $column) {
echo "<input type=\"radio\" class=\"submit\" id=\"selectQuery\" name=\"selectQuery\" value=\"". $column . "\"> " . $column;
}
?>
<input type="submit" class="submit" name="createSelect">
</div>
<div style="position:absolute; bottom:10px; left:50%; font-size: 15pt"></span><em>...</em> Logout</div>
</body>
</html>
<?php
if(isset($_POST['createQuery'])) {
include ("Database.php");
$Database = new Database( "localhost", "root", "1234");
$Database->connectToServer();
$Database->connectToDatabase("test");
$Database->createTable($_POST["query"]);
header("Location:Home.php");
}
?>
And this is my ajax file
$(document).ready(
function() {
$("#createTable").click(goCreate);
$("#displayTable").click(goDisplay);
$('#selectForm').submit(goSelect);
$("#createForm").hide();
$("#displayForm").hide();
}
);
function goCreate(data) {
$("#createForm").show();
$("#functions").hide();
}
function goDisplay(data) {
$("#displayForm").show();
$("#functions").hide();
}
function goSelect() {
var selectedTable = $("#selectQuery:checked").val();
console.log($("#selectQuery:checked").val());
$.ajax({
url: "Prova.php",
type: "POST",
dataType: "html",
data: {
'select': 'display',
'table': selectedTable
},
success: function(msg) {
console.log(msg);
},
error: function(xhr, desc, err) {
console.log("error");
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
}); // end ajax call
return false;
};
And this is Prova.php where I managed ajax call
<?php
include 'ChromePhp.php';
ChromePhp::log("corretto");
echo "ok belo";
?>
I have a code here of inserting and displaying record without refreshing web page using ajax and plain php but I don't know how to set this up using codeigniter. Please help. Here are the codes
inserting.php
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js">
</script>
<script type="text/javascript" >
$(function() {
$(".comment_button").click(function() {
var test = $("#content").val();
var dataString = 'content='+ test;
if(test=='')
{
alert("Please Enter Some Text");
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="ajax-loader.gif" align="absmiddle">
<span class="loading">Loading Comment...</span>');
$.ajax({
type: "POST",
url: "demo_insert.php",
data: dataString,
cache: false,
success: function(html){
$("#display").after(html);
document.getElementById('content').value='';
document.getElementById('content').focus();
$("#flash").hide();
}
});
} return false;
});
});
</script>
// HTML code
<div>
<form method="post" name="form" action="">
<h3>What are you doing?</h3>
<textarea cols="30" rows="2" name="content" id="content" maxlength="145" >
</textarea><br />
<input type="submit" value="Update" name="submit" class="comment_button"/>
</form>
</div>
<div id="flash"></div>
<div id="display"></div>
demo_insert.php
PHP Code display recently inserted record from the database.
<?php
include('db.php');
if(isSet($_POST['content']))
{
$content=$_POST['content'];
mysql_query("insert into messages(msg) values ('$content')");
$sql_in= mysql_query("SELECT msg,msg_id FROM messages order by msg_id desc");
$r=mysql_fetch_array($sql_in);
}
?>
<b><?php echo $r['msg']; ?></b>
In your wellcome controller you can add the following:
public function inserting()
{
$this->load->view('inserting');
}
public function process()
{
$content=$this->input->post('content');
if($this->db->insert('mytable', array('msg' => $content))){
echo "<b>{$content}</b>";
}
You should then use inserting.php as your view, in application/views, and the ajax url would be /process.
Didn't test it, but this should do the trick. Also, you should check this example http://runnable.com/UXczcazDrMMiAAGl/how-to-do-ajax-in-codeigniter-for-php
As shown from the diagram, I have two tables in my mysql and I would like the system to add and retrieve comment without refreshing the page.
I have three php pages involved in this function and they are 'DB.php', 'comment.php' and 'action.php'
The codes are as shown:
DB.php
<?php
$conn = mysql_connect('localhost','Practical4','1234') or die (mysql_error);
$db=mysql_select_db('Practical4', $conn) or die (mysql_error);
?>
comment.php
<----------------ajax script-------------------->
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".submit_button").click(function() {
var textcontent = $("#content").val();
var dataString = 'content='+ textcontent;
if(textcontent=='')
{
alert("Enter some text..");
$("#content").focus();
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
$.ajax({
type: "POST",
url: "action.php",
data: dataString,
cache: true,
success: function(html){
$("#show").after(html);
document.getElementById('content').value='';
$("#flash").hide();
$("#content").focus();
}
});
}
return false;
});
});
</script>
<div>
<-----retrieve hotel id from hotel table-------->
<?php
$conn=mysqli_connect('localhost','Practical4','1234') or die('Not connected');
$database=mysqli_select_db($conn,'Practical4') or die('Database Not connected');
$id=$_GET['id'];
$query = "select * from hotel where name='$id'";
$data=mysqli_query($conn,$query);
while($rows=mysqli_fetch_array($data)){
$name=$rows['name'];
$price=$rows['price'];
$duetime=$rows['dueTime'];
$address=$rows['location'];
}
?>
<---------------post form------------------->
<form method="post" name="form" action="">
<h3>Add Comment for <?php echo $name;?><h3>
<input type="text" name="name" id="name" value="<?php echo $name;?>" hidden > <br>
<textarea cols="30" rows="2" name="content" id="content" maxlength="145" >
</textarea><br />
<input type="submit" value="Post" name="submit" class="submit_button"/>
</form>
</div>
<div class="space"></div>
<div id="flash"></div>
<div id="show"></div>
action.php
<?php
include('DB.php');
$check = mysql_query("SELECT * FROM comment order by commentID desc");
if(isset($_POST['content']))
{
$content=mysql_real_escape_string(trim($_POST['content']));
$name=mysql_real_escape_string(trim($_POST['name']));
mysql_query("insert into comment(content,name) values ('$content','$name')");
$fetch= mysql_query("SELECT content FROM comment order by commentID desc where name = '$name'");
$row=mysql_fetch_array($fetch);
}
?>
<div class="showbox"> <?php echo $row['content']; ?> </div>
when I run this, the page display nothing when I insert the comment, can anyone help me to solve this? Thanks a lot!!
Some changes have been made as follows:
comment.php
<!-- ajax script -->
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".submit_button").click(function() {
var textcontent = $("#content").val();
var name = $("#name").val();
var dataString = 'content='+ textcontent + '&name='+name;
if(textcontent=='')
{
alert("Enter some text..");
$("#content").focus();
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
$.ajax({
type: "POST",
url: "action.php",
data: dataString,
cache: true,
success: function(html){
$("#show").after(html);
document.getElementById('content').value='';
$("#flash").hide();
$("#content").focus();
}
});
}
return false;
});
});
</script>
<div>
<!-- retrieve hotel id from hotel table -->
<?php
include('DB.php');
$id=$_GET['id'];
$query = mysql_query("select * from hotel where name='$id'");
while($rows=mysql_fetch_array($query)){
$name=$rows['name'];
$price=$rows['price'];
$duetime=$rows['dueTime'];
$address=$rows['location'];
}
?>
<!-- post form -->
<form method="post" name="form" action="">
<h3>Add Comment for <?php echo $name;?><h3>
<input type="text" name="name" id="name" value="<?php echo $name;?>" hidden > <br>
<textarea cols="30" rows="2" name="content" id="content" maxlength="145" >
</textarea><br />
<input type="submit" value="Post" name="submit" class="submit_button"/>
</form>
</div>
<div class="space"></div>
<div id="flash"></div>
<div id="show"></div>
action.php
<?php
include('DB.php');
$check = mysql_query("SELECT * FROM comment order by commentID desc");
if(isset($_POST['content']))
{
$content=$_POST['content'];
$name=$_POST['name'];
mysql_query("insert into comment (content,name) values ('$content','$name')");
echo '<div class="showbox">'.$content.'</div>';
}
?>
Reasons why your code failed:
name not added in dataString causing name not sent in post
some mysql errors
I have a login form that uses JQuery and PHP to validate a username and password. I am trying to switch over from extension mysql to mysqli for better practice and am having a lot of trouble. I think the error exists in the JQuery somewhere because I've tested the login.php validation and it works fine.
So here is my code:
index.php:
<!doctype html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#login_a").click(function(){
$("#shadow").fadeIn("normal");
$("#login_form").fadeIn("normal");
$("#user_name").focus();
});
$("#cancel_hide").click(function(){
$("#login_form").fadeOut("normal");
$("#shadow").fadeOut();
});
$("#login").click(function(){
var username=$('#user_name').val();
var password=$('#password').val();
$.ajax({
type: "POST",
url: "login.php",
data: "name="+username+"&pwd="+password,
success: function(html){
if(html=='true'){
$("#login_form").fadeOut("normal");
$("#shadow").fadeOut();
$("#profile").html("<a href='logout.php' id='logout'>Logout</a>");
}
else{
$("#add_err").html("*Wrong username or password");
}
},
beforeSend:function(){
$("#add_err").html("Loading...")
}
});
return false;
});
});
</script>
</head>
<body>
<?php session_start(); ?>
<div id="profile">
<?php if(isset($_SESSION['user_name'])){ ?>
<a href='logout_script_2.php' id='logout'>Logout</a>
<?php }else {?>
<a id="login_a" href="#">login</a>
<?php } ?>
</div>
<div id="login_form">
<form action="login_script_2.php" method="POST">
<label>User Name:</label>
<input type="text" id="user_name" name="user_name" />
<label>Password:</label>
<input type="password" id="password" name="password" />
<label></label><br/>
<input type="submit" id="login" value="Login" />
<input type="button" id="cancel_hide" value="Cancel" />
</form>
<div class="err" id="add_err"><br></div>
</div>
<div id="shadow" class="popup"></div>
</body>
</html>
login.php
<?php
session_start();
$con = mysqli_connect("localhost","root","PW","db") or die("Connection error: " . mysqli_error($con));
if(isset($_POST['submit'])){
$username = $_POST['name'];
$password = $_POST['pwd'];
$stmt = $con->prepare("SELECT * FROM tapp_login WHERE username = ? AND password = ? LIMIT 1");
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
if($stmt->num_rows == 1)
{
if($stmt->fetch())
{
$_SESSION['Logged'] = 1;
$_SESSION['user_name'] = $username;
echo 'Access granted';
exit();
}
}
else {
echo "*Wrong username or password";
}
$stmt->close();
}
else {
}
$con->close();
?>
logout.php
<?php
session_start();
unset($_SESSION['user_name']);
header('Location: index.php');
?>
All the attempts to run the code give me the error in the JQuery validation "*Wrong username or password". Thanks in advanced!
When logging in using ajax, you are not posting submit, so this line
if(isset($_POST['submit'])){
is never true so your code never executes.
Either change it to
if(isset($_POST['name'])){
or add it to your ajax posted data
data: "submit=true&name="+username+"&pwd="+password,
AJAX is a partial submission. Make sure you're firing it without using a submit button, or return false; inside your click function, at the bottom. I would use <input type='button' id='login_a' />, if it's not a link. Additionally, you are not setting your submit button, like #Sean said, because it's AJAX.