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

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.

Related

Is there any way in PHP to store $variable of $variable in session

I created a web-page,where you can search plant's scientific name. Type plant name in search_text it will give you results in search_result(live search like google and facebook search bar) . Ex: when you will type C in search input, in search result you will get C related search. Like C typed in search input, in search result it will start showing Cucumber(Cucumis sativus), Capsicum(Capsicum annuum), etc.
Now I want when you will click on Cucumber(Cucumis sativus) in search result, it have to direct to home.php/Cucumber . Or when user click on Capsicum(Capsicum annuum), it have to direct on home.php/Capsicum .
And on home.php in body tag I want to display plant name with their scientific name. And in para tag information related to plant search result.
index.php
<!DOCTYPE html>
<html>
<head>
<title>Search</title>
<style type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </style>
<style type="text/javascript">
function searchq() {
var searchTxt = $("input[name='search']").val();
$.get("search.php", {searchVal: searchTxt}, function(output) {
$("#output").html(output);
});
}
</script>
</head>
<body>
<form action="index.php" method="post">
<input type="text" name="search" id="myInput1" autocomplete="off"
placeholder="Search username..." onkeydown="searchq(); " />
<input type="submit" value=">>"/>
</form>
<br>
<div id="output"></div>
</body>
</html>
search.php
<?php
$con = mysqli_connect('localhost', 'root');
mysqli_select_db($con, 'plant');
$output = '';
if (isset($_GET['searchVal'])) {
$searchq = $_GET['searchVal'];
$sql = "select * from type where plant like '%$searchq%'";
$query = mysqli_query($con, $sql) or die("could not search");
$count = mysqli_num_rows($query);
if ($count == 0) {
$output = 'There is no serach result';
} else {
while ($row = mysqli_fetch_array($query)) {
$plantname = $row['plant'];
$sciencename = $row['species'];
$id = $row['id'];
$output .= '<div>' . $plantname . ' ' . $sciencename . '</div>';
}
}
}
echo '<a herf="home.php/">' . $output . '</a></div>';
?>
There are many ways of doing this
Passing the name of the plant as a GET param is not an option?
You could do
echo "<a href='home.php?plantname={$plantname}' target='_blank'>{$output}</a></div>";
As the response of your server, that would create the link and in home.php you retrieve the plant name with $_GET['plantname'].
in home.php you do
if(isset($_GET['plantname'])){
echo $_GET['plantname'];
}
Please correct this line in index.php
<style type="text/javascript">
with
<script type="text/javascript">

Comment section wont post comments

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.

Carrying $id variable over in another file

