Comment section wont post comments - php

I have a problem in my code. When I post a comment aka when I hit the button, it wont show in the comment field before I refresh the site. Can somebody help me with that? It would be truly appreciated!
<?php
$db = mysqli_connect("localhost", "root", "", "mydb");
if (mysqli_connect_errno()) {
die(mysqli_connect_error());
}
$query = "SELECT * FROM kommentar";
$resultat = mysqli_query($db,$query);
if (!$resultat) echo "<b>FEIL: ikke i stand til å sende.</b>";
$rows = array();
while ($row = mysqli_fetch_array($resultat, MYSQL_ASSOC)) {
$rows[] = $row;
}
$query2 = sprintf("select * from kommentar");
// Sender spørring til databasen og tester på om den gjekk OK
$resultat2=mysqli_query($db, $query2);
if (!$resultat2) echo "<b>FEIL: ikkje i stand til å senda.</b>";
// Initialisere rows2 som ein 'array'
$rows2 = array();
// Henter verdiar til rows1 frå database-svaret
while ($row2 = mysqli_fetch_array($resultat2, MYSQL_ASSOC)) {
$rows2[] = $row2;
}
if (isset($_GET['id']) && intval($_GET['id']) > 0) {
// Hentar id frå querystreng
$id = $_GET['id'];
// "Cast" id til integer, dvs. gjer om id til heiltal
$id = (int) $id;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Kommentarfelt</title>
</head>
<body>
<h3> Kommentarer: </h3>
<?php foreach($rows2 as $row2): ?>
<?php echo $row2['tekst']; ?>
Lagt inn <?php echo $row2['opprettet']; ?> av <?php echo
$row2['navn']; ?><br>
<?php endforeach; ?>
<h4> Skriv ny kommentar: </h4>
<form method="POST" action="test_envy.php?id=<?php echo $row1['id']; ?>">
<b>Navn:</b><br>
<input type="navn" name="navn"><br>
<b>Kommentar:</b><br>
<textarea cols="60" rows="6" name="tekst"></textarea><br>
<input type="submit" name="sendknapp" value="Send"></form>
</body>
<?php
/*if ($_POST["sendknapp"] == "Send")*/
if($_SERVER['REQUEST_METHOD'] == "POST")
{
//mysql_connect("localhost","root",""); /* server, username, passord */
//mysql_select_db("mydb");
$db = mysqli_connect("localhost","root","","mydb");
$navn=$_POST["navn"];
$tekst=$_POST["tekst"];
$query ="INSERT INTO kommentar (navn, tekst)";
$query.="VALUES ('$navn','$tekst')";
$resultat=mysqli_query($db, $query);
if ($resultat) {
printf("Kommentar registrert", mysqli_insert_id($db));
echo ("<a href='vg.no" . $id . "';> Oppdater side </a>");}
else printf("ikkje i stand til å senda query:%s", $query);;
}
?>

Until page reload, you need to temporarily add the comment via AJAX.
Something like this:
// Add this line in your form
<input type='hidden' id='ajaxURL' value='test_envy.php?id=<?php echo $row1['id'] ?>'>
// Add this to your HTML
<script>
$('input[name="sendknapp"]').click(function(e){
e.preventDefault(); // Stops your page from reloading
var ajaxurl = $('#ajaxURL').val();
$.ajax({ url: ajaxurl, // The URL you're gonna pass to the script
data: {action: 'test'}, // Variables you wanna pass to the function
type: 'post',
success: function(response) {
// Get your variables from the response
alert(response); // This will show you the response in an alert box
// $('#elementID').append("<a href='" + variable + "'> Oppdater side </a>");
}
});
});
</script>
So this should popup a box with a response in it. You need to tweak from here on. Your PHP needs to echo the response and then you append it to your HTML.
You need to pass variables via data. It all depends on what your php script does... In this case test_envy.php.
One more essential thing I forgot to mention is you need to add this line to the head of your html:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.js"></script>
This is to load jQuery on your page... Without it, the script won't work.
Let me know if you need more help.

Related

Searchbox (AJAX) won't load requested data

so I have a problem I can't find the error.
By default the page should load all data and when I hit search, only the requested ones (no refreshing page).
(Even better would be if I could also change the outcome/request by changing the url without having to type in in the input field:
entering url: .../searchpage.php?search=banana --> results for banana
entering url: .../searchpage.php?search=apple --> results for apple
but small steps first.)
Do you have maybe see where my problem is? Or so you know some good pages where I can find solutions/information for my problem? \
A big thankyou in advance!
index.php:
<script src="assets/js/jquery.min.js"></script> //v3.4.1
<section class="wrapper">
<div class="formpost">
<div class="searchpannel">
<input type="text" class="searchBox" name="searchBox" id="searchBox" placeholder="Search..">
<button type="submit" id="searchBtn">SEARCH</button>
</div>
<div id="SearchResult"> <?php include 'startdata.php'?> </div>
</div>
</section>
<script>
$(document).ready(function(){
$('#searchdata').click(function(e){
e.preventDefault();
var searchtext = $('input[name=searchBox]').val();
$.ajax({
type: "POST",
url: "fetchdata.php",
data: {
"search_post_btn": 1,
"searchBox": searchBox,
},
dataType: "text",
success: function (response) {
$("#SearchResult").html(response);
}
})
})
})
</script>
fetchdata.php:
<?php
$conn = mysqli_connect("localhost", "root", "");
$db = mysqli_select_db($conn, 'ajax');
if(isset($_POST['search_post_btn'])) {
$search = $_POST['searchBox'];
$query = "SELECT * FROM ajaxtest WHERE name LIKE '%$search%' ";
$query_run = mysqli_query($conn,$query);
if(mysqli_num_rows($query_run) > 0){
WHILE ($row = mysqli_fetch_assoc($query_run)) {
echo "<h2>Hallo, my name is ";
echo $row['name'];
echo "<strong>";
echo $row['famname'];
echo "</strong></h2><p> On the list I'm place ";
echo $row['id'];
echo "</p>";
}
}
}
?>
Hi you have to do some modification in your code
$.ajax({
type: "POST",
url: "fetchdata.php",
data: {
"search_post_btn": 1,
"searchBox": searchBox,
},
dataType: "json",
success: function (response) {
$("#SearchResult").html(response);
}
})
----- PHP CODE ----
<?php
$conn = mysqli_connect("localhost", "root", "");
$db = mysqli_select_db($conn, 'ajax');
if(isset($_POST['search_post_btn'])) {
$search = $_POST['searchBox'];
$query = "SELECT * FROM ajaxtest WHERE name LIKE '%$search%' ";
$query_run = mysqli_query($conn,$query);
if(mysqli_num_rows($query_run) > 0){
$design = "";
WHILE ($row = mysqli_fetch_assoc($query_run)) {
$design .= "<h2>Hallo, my name is ".$row['name']."<strong>".$row['famname']."</strong></h2><p> On the list I'm place ".$row['id']."</p>";
}
print_r(json_encode($design));
die;
}
}
?>

Is There Any Way I Can Do This Without Refreshing The Page?

I am trying to create and edit button, like Reddit has, for my forum. I have got it to work but I was wondering if I'd be able to do it without having to refresh the page.
For example, when I click the edit button, it reloads the page and displays the form for editing, then when I click save it will reload yet again to display the new edited post.
Code (EDITED from IncredibleHat's answer):
<?php
session_start();
$host = "host"; // Host name
$user = "username"; // Mysql username
$password = "password"; // Mysql password
$db_name = "database"; // Database name
$tbl_name = "fquestions"; // Table name
// Connect to server and select databse.
$conn = mysqli_connect($host, $user, $password)or die("cannot connect");
mysqli_select_db($conn, $db_name)or die("cannot select DB");
// get value of id that sent from address bar
$id = $_GET['id'];
$sql = "SELECT * FROM $tbl_name WHERE id='$id'";
$result = mysqli_query($conn, $sql);
$rows = mysqli_fetch_array($result);
/*Check if topic is locked or not */
$locked = $rows['locked'];
if ($_SESSION['username'] == $rows['username']) {
$editPost = true;
}
?>
<head>
<!-- ****** faviconit.com favicons ****** -->
<link rel="shortcut icon" href="../images/favicon.ico">
<!-- ****** faviconit.com favicons ****** -->
<link id ="pageStyle" rel="stylesheet" href='../css/defaultStyle.css' type='text/css'> <!-- Loads Default Stylesheet -->
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Roboto' type='text/css'>
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
<div id="mainContent">
<div id="question">
<p id="date"><?php echo $rows['datetime']; ?></p>
<h2><?php echo $rows['topic']; ?></h2>
<b><p><?php echo $rows['username']; ?></p></b>
<?php
// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
// The Text you want to filter for urls
$text = htmlspecialchars($rows['detail']);
// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {
$url = preg_replace("/^http:/i", "https:", $url);
// make the urls hyper links
echo preg_replace($reg_exUrl, '<a title="Opening this link will take you to a new page" alt="External Link Deleted" target="_blank" href="'.$url[0].'" rel="nofollow">'.$url[0].'</a><br>', '<p id="post">'.$text.'</p>');
} else {
?>
<p id="post"><?php echo htmlspecialchars($rows['detail']); ?></p>
<?php
}
if ($editPost == true) {
$_SESSION['detail'] = $rows['detail'];
$_SESSION['id'] = $rows['id'];
?>
<style>
#editPostButton {
border: none; outline: 0; background-color: #D8D8D8; margin-left: -5px;
}
#editPostButton.dark {
color: white;
background-color: #1C1C1C;
}
</style>
<input type="submit" value="Edit" name="editPostButton" id="editPostButton" data-postId="<?php echo $rows['id']; ?>">
<div id="editFormBlock"></div>
<script>
$(document).ready(function() {
// for clicking on the edit button, to grab the edit form
$("#editPostButton").on('click',function(e) {
e.preventDefault();
$.post(
'ajaxhandler.php',
{ action: 'editform', postid: $(this).data('postId') },
function(htmlReturn) {
$("#editFormBlock").html( htmlReturn ); // replace editForm content
},
'HTML'
);
});
// for clicking the save button for a edit form
// using .on so it catches dynamically added content
$("#editFormBlock").on('click',"#saveButton",function(e) {
e.preventDefault();
var data = $("#editForm").serializeArray();
data.push({name: 'action', value: 'saveform'});
$.post(
'ajaxhandler.php',
data,
function(htmlReturn) {
$("#editFormBlock").html( '' ); // clear edit form out
},
'HTML'
);
});
});
</script>
<?php
}
?>
</div>
<?php
$tbl_name2="fanswer"; // Switch to table "forum_answer"
$sql2 = "SELECT * FROM $tbl_name2 WHERE question_id='$id'";
$result2 = mysqli_query($conn, $sql2);
$row_cnt = mysqli_num_rows($result2);
if ($row_cnt > 0) {
?>
<h3>Replies:</h3>
<div id="replies">
<?php
while($rows = mysqli_fetch_array($result2)) {
?>
<p id="dates"><?php echo $rows['a_datetime']; ?></p>
<div id="reply">
<b><p><?php echo $rows['a_username']; ?></p></b>
<?php
// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
// The Text you want to filter for urls
$text = htmlspecialchars($rows['a_answer']);
// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {
$url = preg_replace("/^http:/i", "https:", $url);
// make the urls hyper links
echo preg_replace($reg_exUrl, '<a title="Opening this link will take you to a new page" alt="External Link Deleted" target="_blank" href="'.$url[0].'" rel="nofollow">'.$url[0].'</a>', $text);
} else {
?>
<p><?php echo htmlspecialchars($rows['a_answer']); ?></p>
<?php
}
?>
</div>
<?php
}
} else {
?>
<div id="answers">
<p style="color: red;">There doesn't seem to be anything here</p>
<?php
}
$sql3 = "SELECT view FROM $tbl_name WHERE id='$id'";
$result3 = mysqli_query($conn, $sql3);
$rows = mysqli_fetch_array($result3);
$view = $rows['view'];
// if have no counter value set counter = 1
if(empty($view)) {
$view = 1;
$sql4 = "INSERT INTO $tbl_name(view) VALUES('$view') WHERE id='$id'";
$result4 = mysqli_query($conn, $sql4);
}
// count more value
$addview = $view+1;
$sql5 = "update $tbl_name set view='$addview' WHERE id='$id'";
$result5 = mysqli_query($conn, $sql5);
mysqli_close($conn);
?>
</div>
<h3>Post A Reply:</h3>
<form name="form1" method="post" action="add-answer" autocomplete="off">
<label>Reply: </label>
<?php
if ($locked == 1) {
echo '<textarea name="a_answer" id="a_answer" style="width: 800px;" readonly>🔒 This topic is locked! 🔒</textarea><br>';
} else if ($_SESSION['logged_in'] != true) {
echo '<textarea name="a_answer" id="a_answer" style="width: 800px;" readonly>⛔ You must login to reply! ⛔</textarea><br>';
} else {
echo '<textarea name="a_answer" id="a_answer" maxlength="300" required style="width: 800px;"></textarea><br>
<div class="g-recaptcha" data-sitekey="6LdrxD4UAAAAACAaVAR6U9BjOEDC9-j4QaOzBsFh"></div>
<input type="submit" name="submit" value="Submit">
<input type="reset" name="reset" value="Reset">';
}
?>
<input name="id" type="hidden" value="<?php echo $id; ?>">
</form>
</div>
</body>
ajaxhandler.php:
<?php
session_start();
$detail = $_SESSION['detail'];
$id = $_SESSION['id'];
if (!empty($_POST['action'])) {
if ($_POST['action'] == 'editform') {
?>
<style>
#post, #editPostButton {
display: none;
}
#saveButton {
border: none; outline: 0; background-color: #D8D8D8; margin-left: -5px;
}
</style>
<form id="editForm">
<textarea name="detail"><?php echo $detail; ?></textarea><br>
<input type="button" id="saveButton" value="Save">
</form>
<?php
}
if ($_POST['action'] == 'saveform') {
// do save process to db
// echo out a new static post html block
$host = "host"; // Host name
$user = "username"; // Mysql username
$password = "password"; // Mysql password
$db_name = "database"; // Database name
$tbl_name = "fquestions"; // Table name
// Connect to server and select databse.
$conn = mysqli_connect($host, $user, $password)or die("cannot connect");
mysqli_select_db($conn, $db_name)or die("cannot select DB");
$sql = "UPDATE $tbl_name SET detail = '$detail' WHERE id=$id";
$result = mysqli_query($conn, $sql);
}
}
?>
Two ways you could do the toggling of an edit form.
Load in more html (sub parts, not whole html documents) with ajax calls, and replace existing elements with the new html chunks based on actions. Click the edit button, it calls ajax to 'get the form block', and then it replaces some slot on the page with it. Submitting the form, tosses that form, and replaces it with the new static text block. This is generally a cleaner way to handle it.
Have all the relevant bits in the html DOM on first load of the php script. Have many parts hidden. Then clicking certain buttons, or doing actions shows/hides elements based on those actions. This is easier, but not as clean, as all your form submit elements and actions, as well as the original static parts, are all in the HTML on every general page load.
An example of loading in a edit form on edit-button click, and swapping content blocks:
Basic static HTML framework (from first load of main.php):
<p id="post">[the original post html here]</p>
<?php if ($editPost == true) { /* dont bother if they have no edit rights */?>
<input type="button" id="editPostButton" value="Edit" data-postId="<?php echo $postId;?>">
<div id="editFormBlock"></div>
<?php }?>
Script area (jquery required):
<script language="Javascript" type="text/javascript">
$(document).ready(function() {
// for clicking on the edit button, to grab the edit form
$("#editPostButton").on('click',function(e){
e.preventDefault();
$.post(
'ajaxhandler.php',
{ action: 'editform', postid: $(this).data('postId') },
function(htmlReturn){
$("#editFormBlock").html( htmlReturn ); // replace editForm content
},
'HTML'
);
});
// for clicking the save button for a edit form
// using .on so it catches dynamically added content
$("#editFormBlock").on('click',"#saveButton",function(e){
e.preventDefault();
var data = $("#editForm").serializeArray();
data.push({name: 'action', value: 'saveform'});
$.post(
'ajaxhandler.php',
data,
function(htmlReturn){
$("#post").html( htmlReturn ); // replace static post content
$("#editFormBlock").html( '' ); // clear edit form out
},
'HTML'
);
});
});
</script>
The ajaxhandler.php:
// Have blocks that pertain to the $_POST['action']
if (!empty($_POST['action'])) {
if ($_POST['action'] == 'editform') {
// do a database select on using the postId
// grab the data you wish to use in the edit form
// build a form and echo it out for the ajax return
echo '
<form id="editForm">
<input type="hidden" name="postId" value="'. $row['id'] .'">
<textarea name="detail">'. $row['detail'] .'</textarea>
<input type="button" id="saveButton" value="Save">
</form>
';
}
if ($_POST['action'] == 'saveform') {
// put your "save to database" code here
// that uses $_POST['postId'], $_POST['detail'] etc
// after saving, grab a fresh copy of the post
// and then echo out a new static html #post content
echo htmlspecialchars($row['detail']);
}
}
I hope this was clear enough to understand to get a foothold on what you wish to do. There is a lot more you can do, with an extra errorBlock to show errors, and handling of results. You can even push in some animations too. Endless possibilities.
NOTE: I should warn you though, that this is all based off your example, where you are showing just one post, and one edit form. This uses "ID"s, which must be unique on the page. If you are planning on pouring many posts on ONE page, you will need to adjust everything to use classes and enumerated ID's to keep the unique.

