edit.php
<?php
if (((!empty($_GET["mode"])) && (!empty($_GET["ID"]))) && ($_GET["mode"] == "update")) {
if (isset($_POST["updateSubmit"])) {
if ((!empty($_GET["ID"])) && (!empty($_POST["FilmName"]))
&& (!empty($_POST["Producer"])) && (!empty($_POST["YearPublished"]))
&& (!empty($_POST["Stock"])) && (!empty($_POST["Price"]))) {
$query = "UPDATE ProductConsole "
. "SET FilmName = '" . $_POST["FilmName"] . "', "
. "Producer = '" . $_POST["Producer"] . "', "
. "YearPublished = '" . $_POST["YearPublished"] . "', "
. "Stock = " . $_POST["Stock"] . ", "
. "Price = '" . $_POST["Price"] . "' "
. "WHERE ID=" . $_GET['ID'] . ";";
$result = mysqli_query($connection, $query);
if ($result == false) {
echo "<p>Updating failed.</p>";
} else{
echo "<p><br><br>Updated, please refresh page.</p>"; // CAN I AVOID REFRESHING PAGE?
}
}
}
}
?>
So on the home page you can view products by table. You can click edit to edit that particular row. When I modify a value and navigate back to the home page, I have to manually refresh. Once I've edited the record, I have to refresh the page edit.php for it to retrieve the record. Here is the php for once the page is updated. I assume that's the only code you need. Can anyone help? Thanks
Related
I am new at web programming and JavaScript.
I have a model page that show all the details of a request let 's say. And Before that page, what the user sees is a list with all the requests he have made. The this is, I want somehow to passe the ID of that clicked request, save it somewhere and pass to the other page and in there, by ID e shows all the details of that previously clicked request.
Here is my code:
<div class="list-group">
<?php
$id_utilizador = $_SESSION["id_utilizador"];
if(isset($_POST["por_aprovar"])){
$url = "http://localhost/myslim_aluguer_viaturas/api/requisicoes/fase1/" . $id_utilizador;
$json = file_get_contents($url);
$obj = json_decode($json);
if($obj->status == true){
$array = $obj->data;
foreach($array as $requisicao){
echo "<a href='requisicao.php' name = 'requisicao" . $requisicao->requisicao->id . "' class='list-group-item'>" . $requisicao->nome_condutor . " | " . $requisicao->requisicao->deslocacao . " | " . $requisicao->descricao_viatura . " | " . $requisicao->requisicao->data_requisicao . "</a>";
}
} else {
echo "Não existem resultados a apresentar.";
}
?>
I don 't know what to do. thank you for your time!!!
What you are looking for is a url query string aka get parameters. In your code change this:
echo "<a href='requisicao.php' name = 'requisicao" . $requisicao->requisicao->id . "' class='list-group-item'>" . $requisicao->nome_condutor . " | " . $requisicao->requisicao->deslocacao . " | " . $requisicao->descricao_viatura . " | " . $requisicao->requisicao->data_requisicao . "</a>";
To this:
echo "<a href='requisicao.php?theid=" . $requisicao->requisicao->id . "' class='list-group-item'>" . $requisicao->nome_condutor . " | " . $requisicao->requisicao->deslocacao . " | " . $requisicao->descricao_viatura . " | " . $requisicao->requisicao->data_requisicao . "</a>";
And on requisicao.php you will obtain the value using php's super global variable $_GET[] which will be something like this:
if(isset($_GET['theid']) && $_GET['theid'] != ''){
$the_id = $_GET['theid'];
// do stuff with $the_id;
}
You can pass multiple values by adding additional parameters:
requisicao.php?theid=22&anothervar=something&var3=33
Also keep in mind the security implications when passing variables via query string parameters as users will be able to easily manipulate these variables, and they will be saved in access logs. Your application should have the logic to sanitize and insure that the values passed are valid.
I need to exicute one JS function after another sequencually. I can exicute these functions individually and they work but when I put them in a sequence I only get the openPatient() and the openMessage() does not exicute. My JS functions
function openPatient() {
myRestoreSession();
opener.top.RTop.document.location.href = '../patient_file/summary/demographics.php?set_pid=<?php echo attr($ptid); ?>';
}
function openMessage(messageid) {
myRestoreSession();
document.location.href = 'upload_form.php?messageid=' + messageid;
}
My function call:
echo " onclick=\"openPatient().then(openRequest(" .
"'" . addslashes($postid) . "'," .
"'" . addslashes($v1[1]['type']) . "'" .
"))\">" . text($v1[1]['datetime']) . "</td>\n";
This function call exists in this process:
<?php
// Generate a table row for each pending portal request or message.
// This logic merges requests with messages by date.
$v1 = each($result['list']);
$v2 = each($result['messages']);
while ($v1 || $v2) {
echo " <tr class='detail' bgcolor='#ddddff'>\n";
if (!$v2 || $v1 && $v1[1]['datetime'] < $v2[1]['datetime']) {
$postid = $v1[1]['postid'];
$ptname = patientNameFromLogin($v1[1]['user']);
// Get the portal request data.
if (!$postid) die(xlt('Request ID is missing!'));
$result2 = cms_portal_call(array('action' => 'getpost', 'postid' => $postid));
if ($result2['errmsg']) {
die(text($result2['errmsg']));
}
// Look up the patient in OpenEMR.
$ptid = lookup_openemr_patient($result2['post']['user']);
echo " <td>" . text($v1[1]['user']) . "</td>\n";
echo " <td style='cursor:pointer;color:blue;' onclick=\"openPatient()\">" .text($ptname ) . "</td>\n";
echo " <td style='cursor:pointer;color:blue;'";
echo " onclick=\"openPatient().then(openRequest(" .
"'" . addslashes($postid) . "'," .
"'" . addslashes($v1[1]['type']) . "'" .
"))\">" . text($v1[1]['datetime']) . "</td>\n";
echo " <td>" . text($v1[1]['type' ]) . "</td>\n";
echo " <td align='center'><input type='checkbox' name='form_req_cb[" .
attr($postid) . "]' value='" . attr($postid) . "' /></td>\n";
$v1 = each($result['list']);
}
else {
$messageid = $v2[1]['messageid'];
$ptname = patientNameFromLogin($v2[1]['user']);
echo " <td>" . text($v2[1]['user']) . "</td>\n";
echo " <td>" . text($ptname ) . "</td>\n";
echo " <td style='cursor:pointer;color:blue;'";
echo " onclick=\"openMessage(" .
"'" . addslashes($messageid) . "'" .
")\">" . text($v2[1]['datetime']) . "</td>\n";
echo " <td>" . text($v2[1]['user'] == $v2[1]['fromuser'] ?
xl('Message from patient') : xl('Message to patient')) . "</td>\n";
echo " <td align='center'><input type='checkbox' name='form_msg_cb[" .
attr($messageid) . "]' value='" . attr($messageid) . "' /></td>\n";
$v2 = each($result['messages']);
}
echo " </tr>\n";
}
?>
I am thinking part of the problem may be that openPatient() opens in another window. Perhaps it is loosing focus. Any tips to fix this would be appreciated.
EDIT:
What I have tried and helps is adding return this; to openPatient():
function openPatient() {
myRestoreSession();
opener.top.RTop.document.location.href = '../patient_file/summary/demographics.php?set_pid=<?php echo attr($ptid); ?>';
return this;
}
This then executes the next function but the next function executes too soon. it needs to wait for openPatient() to fully load before executing openMessage(). I have tried adding setTimeout( wait, 1000 ); but then openMessage() does not execute at all.
The solution:
The call:
echo " <td style='cursor:pointer;color:blue;'";
echo " onclick=\"openPatient();setTimeout(function(){openRequest(" .
"'" . addslashes($postid) . "'," .
"'" . addslashes($v1[1]['type']) . "'" .
")}, 2500);\">" . text($v1[1]['datetime']) . "</td>\n";
The functions:
function openPatient() {
myRestoreSession();
opener.top.RTop.document.location.href = '../patient_file/summary/demographics.php?set_pid=<?php echo attr($ptid); ?>';
return this;
}
function openMessage(messageid) {
myRestoreSession();
document.location.href = 'upload_form.php?messageid=' + messageid;
}
Keys to success: return this; and the use of the anonymous function with setTimeout in the call.
Posts that helped:
What does "return this" do within a javascript function?
setTimeout delay not working
hope you can help
I want to have a drop down list that searches my mysql database and shows the first and last names of the users. You can then select any of the names and it will generate the rest of the membership details (i.e. date signed up, last logged in etc).
I have got the dropdown list working fine, but my problem comes with the next step of generating the rest of the details. With my below code it just shows the details of the last user who signed up and does not change when I change the name in the drop down menu.
I'm pretty sure I need Javascript to help get this working but as I am a beginner to PHP/MYSQL any advise toward the right direction for me would be great. Thanks
This is the code which searches my database and puts the first and last name in to a drop down list
$sql = "SELECT first_name,last_name FROM registration_tbl";
$query = mysqli_query($dbc, $sql);
echo '<select name="name" style="width: 400px">';
while ($row = mysqli_fetch_assoc($query)){
$firstname = $row['first_name'];
$lastname = $row['last_name'];
echo'<option>' . $firstname . " " . $lastname . '</option>';
}
echo '</select> <p>';
Again the above code works fine, but the below code is what I am having difficulty with
$sql = "SELECT * FROM registration_tbl WHERE first_name = '".$firstname."'";
$query = mysqli_query($dbc, $sql);
while($row = mysqli_fetch_array($query)){
echo "ID: " . " " . $row[0] . "<br>" .
"Name: " . $row[1] . " " . $row[2] . "<br>" .
"Company: " . $row[3] . "<br> " .
"Email: " .$row[4] . "<br> " .
"Date of registration: " . $row[6] . "<br> " .
"Last login: " .$row[7] . "<br>" .
"Admin/User: " .$row[8] . "<p>";
}
if you don't want to use AJAX to dynamically load the content, you need a form to submit the data, your problem is that after your first loop, $firstname is the last user loaded into the , to make your code work, you need a form.
just put the select in a form and add a button
<form action="mypage.php" method="get">
<select name="name" style="width: 400px">
<?php
$sql = "SELECT first_name,last_name FROM registration_tbl";
$query = mysqli_query($dbc, $sql);
while ($row = mysqli_fetch_assoc($query)){
$firstname = $row['first_name'];
$lastname = $row['last_name'];
echo'<option>' . $firstname . " " . $lastname . '</option>';
}
?>
</select>
<input type="submit" value="Load User Data">
</form>
then in mypage.php you need to check if the form is submitted, and show the user details.
<?php
if(isset($_GET["name"])) {
//this form is posted, show user details
//$firstname = $_GET["name"]; <--- SQL Injection enabled here!!
$firstname = mysqli_real_escape_string($_GET["name"]); // please try to avoid SQL injection!
//your code continues here
$sql = "SELECT * FROM registration_tbl WHERE first_name = '".$firstname."'";
$query = mysqli_query($dbc, $sql);
while($row = mysqli_fetch_array($query)){
echo "ID: " . " " . $row[0] . "<br>" .
"Name: " . $row[1] . " " . $row[2] . "<br>" .
"Company: " . $row[3] . "<br> " .
"Email: " .$row[4] . "<br> " .
"Date of registration: " . $row[6] . "<br> " .
"Last login: " .$row[7] . "<br>" .
"Admin/User: " .$row[8] . "<p>";
}
}
last note, if you don't want the username to appear in the querystring, change form action to post, and get variable using $_POST["name"]
EDIT: if you want the form to autopost using javascript then add this to ur select definition:
<select name="name" style="width: 400px" onchange="this.form.submit()">
but bear in mind that a lot of users block javascript, thus this will not work.
The best way would be to use AJAX to get the data of the other script. However, another (far less elegant and efficient) way of doing it is while you're looping through the names to put into the select. You can also be using the names to get the info for that name and put it into an array (but don't echo it) until you need it.
Use this code from where user will select the name
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js">
<script type="text/javascript">
$(document).ready(function()
{
$(".listdata").change(function()
{
var dataString = 'listdata='+ $(this).val();
$.ajax
({
type: "POST",
url: "alldata",
data: dataString,
cache: false,
success: function(html)
{
$(".alldata").html(html);
}
});
});
});
</script>
<?php
$sql = "SELECT first_name,last_name FROM registration_tbl";
$query = mysqli_query($dbc, $sql);
echo '<select name="name" style="width: 400px" class="listdata">';
while ($row = mysqli_fetch_assoc($query)){
$firstname = $row['first_name'];
$lastname = $row['last_name'];
echo'<option value="'.$firstname.'">' . $firstname . " " . $lastname . '</option>';
}
echo '</select> <p>';
?>
<div class="alldata">
<!--here your all data will come-->
</div>
<br/><br/>
Crate one more and give the name alldata.php
And use the below code on that page
<?php
$sql = "SELECT * FROM registration_tbl WHERE first_name = '".$firstname."'";
$query = mysqli_query($dbc, $sql);
while($row = mysqli_fetch_array($query)){
echo "ID: " . " " . $row[0] . "<br>" .
"Name: " . $row[1] . " " . $row[2] . "<br>" .
"Company: " . $row[3] . "<br> " .
"Email: " .$row[4] . "<br> " .
"Date of registration: " . $row[6] . "<br> " .
"Last login: " .$row[7] . "<br>" .
"Admin/User: " .$row[8] . "<p>";
}
?>
Just to complete your options, here you have a full but basic AJAX implementation (using jQuery):
File select.php (javascript part at the bottom of the file):
<?php
// Notice that you'll need to get the $dbc from somewhere, maybe require 'db.php'?
// Retrieve list of people... (notice I've added id column!)
$sql = "SELECT id, first_name, last_name FROM registration_tbl";
$query = mysqli_query($dbc, $sql);
$people = [];
while ($row = mysqli_fetch_assoc($query)){
$people[$row['id']] = $row['first_name'] . " " . $row['last_name'];
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>List of people</title>
<style type="text/css">
.error {
color: red;
box-shadow: 0px 0px 15px 0px rgba(247, 17, 40, 0.44);
}
#person-info {
padding: 10px;
margin-top: 1em;
}
</style>
</head>
<body>
<h2>People list</h2>
<label for="person">Please select one person</label>
<select name="person" id="people-selection">
<option value="-1"></option>
<?php foreach ($people as $person_id => $person_name): ?>
<option value="<?php echo $person_id ?>"><?php echo $person_name ?></option>
<?php endforeach; ?>
</select>
<div id="person-info"><!-- here we will put person info using AJAX request --></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
// We bind our AJAX handler to the onChange event of the select element
$("#people-selection").on('change', function(e) {
if ($(this).val() != -1) { // If we did select some value
$.ajax({
type: "POST",
url : "/get_people_info.php",
data: { id: $(this).val() },
})
.done(function(data) {
$("#person-info")
.removeClass("error") // we don't need the error class here, it's a success response
.html(data);
})
.fail(function(jqXHR, textStatus, errorThrown) {
$("#person-info")
.addClass("error") // in order to add some UI for the user
.html("Something went wrong!<br><blockquote>" + errorThrown + "</blockquote>");
});
}
else {
$("#person-info")
.removeClass("error")
.html("");
}
})
});
</script>
</body>
</html>
And then get_people_info.php
<?php
if ($_SERVER['REQUEST_METHOD'] !== "POST") {
header('HTTP/1.0 400 Bad request');
die("Only POST request accedpted!");
}
if (!isset($_POST['id'])) {
header('HTTP/1.0 400 Bad request');
die("id parameter is mandatory!");
}
$id = (int) $_POST['id'];
// Notice that you'll need to get the $dbc from somewhere, maybe require 'db.php'?
$sql = "SELECT * FROM registration_tbl WHERE id = ". $id .";";
$query = mysqli_query($dbc, $sql);
if ($row = mysqli_fetch_array($query)){
echo "<p>ID: " . " " . $row[0] . "<br>" .
"Name: " . $row[1] . " " . $row[2] . "<br>" .
"Company: " . $row[3] . "<br> " .
"Email: " .$row[4] . "<br> " .
"Date of registration: " . $row[6] . "<br> " .
"Last login: " .$row[7] . "<br>" .
"Admin/User: " .$row[8] . "</p>";
}
else {
echo "Person not found!";
}
Let me give you some further reading (you said you were new to PHP, I asume the whole web development):
jQuery Learning center
PHP: The right way
I'm trying to alter the src of imgs loaded via. AJAX, wherein the <select> and <option> elements used to control the function are also loaded by AJAX.
I'm trying to do this in order to change the size of Flickr images on the page.
I've tried loading the element, and calling an existing function to update it, but of course the <select> option doesn't exist on document.ready() and thus returns null when I try to get it.
I've also tried loading a new <script type='text/javascript'></script> in the PHP file I'm using for my XML response, but although this shows on the page it obviously isn't picked up as a source.
How can I tell the Document to 're-ready' itself, or acknowledge new sources?
Here's my code as it stands:
Making the request
function makeRequest (url, userID, searchString, selectedLicense) {
event.preventDefault();
var formData = new FormData();
formData.append("userID", userID);
formData.append("searchString", searchString);
formData.append("selectedLicense", selectedLicense);
var xmlRequest = new XMLHttpRequest();
xmlRequest.open("POST", url, true);
xmlRequest.send(formData);
xmlRequest.onreadystatechange=function()
{
if (xmlRequest.readyState===4 && xmlRequest.status===200) {
document.getElementById("working...").innerHTML="<p style='background-color:#BCED91; width:200px; text-align:center;'>Done!</p>";
document.getElementById("results").innerHTML=xmlRequest.responseText;
} else {
document.getElementById("results").innerHTML="<p>Ready State: " + xmlRequest.readyState + "</p> <p>Status Code: " + xmlRequest.status + "</p>";
}
}
}
The PHP
//more code before
$resultString = $resultString . "<script type='text/javascript'>"
. "function sizeChanged(i, select) {
var sel = getSelectedOptionValue(select);
var imgURL = document.getElementById(i.toString());
alert(imgURL);
}"
. "</script>";
//main loop
foreach ($XML->photos->photo as $photo):
$resultString = $resultString . '<div class="photoBox"' . photoBox($photoCounter) . "> <p>" . $photoCounter . ". " . $photo['title'] . "" . "</p>"
. " <p>" . "<img id='" . $photoCounter . "' src=\"http://farm" . $photo['farm'] . $imgURL . "/" . $photo['server'] . "/" . $photo['id'] . "_" . $photo['secret'] . "_" . $size . "\" alt=\"" . $photo['title'] . "\">" . "</p>"
. "<select form='addInformationForm' id='selectSize" . $photoCounter . "' onChange='return sizeChanged(" . $photoCounter . ", selectSize" . $photoCounter . ");'>"
. "<option value='n'>Small (320)</option>"
. "<option value='z' selected='selected'>Medium (640)</option>"
. "<option value='h'>Large (1600)</option>"
. "</select>"
. "</div>";
$photoCounter++;
endforeach;
//more code here
echo $resultString;
The HTML Output (Example)
<div class="photoBox" style="background-color:#FFFFFF">
<p>1. Killip's Adirondack Travelog, page 20</p>
<p><img id="1" src="http://farm9.staticflickr.com//8184/8427833074_2f7e22e7ce_z.jpg" alt="Killip's Adirondack Travelog, page 20"></p>
<select form="addInformationForm" id="selectSize1" onChange="return sizeChanged(1, selectSize1);">
<option value="n">Small (320)</option>
<option value="z" selected="selected">Medium (640)</option>
<option value="h">Large (1600)</option></select>
</div>
Any advice much appreciated!
NOTE: This code is for an internal tool, not a client-facing website.
The <select> doesn't exists at onload, but it does when you create it:
var res = document.getElementById("results");
xmlRequest.onreadystatechange = function() {
if (xmlRequest.readyState===4 && xmlRequest.status===200) {
document.getElementById("working...").innerHTML="<p style='background-color:#BCED91; width:200px; text-align:center;'>Done!</p>";
res.innerHTML = xmlRequest.responseText;
var select = res.getElementsByTagName('select')[0];
/* Use select here */
} else {
res.innerHTML="<p>Ready State: " + xmlRequest.readyState + "</p> <p>Status Code: " + xmlRequest.status + "</p>";
}
};
Note that the <img> element should be available too, but you won't know its dimensions because it won't be downloaded. If you want to wait until it's loaded, you can add a load event listener.
I'm trying to make a comments system which adds to the database using PHP and AJAX without having to reload the page (if I reload the page it will pick another film suggestion at random).
At the moment it doesn't seem to work - when I click "Submit comment" it reloads the page (loading a different film) and nothing is inserted to the database.
I'd also like to be able to have the comment appear in the comments section below after submission if possible.
Thanks for your help
yourfilm.php (the process page that displays a film, specified by options selected on a form on the previous page)
<?php //recaptcha_process.php
require_once("php/checklog.php");
require_once('php/functions.php');
require_once('php/db_connect.php');
include_once("php/home_start_logged.php");
if (!$db_server){
die("Unable to connect to MySQL: " . mysqli_connect_error());
$db_status = "not connected";
}else{
//CODE TO QUERY DATABASE TO GO HERE
//Capture form data, if anything was submitted
if (isset($_POST['genreList']) && ($_POST['genreList'] != '')){
$genre = clean_string($db_server, $_POST['genreList']);
//create the SQL query
$query = "SELECT * FROM films WHERE genreID=$genre ";
//$endquery = " AND (";
$endquery = "";
$orFlag = false;
if (isset($_POST['streamingCheckbox1']) && ($_POST['streamingCheckbox1'] != '')){
$endquery .= " netflix IS NOT NULL";
$orFlag = true;
}
if (isset($_POST['streamingCheckbox2']) && ($_POST['streamingCheckbox2'] != '')){
if($orFlag){
$endquery .= " OR ";
}
$endquery .= " lovefilmInstant IS NOT NULL";
$orFlag = true;
}
if (isset($_POST['streamingCheckbox3']) && ($_POST['streamingCheckbox3'] != '')){
if($orFlag){
$endquery .= " OR ";
}
$endquery .= " blinkbox IS NOT NULL";
}
if($endquery != "") $query .= " AND (" . $endquery . ")";
$query .= " ORDER BY (SELECT FLOOR(MAX(filmID) * RAND()) FROM films) LIMIT 0,1;";
//query the database
mysqli_select_db($db_server, $db_database);
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server) . $query);
//if there are any rows, print out the contents
if ($row = mysqli_fetch_array($result)) {
//Whether to display links or not for purchase and streaming
if ($row['netflix'] == null){
$netflixLink = "";
}else{
$netflixLink = "<a href='" . $row['netflix'] . "'>" . "<img class='streamingLogo' src='images/netflix_logo.jpg' alt='Watch on Netflix'></a>";
}
if ($row['lovefilmInstant'] == null){
$lovefilmLink = "";
}else{
$lovefilmLink = "<a href='" . $row['lovefilmInstant'] . "'>" . "<img class='streamingLogo' src='images/Lovefilm_logo.jpg' alt='Watch on LoveFilm'></a>";
}
if ($row['blinkbox'] == null){
$blinkboxLink = "";
}else{
$blinkboxLink = "<a href='" . $row['blinkbox'] . "'>" . "<img class='streamingLogo' src='images/blinkbox_logo.jpg' alt='Watch on Blinkbox'></a>";
}
if ($row['itunes'] == null){
$iTunesLink = "";
}else{
$iTunesLink = "<a href='" . $row['itunes'] . "'>" . "<img class='streamingLogo' src='images/itunes_logo.jpg' alt='Buy now on iTunes'></a>";
}
if ($row['googlePlay'] == null){
$googleplayLink = "";
}else{
$googleplayLink = "<a href='" . $row['googlePlay'] . "'>" . "<img class='streamingLogo' src='images/googleplay_logo.jpg' alt='Buy now on Google Play'></a>";
}
if ($row['amazon'] == null){
$amazonLink = "";
}else{
$amazonLink = "<a href='" . $row['amazon'] . "'>" . "<img class='streamingLogo' src='images/amazon_logo.jpg' alt='Buy now on Amazon'></a>";
}
//Body content for film
$str_result = "<section>
<div class='sectionColumnThird'>
<img class='poster' src='images/posters/" . $row['poster'] . ".jpg'>
</div>
<div class='sectionColumnTwoThirds'>
<h2>" . $row['filmName'] . "</h2>
<p class='filmDate'>(" . $row['filmYear'] . ")</p>
<a class='formButton' href='#comments'>Jump to comments</a>
</div>
</section>
<section>
<h3>Not interested?</h3>
<a class='formButton' href='#yourfilm.php'>Find another film</a>
</section>
<section>
<h3>Rating</h3>
<p><span class='bold'>IMDB:</span> " . $row['ratingIMDB'] . "</p>
<p><span class='bold'>Rotten Tomatoes:</span> " . $row['ratingRottenTomatoes'] . "</p>
<p><span class='bold'>Metacritic:</span> " . $row['ratingMetacritic'] . "</p>
</section>
<section>
<h3>Synopsis</h3>
<p>" . $row['synopsis'] . "</p>
</section>
<section>
<h3>Trailer</h3>
<div class='videoWrapper'>
<iframe src='//www.youtube.com/embed/" . $row['trailer'] . " ' frameborder='0' allowfullscreen></iframe>
</div>
</section>
<section>
<h3>Cast & Crew</h3>
<p><span class='bold'>Director:</span> " . $row['director'] . "</p>
<p><span class='bold'>Writers:</span> " . $row['writer'] . "</p>
<p><span class='bold'>Cast:</span> " . $row['cast'] . "</p>
</section>
<section>
<h3>Details</h3>
<p><span class='bold'>Certificate:</span> " . $row['certificate'] . "</p>
<p><span class='bold'>Country:</span> " . $row['country'] . "</p>
<p><span class='bold'>Language:</span> " . $row['language'] . "</p>
</section>
<section>
<h3>Streaming Services</h3>"
. $netflixLink . $lovefilmLink . $blinkboxLink ."
</section>
<section>
<h3>Buy now</h3>"
. $iTunesLink . $googleplayLink . $amazonLink ."
</section>
<section>
<form id='frmFilmComments' action='yourfilm.php' method='post'>
<a id='comments' class='anchor'></a><h3>Comments</h3>
<p><span class='bold'>Did you like " . $row['filmName'] ."?</span></p>
<select class='selectbox' name='yesornoList'>
<option value='Yes'>Yes</option>
<option value='No'>No</option>
</select>
<p id='commentResult'></p>
<p><span class='bold'>Provide your feedback here:</span></p>
<textarea id='commentBox' class='insertComment' rows='2' cols='30' name='comment'></textarea><br>
<input class='formButton' type='submit' id='submitComment' name='submitComment' value='Submit comment' />
</form>";
$filmID=$row['filmID'];
mysqli_free_result($result);
//Print out Like it - Comments
$likeitQuery = "SELECT * FROM comments
JOIN users on users.userID = comments.userID
WHERE likeit='Yes' AND filmID=$filmID";
$likeitResult = mysqli_query($db_server, $likeitQuery);
if (!$likeitResult) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($likeitResult)){
$str_likedcomments .= "<p>" . $row['username'] . " - " . $row['commDate'] . "<br>"
. $row['comment'] . "<br>
▲(" . $row['upvotes'] . ") ǀ ▼ (" . $row['downvotes'] . ")</p>";
}
mysqli_free_result($likeitResult);
$likedcomments = "<div class='half subSection'>
<h4>Liked it</h4>"
. $str_likedcomments .
"</div>";
//Print out disike it - Comments
$dislikeitQuery = "SELECT * FROM comments
JOIN users on users.userID = comments.userID
WHERE likeit='No' AND filmID=$filmID";
$dislikeitResult = mysqli_query($db_server, $dislikeitQuery);
if (!$dislikeitResult) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($dislikeitResult)){
$str_dislikedcomments .= "<p>" . $row['username'] . " - " . $row['commDate'] . "<br>"
. $row['comment'] . "<br>
▲(" . $row['upvotes'] . ") ǀ ▼ (" . $row['downvotes'] . ")</p>";
}
mysqli_free_result($dislikeitResult);
$dislikedcomments = "<div class='half subSection'>
<h4>Disliked it</h4>"
. $str_dislikedcomments .
"</div>";
}else{
$str_result = "<section><h3>Sorry</h3><p>We couldn't find any films that match your terms. </br> <a href='home.php'>Please try again.</a></p></section>";
}
}else{
$str_result = "<section><h3>Sorry</h3><p>No genre was chosen.</br><a href='home.php'>Please try again.</a></p></section>";
}
$message = $str_result . $likedcomments . $dislikedcomments . "<section/>";
}
//Comments
$userID = $_SESSION['userID'];
$likeit = $_POST['yesornoList'];
$comment = clean_string($db_server, $_POST['commentBox']);
//Get any submitted comments and insert
if ($comment != '') {
$query = "INSERT INTO comments (userID, filmID, comment, likeit) VALUES ($userID, $filmID, $comment)";
mysqli_select_db($db_server, $db_database);
mysqli_query($db_server, $query) or
die("Insert failed: " . mysqli_error($db_server));
$message = "Thanks for your comment!";
}
require_once('php/db_close.php');
?>
<div id="top" class="content container headerMargin">
<div class="content wrapper">
<?php echo $message; ?>
</div>
</div>
<?php
require_once('php/home_end.php');
?>
addCommentAJAX.js
$("#submitComment").click( function() {
$.post( $("#frmFilmComments").attr("action"),
$("#frmFilmComments :input").serializeArray(),
function(info){ $("#commentResult").html(info);
});
clearInput();
});
$("#frmFilmComments").submit( function() {
return false;
});
function clearInput() {
$("#frmFilmComments :input").each( function() {
$(this).val('');
});
}
home_start_logged.php is simply a header template, I won't post it all but it contains:
<script src="js/addCommentAJAX.js" type="text/javascript"></script>
EDIT: Added more specific info about the error (see above).
there is not enough data to make an exact solution, but i see two problems :
1 - you are not preventing the default form submit in your submit function event.preventDefautlt() or just change the input type attribut in your form to button rather than submit
2 - if you wan't the comment that the user just sent to show up then you can use the function append() to make it show at the end of the comment section this is the fastest way to do this rather than waiting for it to show from the database
So what is probably happening here is that you haven't used event.preventDefault() This will stop your submit button from reloading the page, which will allow your ajax code and your code posting the comment to finally get run.
http://api.jquery.com/event.preventdefault/
The idea behind preventDefault is that it stops the submit button from doing its default behavior, which is submitting a form and reloading the page.
can you change this
$("#submitComment").click( function() {
$.post( $("#frmFilmComments").attr("action"),
$("#frmFilmComments :input").serializeArray(),
function(info){ $("#commentResult").html(info);
});
clearInput();
});
to
function onclicksth() {
$.post( $("#frmFilmComments").attr("action"),
$("#frmFilmComments :input").serializeArray(),
function(info){ $("#commentResult").html(info);
});
clearInput();
}
and change submitComment type to button? There is a better way to do this too:
//rough code including the submit and post data
$('form.frmFilmComments').on('submit', function() {
if(confirm('Do u want to input that field')){
fields-=1;
var obj = $(this),
url = obj.attr('action'),
method = obj.attr('method'),
data = {};
$("#hdnlstcount").val(fields);
//console.log(fields);
obj.find('[name]').each(function(index, value) {
var obj = $(this),
name = obj.attr('name'),
value = obj.val();
data[name] = value;
});
$.ajax({
url: url,
type: method,
data: data,
success: function(response2) {
//do sth with success response
}
});
return false; //disable refresh
clearInput();
}
});