I recently found this tutorial http://www.infotuts.com/create-ajax-based-search-system-php-jquery/ and have noticed that all the results are displayed in search.php while search.php is called through ajax and displayed in index.php. Whenever I tried to integrate it into my website, my index.php contains a variable of $id which is shown in this url: (index.php?id=1) My problem is, I can't seem to get it to know what my $id is. I am unable to change the query in search.php to what I like as a result of this.
$query = mysql_query("select * from userdetail where name like '{$term}%'", $connection);
Here is the original query above me, however I want to have it dependent on the id of the page, so... :
$query = mysql_query("select * from userdetail where id = '$id' AND name like '{$term}%'", $connection);
The only problem is, that search.php has no idea what my $id variable is, even when I load it from index.php it does not work. Can anyone help?
The full code can be seen in the tutorial, but I can show you guys here.
Search.php
<?php
$connection = mysql_connect('localhost', 'root', '12345');
$db = mysql_select_db('userdata', $connection);
$term = strip_tags(substr($_POST['searchit'],0, 100));
$term = mysql_escape_string($term); // Attack Prevention
if($term=="")
echo "Enter Something to search";
else{
$query = mysql_query("select * from userdetail where id = '$id' AND name like '{$term}%'", $connection);
$string = '';
if (mysql_num_rows($query)){
while($row = mysql_fetch_assoc($query)){
$string .= "<b>".$row['name']."</b> - ";
$string .= $row['email']."</a>";
$string .= "<br/>\n";
}
}else{
$string = "No matches found!";
}
echo $string;
}
?>
Here is index.php
<html>
<head>
<title>Ajax Based Search- InfoTuts</title>
<?php
$id = ((int)$_GET["id"]);
?>
<style type="text/css" >
#main {
padding: 10px;
margin: 100px;
margin-left: 300px;
color: Green;
border: 1px dotted;
width: 520px;
}
#display_results {
color: red;
background: #CCCCFF;
}
</style>
<script type="text/javascript "src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function(){
$("#search_results").slideUp();
$("#button_find").click(function(event){
event.preventDefault();
search_ajax_way();
});
$("#search_query").keyup(function(event){
event.preventDefault();
search_ajax_way();
});
});
function search_ajax_way(){
$("#search_results").show();
var search_this=$("#search_query").val();
$.post("search.php", {searchit : search_this}, function(data){
$("#display_results").html(data);
})
}
</script>
</head>
<body>
<div id="main">
<h1>Ajax Based Search System- InfoTuts</h1>
<form id="searchform" method="post">
<label>Enter</label>
<input type="text" name="search_query" id="search_query" placeholder="What You Are Looking For?" size="50"/>
<input type="submit" value="Search" id="button_find" />
</form>
<div id="display_results"></div>
</div>
</body>
</html>
Try this
In search.php file add the following code to accept the id from index.php file
<code>
$term = mysql_escape_string($term); // Attack Prevention
$id = $_POST['id'];
if(!empty($id)) {
$query = mysql_query("select * from userdetail where id = '$id' AND name like '{$term}%'", $connection);
} else {
$query = mysql_query("select * from userdetail where name like '{$term}%'", $connection);
}
if($term=="")
echo "Enter Something to search";
</code>
In the index.php file send the $id variable value along with the ajax request.
<code>
function search_ajax_way(){
$("#search_results").show();
var search_this=$("#search_query").val();
var id_val=$("#id").val();
$.post("search.php", {searchit : search_this, id : id_val}, function(data){ $("#display_results").html(data);}
</code>
In the html add a input hidden field for id
<code>
<form id="searchform" method="post">
<label>Enter</label>
<input type="text" name="search_query" id="search_query" placeholder="What You Are Looking For?" size="50"/>
<input type='hidden' value='<?php echo $id; ?>' id='id'/>
<input type="submit" value="Search" id="button_find" />
</form>
</code>
in
Please mention action='search.php' in form then it will redirect to search.php...and there you will get $id...

Using a variable with a changing value in MySQL query?

I'm building a tagging system for a site I'm working on. I have a variable for the url of the image that changes as the user selects different pictures. I'm using a MySQL command to display 3 tags for the selected picture, but it isn't working if I give it that changing variable. However, if I manually insert a url of an image, the captions show. However, these will show no matter what picture you're on so that doesn't really help. If I store a url under a variable, that works too, but not with the one that changes all the time.
Here's the site.
I know this isn't very easy to understand, so please let me know if you want me to try re-explaining something or if you want me to include some of the code. Thanks!
EDIT: Ok, I'll retry here. First, here's the code:
<?php
$username = $_GET['username'];
session_start();
$_SESSION['username'] = $username;
//Database Information
$dbhost = "";
$dbname = "";
$dbuser = "";
$dbpass = "";
//Connect to database
mysql_connect ( $dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());
//Do the query
$query = mysql_query("SELECT * FROM images ORDER BY idnum DESC LIMIT 5");
// Generate an array of all images.
$images = array();
while($image = mysql_fetch_array($query)) {
// Adds each image to the images array.
$images[] = $image;
}
$image['filename'] = $current_image;
$query_captions = mysql_query("SELECT * from captions WHERE image = '$current_image' ORDER BY idnum DESC LIMIT 3");
$captions = array();
while($caption = mysql_fetch_array($query_captions)) {
$captions[] = $caption;
}
?>
<?php
// Beginning attempt at a caption script.
?>
<html>
<head>
<title>Home - Site in Development</title>
<link rel="stylesheet" type="text/css" href="styles.css"/>
<script type="text/javascript">
// Switches the url to view large image.
function switchImageUrl(url, width, height) {
var x = document.getElementById('caption_selection');
var y = document.getElementById('caption_input');
var z = document.getElementById('input_value');
x.style.display = 'none';
y.style.display = 'none';
z.value = '';
document.getElementById('center_frame').style.backgroundImage = 'url' + '(' + url + ')';
document.getElementById('center_frame').style.width = width;
document.getElementById('center_frame').style.height = height;
}
</script>
<!--Toggles view of caption selection tools and resets after.-->
<script type="text/javascript">
function selectionToggle() {
var x = document.getElementById('caption_selection');
var y = document.getElementById('caption_input');
var z = document.getElementById('input_value');
if(x.style.display == 'block')
x.style.display = 'none';
else
x.style.display = 'block';
x.style.width = '75px';
x.style.height = '75px';
x.style.top = '0px';
x.style.left = '0px';
if(y.style.display == 'block')
y.style.display = 'none';
else
y.style.display = 'block';
z.value = '';
}
</script>
<script type="text/javascript">
function collectAttributes() {
var cap = document.getElementById('caption_selection');
var cw = document.getElementById('cap_width');
var ch = document.getElementById('cap_height');
var cl = document.getElementById('cap_left');
var ct = document.getElementById('cap_top');
cw.value = cap.style.width;
ch.value = cap.style.height;
cl.value = cap.style.left;
ct.value = cap.style.top;
}
</script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
$(document).ready(function() {
$("#caption_selection").draggable({
containment : "#center_frame"
});
$("#caption_selection").resizable({
containment : "#center_frame"
});
});
</script>
</head>
<body onLoad="CalculateAllImageWidthes()">
<div id='account_links'>
<?php
if ($_SESSION['username']) {
echo "Welcome $username!";
} else { ?>
<a href='login.php'>Login</a> | <a href='register.php'>Register</a>
<?php } ?>
</div>
<h1>Picture Captions</h1>
<br/>
<br/>
<div id="left_bar">
Submit a picture here.
<hr/>
<h2>Top Images</h2>
<br/>
<div id="front_pg_images">
<?php foreach($images as $image) { ?>
<a onClick="switchImageUrl('<?php echo $image['filename']; ?>', '<?php echo $image['width']; ?>', '<?php echo $image['height']; ?>')"><img src="<?php echo $image['filename'];?>" width="72px" height="58px" id="front_pg_thumbnail"/></a>
<?php echo $image['name']." - by ".$image['submitter']; ?> <br/>
<br/>
<?php } ?>
</div>
</div>
<div id="center_frame" style="width: <?php echo $image['width']; echo "px" ?>; height: <?php echo $image['height']; echo "px" ?>; background-image: url('<?php echo $image['filename'];?>')" >
<?php foreach($captions as $caption) { ?>
<div id="set_caption" style="width:<?php echo $caption['width'].'px';?>;height:<?php echo $caption['height'].'px';?>; left:<?php echo $caption['posleft'].'px';?>; top:<?php echo $caption['postop'].'px';?>"><?php echo $caption['text'];?></div>
<?php } ?>
<div id="caption_selection" style="display:none">
</div>
</div>
<div id="toggle_select_container">
<input type="button" id="toggle_select" onClick="selectionToggle()" value="Caption"/>
<div id="caption_input" style="display:none">
<form action="postcaption.php" method="post" onSubmit="collectAttributes()">
<br/>
<textarea name="caption_text" cols="27" rows="4" id="input_value"></textarea><br/>
<input type="hidden" name="filename" value="<?php echo $image['filename'];?>"/>
<input type="hidden" name="width" value="" id="cap_width"/>
<input type="hidden" name="height" value="" id="cap_height"/>
<input type="hidden" name="left" value="" id="cap_left"/>
<input type="hidden" name="top" value="" id="cap_top"/>
<input type="submit" value="Post Caption"/>
</form>
</div>
</div>
</body>
</html>
It uses a JavaScript function to change the image when the user clicks on the thumbnail. Take note of the foreach. For everywhere else on the page, the $image['filename'] has worked perfectly for similar uses, but it just isn't working when I try to use it with this.

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