Data is not inserting to database but retrieving is working fine using PHP and Ajax?

Before I ask you my question I want to clarify that I'm just a rookie to Ajax and Jquery, so please spare me if the doubt is very small or a piece of cake, sorry for that.
I'm trying to create review system for my E-Commerce using Ajax and PHP. The problem is, the data is not inserting in to the database, but if I insert the the data manually in the database it displaying perfectly in my site.I think there is something going wrong with the variable review or user_review but couldn't find what it is.So, could you please tell me where I've done the mistake.
<div role="tabpanel" class="tab-pane" id="reviews">
<h4>Write your Review</h4>
<form action="" method="post" onsubmit="return post();">
<textarea id="review" class="reviewbox" placeholder="Write Your Review Here....."></textarea>
<button type="submit" class="btn">Submit</button>
</form>
<div id="all_reviews">
<?php
$query = $pdo->prepare("SELECT * FROM reviews WHERE product_id=?");
$query -> bindValue(1, $id);
$query->execute();
while ($row = $query->fetch(PDO::FETCH_ASSOC))
{
$name = $row['user_name'];
$text = $row['review_text'];
$time = $row['post_time'];
?>
<h5>By <?php echo $name; ?></h5>
<p><i>posted on <?php echo $time; ?></i></p>
<p>
<?php echo $text; ?>
</p>
<hr>
<?php
}
?>
</div>
<script type="text/javascript" src="jquery.js">
< script type = "text/javascript" >
function post() {
var review = document.getElementById("review").value;
if (review) {
$.ajax({
type: 'POST',
url: 'post_reviews.php',
data: {
user_review: review
},
success: function(response) {
document.getElementById("all_reviews").innerHTML = response + document.getElementById("all_reviews").innerHTML;
document.getElementById("review").value = "";
}
});
}
return false;
}
</script>
</div>
This is my post_reviews.php:
<?php
session_start();
require('includes/product.php');
require('includes/connect.php');
$product = new Product;
if(isset ($_GET['id'])) {
$id = $_GET['id'];
$data = $product -> fetch_data($id);
if(isset($_POST['user_review'])){
$review=$_POST['user_review'];
if (isset($_SESSION['logged_in'])) {
$query = $pdo -> prepare("INSERT INTO reviews(product_id,user_name,review_text) VALUES (?,?,?)");
$query -> bindValue(1, $id);
$query -> bindValue(2, $_SESSION['name']);
$query -> bindValue(3,$review);
$query ->execute();
}
else{
$review_msg="Please login to post your review";
}
$query = $pdo->prepare("SELECT * FROM reviews WHERE product_id=?");
$query -> bindValue(1, $id);
$query->execute();
while ($row = $query->fetch(PDO::FETCH_ASSOC)){
$name = $row['user_name'];
$text = $row['review_text'];
$time = $row['post_time'];
?>
<?php if(isset($review_msg)){ ?>
<small style = "color : #aa0000"; ><?php echo $review_msg ?></small>
<br><br>
<?php } ?>
<h5>By <?php echo $name; ?></h5>
<p><i>posted on <?php echo $time; ?></i></p>
<p><?php echo $text; ?></p>
<hr>
<?php
}
}
exit;
}
?>
There is a mistake you have done your script code is not closed
<script type="text/javascript" src="jquery.js">
To
<script type="text/javascript" src="jquery.js"></script>
That is the reason your ajax is not working.
first check your ajax working or not on button click
var review = document.getElementById("review").value;
$.ajax({
type: "POST",
url: "post_reviews.php",
data: review,
cache: false,
dataType: 'json',
success: function(response){
document.getElementById("all_reviews").innerHTML = response + document.getElementById("all_reviews").innerHTML;
document.getElementById("review").value = "";
}
});
return false;
Now I see. You are submiting the form.
<form action="" method="post" onsubmit="return post();">
<textarea id="review" class="reviewbox" placeholder="Write Your Review
Here....."></textarea>
<button type="submit" class="btn">Submit</button>
</form>
Try to replace your form with this:
<form action="" method="post">
<textarea id="review" class="reviewbox" placeholder="Write Your Review
Here....."></textarea>
<button type="button" onclick="post()" class="btn">Submit</button>
</form>
If button type is "button" it will not submit the form. And by clicking it now will call your function and execute ajax call.

Unable to submit form, Just hit First Validation Error

When i submit my form i just hit my first validation error. No data ever posts.
I'm new to all this stackOverflow stuff and new to all the database scene. To get what I've got i used some TUT's and Books.
Hope someone can help me.
$itemid = $_GET['page_id'];
$itemid = mysql_real_escape_string($itemid);
//get data from database that needs editing
$sql = mysql_query("SELECT * FROM content WHERE `page_id`='{$itemid}'")or die(mysql_error());
//if(!$sql) die ("Database access failed" . mysql_error());
if(isset($_POST['submit'])){
//start validation
//check fields are not empty
if(empty($pagetitle)) {
$error['page_title'] = 'enter a title.';
}
$pagecontent = trim($_POST['page_content']);
if(empty($pagecontent)){
$error['page_content'] = 'Please enter your content.';
}
//If validation is ok... cary on.. do this
if (!$error) {
$pageid = $_POST['page_id'];
$pagetitle = $_POST['page_title'];
$pagecontent = $_POST['page_content'];
//Update items
$sql = "UPDATE content SET page_title ='$pagetitle', page_content ='$pagecontent' WHERE page_id='$itemid'";
$resultupdate = mysql_query($sql)or die (mysql_error());
//Success Message
echo "Your site is now updated";
}//close if !error
}//close if form submit
//input validation checks input not empty
if (isset($error['page_title'])) {
echo "<p><span class=\"warning\">" . $error['page_title']."</span><p> ";
}
if (isset($error['page_content'])) {
echo "<p><span class=\"warning\">" . $error['page_content']."</span><p> ";
}
?>
<div>
<?php while ($row = mysql_fetch_object($sql)) { ?>
<form action="<?php $_SERVER['PHP_SELF'];?>" method="post">
<input type="hidden" name="page_id" value="<?php echo $row->page_id; ?>" />
<div class="edit-title">
<h2><label>Page Title</label></h2>
<p><textarea name="page_title"><?php echo $row->page_title; ?></textarea></p>
</div><!-- end edit title -->
<div class="edit-content">
<h2><label>Page Content</label></h2>
<p><textarea name="page_content"><?php echo $row->page_content; ?></textarea></p>
</div><!-- end edit content -->
<div class="submit-form">
<input type="submit" name="submit" value="Update" />
</div>
</form>
<?php } ?>
</div>
You check if $pagetitle exists but you don't initialize it, you should have put :
if(empty($_POST['page_title'])) { ... }
EDIT :
if(isset($_POST['submit'])){
//start validation
//check fields are not empty
if(empty($_POST['page_title'])) {
$error['page_title'] = 'enter a title.';
}
$pagecontent = trim($_POST['page_content']);
if(empty($pagecontent)){
$error['page_content'] = 'Please enter your content.';
}
//If validation is ok... cary on.. do this
if (!$error) {
$pageid = $_POST['page_id'];
$pagetitle = $_POST['page_title'];
$pagecontent = $_POST['page_content'];
//Update items
$sql = "UPDATE content SET page_title ='$pagetitle', page_content ='$pagecontent' WHERE page_id='$itemid'";
$resultupdate = mysql_query($sql)or die (mysql_error());
//Success Message
echo "Your site is now updated";
}//close if !error
}//close if form submit

How can I use jQuery to submit a form using Ajax and then get the output of the page it submitted to?

I'm learning PHP and JavaScript, and I'm building a blogging platform. I'm working on the comment system. I want to check if the name field matches any users in the database, and if it does, then I want to display a message that the name is taken.
Here's the page that contains the form. (fullpost.php)
<!DOCTYPE html>
<html>
<?php
include ('functions.php');
connectDB();
$id = $_GET['id'];
$result = queryDB('SELECT * FROM posts WHERE id='.$id);
$post = mysql_fetch_array($result);
?>
<head>
<title><?php echo $post['title']; ?> - SimpleBlog</title>
<link rel="stylesheet" href="style.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.microsoft.com/ajax/jQuery.Validate/1.6/jQuery.Validate.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".commentform").validate();
});
</script>
</head>
<body>
<div id="header">
SimpleBlog
</div>
<div id="wrapper">
<?php
//post found, display it
if (mysql_num_rows($result) >0) {
echo '<div class="post">';
echo '<div class="postheader">';
echo '<h1>'.$post['title'].'</h1>';
echo '<h5>by '.$post['author'].' at '.$post['date'].' in '.$post['category'].'</h5>';
echo '</div>';
echo '<p>'.$post['fullpost'].'</p>';
echo '</div>';
//display comments form
?>
<div id="commentform">
<form action="commentsubmit.php" method="POST" class="commentform"/>
<?php
//if not logged in, display a name field
if (!loggedIn()) {
echo '<label for="author">Name: </label><br />';
echo '<input type="text" name="author" class="required"/><br />';
}
?>
<label for="comment">Comment: </label><br />
<textarea type="text" name="comment" class="required"></textarea><br />
<input type="hidden" value="<?php echo $id; ?>" name="postid"/>
<input type="submit" name="submit" Value="Submit" id="sendbutton" class="button"/>
</form>
</div>
<?php
}
else {
//no posts found
echo "That post doesn't exist!";
}
$result = queryDB('SELECT * FROM comments WHERE postid='.$id.' ORDER BY date DESC');
$numcomments = mysql_num_rows($result);
//comments found, display them
if (mysql_num_rows($result) >0) {
if (mysql_num_rows($result) == 1) {
echo '<h5>'.$numcomments.' Comment:</h5>';
}
if (mysql_num_rows($result) > 1) {
echo '<h5>'.$numcomments.' Comments:</h5>';
}
while($comment = mysql_fetch_array($result)) {
echo '<h6> by '.$comment['author'].' on '.$comment['date'].'</h6>';
echo '<p>'.$comment['text'].'</p>';
}
}
else {
//no comments found
echo '<h4>No comments</h4>';
}
?>
</div>
</body>
</html>
Here's the page it submits to. (commentnew.php)
<?php
//creates a new comment
include('functions.php');
//form submitted
if (isset($_POST['submit'])) {
//set $author if not logged in
if(!loggedIn()) {
//check if username is taken
connectDB();
$result = queryDB("SELECT * FROM users WHERE username='".$_POST['author']."'");
if (mysql_num_rows($result) > 0) {
die('That name is taken!');
}
else {
//username is not taken
$author = mysql_real_escape_string($_POST['author']);
}
}
else {
//user is logged in, set author to their username
$author = $_SESSION['username'];
}
//$author is set, submit
if (!empty($author)) {
$postid = mysql_real_escape_string($_POST['postid']);
$comment = mysql_real_escape_string($_POST['comment']);
$date = mysql_real_escape_string(date("Y-m-d")." ".date("H:i:s"));
queryDB('INSERT INTO comments (postid,date,author,text) VALUES ("'.$postid.'","'.$date.'","'.$author.'","'.$comment.'")');
echo 'Comment Sent!';
}
}
?>
I tried using $.ajax in the script tags, but it seems to do nothing. Can I get an example of how to properly use it? How do I get it to pull the message from commentnew.php? Am I going about checking for the username the wrong way? Should I be using jQuery's validation plugin somehow?
in general:
var form = $("form.commentform");
$.post(form.attr('action') , form.serialize(), function(data) {
alert("Response: " + data);
});
Try this
$("form.commentform").submit(function(e){
e.preventDefault();
$.post({
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(reponse){
//here response will contain whatever you send from the server side page
}
});
}):
Look into jquery ajax function. That's what I use. http://api.jquery.com/jQuery.ajax/

Categories