Cannot read property 'getEditor' of undefined - javascript

I am working on a website using CKEditor. I tried to incorporate the Image Uploader plugin (https://ckeditor.com/cke4/addon/uploadimage). When I try to copy in the image, I get an error: "Cannot read property 'getEditor' of undefined". I am fairly certain that I installed the files correctly because I am able to paste a photo into the textarea, but it is unable to post. The documentation (https://docs.ckeditor.com/ckeditor4/docs/#!/guide/dev_file_upload) of the plugin mentioned a lot of different code that the plugin requires, and it is likely that I am missing those files however the documentation is not very clear and is difficult to understand. If the problem is that I am missing those files, I would greatly appreciate it if someone could explain it to me. Here is the code of my file I am using:
<?php
error_reporting(E_ERROR | E_WARNING | E_PARSE);
require_once('../utils.php');
$access = $_REQUEST['access'];
$selectedPost = $_REQUEST['selectedPost'];
$submit = $_REQUEST['submit'];
$create = $_REQUEST['create'];
$delete = $_REQUEST['delete'];
$save = $_REQUEST['save'];
?>
<html>
<head>
<style>
body
{
background-image: url('../imgs/background.jpg');
text-align: left;
}
h2 {
color: #880000;
}
#wrapper
{
font-family: arial;
padding-top: 50px;
padding-bottom: 50px;
padding-left: 20px;
padding-right: 20px;
background: #FFFFFF;
width: 800px;
}
</style>
<script type="text/javascript" language="javascript" src="ckeditor/ckeditor.js"></script>
</head>
<body>
<div id="wrapper">
<?php
// PRINTING OUT PAGE STUFF
echo '<h2>Manage News Posts</h2>';
// Boot you out if you lack the login stuff in the POST
if(!$access) {
echo '<h2>Invalid Login Credentials.</h2>';
echo 'Back';
}
// We are authenticated
else {
// Something was submitted. Do whatever we are trying to, then dump us back
// to the main post selection UI.
if($submit) {
if($create) {
$query = "INSERT INTO blog_posts VALUES (NULL, '" . $_REQUEST['postSubject'] . "', '" . $_REQUEST['postBody'] . "', CURRENT_DATE)";
$insertPost = doQuery($query);
$query = '';
if($insertPost) {
echo '<i><h4>New Post Created!</h4></i>';
}
else {
echo '<i><h4>Error encountered during New Post creation!</h4></i>';
}
}
else if ($save) {
$query = "UPDATE blog_posts SET subject = '" . $_REQUEST['postSubject'] . "', body = '" . $_REQUEST['postBody'] . "' WHERE post_id = " . $selectedPost;
$updatePost = doQuery($query);
$query = '';
if($updatePost) {
echo '<i><h4>Post Updated Successfully!</h4></i>';
}
else {
echo '<i><h4>Error encountered during post update!</h4></i>';
}
}
else if ($delete) {
$query = "DELETE FROM blog_posts WHERE post_id = " . $selectedPost;
$deletePost = doQuery($query);
$query = '';
if($deletePost) {
echo '<i><h4>Post Deleted.</h4></i>';
}
else {
echo '<i><h4>Error encountered during deletion!</h4></i>';
}
}
$selectedPost = false;
$save = false;
$create = false;
$delete = false;
}
// Nothing selected, show the selection page.
if(!$create && !$selectedPost) {
echo '<form method="post" action="admin_posts.php?access=1">';
$query = "SELECT * FROM blog_posts ORDER BY post_id ASC";
$all_posts = getResults($query);
// Lay out selections
foreach($all_posts as $post) {
echo '<input type="radio" name="selectedPost" value="' . $post['POST_ID'] . '"/>' . ' ' . $post['SUBJECT'] . ' - (Posted on ' . $post['POST_DATE'] . ')<br/>';
}
echo '<input type="submit" value="Select" />';
echo '</form>';
// Create post button, gets its own form.
echo '<br/><br/>';
echo '<form method="post" action="admin_posts.php?access=1&create=1">';
echo '<input type="submit" value="Write New Post">';
echo '</form>';
// Back button
echo 'Back';
}
// End initial "nothing selected" box
// Something is selected, display its info for editing.
else {
echo '<br/>';
$post_subject = '';
$post_body = '';
if(!$create) {
$query = "SELECT * FROM blog_posts WHERE post_id = $selectedPost";
$post_data = getSingleRow($query);
$post_subject = $post_data['SUBJECT'];
$post_body = $post_data['BODY'];
}
// Print out the dialogue for creating and editing post
echo '<form method="post" action="admin_posts.php?access=1&submit=1">';
echo '<h4>Subject</h4>';
echo '<input name="postSubject" type="text" value="' . $post_data['SUBJECT'] . '" size=100/>';
echo '<br/>';
echo '<h4>Post Body</h4>';
echo '<textarea id="postBody" name="postBody" type="text" rows="25" cols="75">' . $post_data['BODY'] . '</textarea>';
echo '<br/><br/>';
if($create) {
echo '<input type="hidden" name="saveNewPost" value="1">';
echo '<input type="hidden" name="create" value="1">';
}
else {
echo '<input type="hidden" name="selectedPost" value="' . $selectedPost . '">';
echo '<input type="hidden" name="save" value="1">';
}
echo '<input type="submit" value="Save Post" />';
echo '</form>';
// Delete button. Only if you are editing.
// Gets its own submit form.
if(!$create) {
echo '<form method="post" action="admin_posts.php?access=1&submit=1&delete=1" onsubmit="return confirm(\'Are you sure you want to delete this post?\');">';
echo '<input type="hidden" name="selectedPost" value="' . $selectedPost . '">';
echo '<input type="submit" value="Delete Post">';
echo '</form>';
}
echo '<br/><br/>';
// Back button
echo 'Back';
}
}
?>
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
<script type="text/javascript">
bkLib.onDomLoaded(function()
{
CKEDITOR.replace( 'postBody' );
});
</script>
</div>
</body>
</html>

Related

how to do a 3 filters from a <select> in ajax

im a fairly newbie into javascript and php (just got less than two weeks max)however im trying to learn because i really enjoy this,anyway, right now im trying to do a proyect for the company where i work for ( not that we will use it, but as an incentive).
the proyect is about making a query in sql that would return a table, but using the parameters given in three drop down's
now those three 's must pick three conditionals. ie
$sql ="SELECT * FROM catalogo WHERE escuelas='$e' and grado='$g' and seccion='$p'";
so far i have wrote ( and to be honest copy/paste a lot from different sources)
the basics, but im stuck trying to a query.. anyway here is my code for the index.php
<script>
function showescuelas(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajaxdatospersonales.php?e="+str, true);
//xmlhttp.open("GET","ajaxdatospersonales.php?e="+document.getElementById("esc").value+"&gra="+document.getElementById("gra").value+"&sec="+document.getElementById("sec").value,,true);
xmlhttp.send();
}
}
</script>
</header>
<?php include_once("menu.php"); ?>
<div class="container">
<h1> Agregar apartado </h1>
<form id="form" method="post" action="procesadordatospersonales.php" >
<!-- down below is my first filter, it feeds from a table named "escuelas"-->
<p> <label for="escuelas">Escuela:</label>
<select name="escuelas" id="esc" onchange="showescuelas(this.value)">
echo "<option> </option>";
<?php
$con = mysql_connect('localhost', 'root', 'pass') or die(mysql_error());
mysql_select_db('apartados');
$sql = "SELECT escuelas FROM escuelas";
$data = mysql_query($sql,$con);
while($category = mysql_fetch_array($data)){
$catname = $category['escuelas'];
$valueid = $category['escuelas'];
echo '<option value="'.$valueid.'">'.$catname.'</option>';
}
?>
</select>
<br />
</p>
<!-- down below is my second filter, it feeds from a table named "grados"-->
<p> <label for="grado">grado:</label>
<select name="grado" id="gra" onChange="showgrados(this.value)">
echo "<option> </option>";
<?php
$con = mysql_connect('localhost', 'root', 'pass') or die(mysql_error());
mysql_select_db('apartados');
$sql = "SELECT grado FROM grado";
$data = mysql_query($sql,$con);
while($category = mysql_fetch_array($data)){
$catname = $category['grado'];
$valueid = $category['grado'];
echo '<option value="'.$valueid.'">'.$catname.'</option>';
}
?>
</select>
<br />
</p>
<!-- yep you guess it this is the last filter, it feeds from a table named "grados"-->
<p> <label for="seccion" >seccion:</label>
<select name="seccion" id="sec" onChange="showescuelas(this.value)">
echo "<option> </option>";
<?php
$con = mysql_connect('localhost', 'root', 'pass') or die(mysql_error());
mysql_select_db('apartados');
$sql = "SELECT seccion FROM seccion";
$data = mysql_query($sql,$con);
while($category = mysql_fetch_array($data)){
$catname = $category['seccion'];
$valueid = $category['seccion'];
echo '<option value="'.$valueid.'">'.$catname.'</option>';
}
?>
</select>
<br />
</p>
</div>
</div>
<div id="txtHint"><b> info will be listed here.</b></div>
<input type="submit" value="Agregar">
</form>
and this is my "ajaxdatospersonales.php"
<?php
$e=$_GET["e"];
$g=$_GET["g"];
$s=$_GET["s"];
$con = mysqli_connect('localhost','root','pass','apartados');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con);
//i made this array just to check if the variables
$test= array("$e", "$g", "$s");
echo "esta es la escuela " . $test[0] . " y este el grado " . $test[1] . " y la seccion " . $test[2] . ".";
$sql ="SELECT * FROM catalogo WHERE escuelas='$e' and grado='$g' and seccion='$p'";
$result = mysqli_query($con, $sql);
$ii=1;
echo "<table border='1'>
<tr>
<th>agregar</th>
<th>isbn</th>
<th>nombre</th>
<th>autor</th>
<th>editorial</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td> <input type='checkbox' name= isbn".$ii." value=".$row['isbn']. " </td>";
echo "<td>" . $row['isbn'] . "</td>";
echo "<td>" . $row['nombre'] . "</td>";
echo "<td>" . $row['autor'] . "</td>";
echo "<td>" . $row['editorial'] . "</td>";
echo "</tr>";
$ii++;
}
echo "</table>";
mysqli_close($con);
?>
now for some reaso it just dosent work.... i dont know whats going on..
thanks.
now if you decide to help me please, try to be as newbie frendly as possible.
also i already know about sql injection. but this is a proyect for fun

Calling Javascript from a Form using Onsubmit

I am newbie in PHP and AJAX, and I am in trouble and don't know how to solve it.
I am creating this page that shows a recordset that resulted from a query.
There are 2 pages: getdata.php and phpajax.php. phpajax.php calls getdata.php via Javascript.
What I have done:
I manage to make it work by using button "Try it" (using static value)
What I want:
How to display the data properly using "Submit" button on a single click (ATM the data appears for a couple of seconds after I click Submit twice, then disappears because the page suddenly refreshes) ?
How to pass the value of SELECT and TEXT into fshowdata() using the Submit Button ?
How to pass the value of SELECT and TEXT into fshowdata() using the "Try It" Button ?
Here is the for the phpajax.php:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script>
function fshowdata(str1,date1) {
//alert("The form was submitted");
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
//document.getElementById("demo").innerHTML = str1 + " " + date1;
xmlhttp.open("GET","getdata.php?q="+str1+"&"+"t="+date1,true);
xmlhttp.send();
}
}
</script>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
padding: 5px;
}
th {text-align: left;}
</style>
</head>
<body>
<p id="demo">Click the button to change the text in this paragraph.</p>
<?php
$con = mysql_connect('localhost','root','123');
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb')or die('Could not select database');
$sql="SELECT DISTINCT(rides) FROM t_trx ORDER BY rides ";
$result = mysql_query($sql) or die('Query failed: ' . mysql_error());
echo "<form onsubmit='"."fshowdata(`some rides`,`a date`)"."' action='".""."'>";
echo "Choose Rides : "." "."<select id='"."rides"."' name='"."rides"."'>";
echo "<option value='"."ALL"."'>ALL</option>";
while($row = mysql_fetch_array($result)) {
echo "<option value='".$row["rides"]."'>".$row["rides"]."</option>";
}
mysql_free_result($result);
echo "</select>";
mysql_close($con);
echo "<input id='"."date2"."' type='"."TEXT"."' name = '"."date2"."'>";
echo "<input id='"."button1"."' type='"."SUBMIT"."' value = '"."SUBMIT"."'>";
echo "</form>";
echo "<button onclick='"."fshowdata(`ROLLER COASTER`,`18/07/2015`)"."'>";
echo "Try it";
echo "</button>";
?>
<br>
<div id="txtHint"><b>Data will be shown here...</b></div>
</body>
</html>
And for the getdata.php:
<!DOCTYPE html>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
padding: 5px;
}
th {text-align: left;}
</style>
</head>
<body>
<?php
$q = $_GET['q'];
echo $q;
$date_ = $_GET['t'];
echo $date_;
$con = mysql_connect('localhost','root','123');
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb')or die('Could not select database');
$sql="SELECT * FROM t_trx WHERE rides = '".$q."' AND date1 = '".$date_."' LIMIT 10";
echo $sql;
$result = mysql_query($sql) or die('Query failed: ' . mysql_error());
echo "<table>
<tr>
<th>Rides</th>
<th>Number</th>
<th>Date</th>
</tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['Rides'] . "</td>";
echo "<td>" . $row['Number'] . "</td>";
echo "<td>" . $row['Date'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
</body>
</html>
Thanks guys. I appreciate your help...
use below code to skip refresh page
onsubmit="return fshowdata(`some rides`,`a date`)"
in the fshowdata function, you should return false.

Using ajax to refresh a div in a for each loop, wrong result

So I've been struggling with this for a while, i have a div and a form in a for each loop and on submitting one of the forms in the loop, the content of its div is updated in the database and refreshed ("div only"). This is done using JavaScript and Ajax. My update query works fine, JavaScript handles the form and Ajax refreshes only the div in the page. My problem is, upon refreshing all the contents in the loop are put into one div but instead i want one content to one div as many times the loop is run, to better understand my problem please refer to the image below:
Before:
After first like button is clicked:
This is the result i expect to see:
info.php
<html>
<head>
.......
<script type="text/javascript">
$(document).ready(function(){
$('.ajaxform').submit(function(e) {
e.preventDefault(); // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: "POST", // POST
dataType:'html',
url: "test.php", // the file to call
cache: false,
success: function(response) { // on success..
$('.ld').html(response);
}
});
return false; // cancel original event to prevent form submitting
});
});
</script>
</head>
<body>
<?php
...........
foreach($stmt as $obj){
$username = $obj['user_name'];
$comment = $obj['comment'];
$id = $obj['id'];
$userimage = $obj['user_image'];
$row ++;
$likes = $obj['like1'];
$dislikes = $obj['dislike'];
echo '<div class="txt">';
echo '<div class="comment-container">';
echo '<div class="comment-item">';
echo '<div class="comment-avatar">';
echo '<img src="user/user_images/'.$userimage.'" alt="avatar">';
echo '</div>';
echo '<div class="comment-post">';
echo '<span style="font-weight:bold;">'.$username.'&nbsp&nbspsaid....
</span>';
echo '<p style="margin-left:-11px;">'.$comment.'</p>';
echo '<input type="hidden" name="comment_id" value="'.$id.'">';
echo '<form action="" method="post" class="ajaxform"
enctype="multipart/form-data">';//form to submit
echo '<input type="hidden" name="lkcv[]" value="'.$id.'">';
echo '<input type="hidden" name="pid" value="'.$type_id.'">';
echo '<input type="hidden" name="stk" value="'.$likes.'">';
echo '<input type="image" src="images/like.png" id="lksub" width="15"
value="som" height="15" style="float:right;position:relative;margin-
right:290px;"/><div class="ld">'.$likes.'</div>';//div to refresh
echo '</form>';
echo '<form action="" method="post" enctype="multipart/form-data">';
echo '<input type="hidden" name="lkd_id" value="'.$id.'">';
echo '<input type="hidden" name="dislike" value="">';
echo ' <input type= "image" id="submit" src="images/dislike.png"
width="15" height="15" style="float:right;position:relative;
margin-top:-14px;margin-right:230px;"/>
<div class="ldks">'.$dislikes.'</div>';
echo '</form>';
echo '<span class="SendCopy">Reply</span> ';
echo '<div class="users">';
echo '<form action="" method="post" enctype="multipart/form-
data">';
echo '<textarea rows="4" name="replycomment" style="float:right;
resize: none;margin-top:5px;" cols="50" >';
echo '</textarea>';
echo '<input type="hidden" name="comment_id" value="'.$id.'">';
echo '<input type="submit" name="reply" id="submit" class="post-
button" value="Send" />';
echo '</form>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
?>
</body>
</html>
test.php
<?php
$mysqli = new mysqli("localhost", "root", "", "Anonmy");
if( isset( $_POST['lkcv'] ) && is_array( $_POST['lkcv'] ) )
{
$idArray = array();
foreach( $_POST['lkcv'] as $value )
{
$idArray[] = intval( $value );
}
$mysqli->query( "UPDATE comment SET like1 = like1 + 1 WHERE id IN (".implode(
',', $idArray ).")" );
}
?>
<?php
$host = 'localhost';
$dbname = 'dbname';
$username = "root";
$password = "";
$conn = new PDO('mysql:host=localhost;dbname=Anonmy', $username,
$password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$type_id = $_POST['pid'];
$like = $_POST['stk'];
$target_no = 3;
echo '<div class="wrap">';
// retrive comments with post id
$stmt = $conn->prepare(
"SELECT *
FROM comment
WHERE post_id = :pid
");
$stmt->bindParam(":pid", $type_id, PDO::PARAM_INT);
$stmt->execute();
foreach($stmt as $obj){
$username = $obj['user_name'];
$comment = $obj['comment'];
$id = $obj['id'];
$userimage = $obj['user_image'];
$likes = $obj['like1'];
$dislikes = $obj['dislike'];
echo '<div class="">'.$likes.'</div>';
}
?>
</body>
</html>
How can i modify my code to achieve the result in image 3.
test.php[updated]
$host = 'localhost';
$dbname = 'dbname';
$username = "root";
$password = "";
$conn = new PDO('mysql:host=localhost;dbname=Anonmy', $username,
$password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$type_id = $_POST['pid'];
$like = $_POST['stk'];
$target_no = 3;
echo '<div class="wrap">';
// retrive comments with post id
$stmt = $conn->prepare(
"SELECT *
FROM comment
WHERE post_id = :pid
");
$stmt->bindParam(":pid", $type_id, PDO::PARAM_INT);
$stmt->execute();
//updated
$result = array();
foreach ($stmt as $row) {
$result[] = array('id' => $row['id'], 'likes' => $row['like1'], 'dislikes' =>
$row['dislike']);
}
echo json_encode($result);
?>
info.php[updated]
<html>
<head>
.......
<script type="text/javascript">
$(document).ready(function(){
$('.ajaxform').submit(function(e) {
e.preventDefault(); // catch the form's submit event
//updated
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: "POST", // POST
dataType:'json',
url: "test.php", // the file to call
cache: false, // Not needed for POST
success: function(response) { // on success..
$.each(response, function(i, el) {
var comment_post = $("#comment-post-" + el.id);
comment_post.find(".ld").text(el.likes);
comment_post.find(".ldks").text(el.dislikes);
});
}
});
return false; // cancel original event to prevent form submitting
});
});
</script>
</head>
<body>
<?php
...........
foreach($stmt as $obj){
$username = $obj['user_name'];
$comment = $obj['comment'];
$id = $obj['id'];
$userimage = $obj['user_image'];
$row ++;
$likes = $obj['like1'];
$dislikes = $obj['dislike'];
echo '<div class="txt">';
echo '<div class="comment-container">';
echo '<div class="comment-item">';
echo '<div class="comment-avatar">';
echo '<img src="user/user_images/'.$userimage.'" alt="avatar">';
echo '</div>';
echo '<div class="comment-post" id="comment-post-' . $id .'">';//updated
echo '<span style="font-weight:bold;">'.$username.'&nbsp&nbspsaid....
</span>';
echo '<p style="margin-left:-11px;">'.$comment.'</p>';
echo '<input type="hidden" name="comment_id" value="'.$id.'">';
echo '<form action="" method="post" class="ajaxform"
enctype="multipart/form-data">';//form to submit
echo '<input type="hidden" name="lkcv[]" value="'.$id.'">';
echo '<input type="hidden" name="pid" value="'.$type_id.'">';
echo '<input type="hidden" name="stk" value="'.$likes.'">';
echo '<input type="image" src="images/like.png" id="lksub" width="15"
value="som" height="15" style="float:right;position:relative;margin-
right:290px;"/><div class="ld">'.$likes.'</div>';//div to refresh
echo '</form>';
echo '<form action="" method="post" enctype="multipart/form-data">';
echo '<input type="hidden" name="lkd_id" value="'.$id.'">';
echo '<input type="hidden" name="dislike" value="">';
echo ' <input type= "image" id="submit" src="images/dislike.png"
width="15" height="15" style="float:right;position:relative;
margin-top:-14px;margin-right:230px;"/>
<div class="ldks">'.$dislikes.'</div>';
echo '</form>';
echo '<span class="SendCopy">Reply</span> ';
echo '<div class="users">';
echo '<form action="" method="post" enctype="multipart/form-
data">';
echo '<textarea rows="4" name="replycomment" style="float:right;
resize: none;margin-top:5px;" cols="50" >';
echo '</textarea>';
echo '<input type="hidden" name="comment_id" value="'.$id.'">';
echo '<input type="submit" name="reply" id="submit" class="post-
button" value="Send" />';
echo '</form>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
?>
</body>
</html>
test.php[ajax response]
<html>
<head>
<script type="text/javascript" src="js/jquery-2.1.4.js"></script>
<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2
/jquery.min.js"> </script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1
/jquery.min.js"> </script>
<script language="JavaScript">
$(document).ready(function(){
$(".users").hide();
$(".SendCopy").click(function(){
$(this).next(".users").slideToggle("slow");
});
});
</script>
</head>
<body>
[{"id":"2","likes":"196","dislikes":"0"},
{"id":"5","likes":"80","dislikes":"0"},
{"id":"6","likes":"45","dislikes":"0"},
{"id":"7","likes":"31","dislikes":"0"}]
</body>
</html>
Change the HTML so that the post ID is included in the the ID of the DIV containing the like/dislike data.
echo '<div class="comment-post" id="comment-post-' . $id .'">';
Change test.php so it returns JSON instead of HTML:
$result = array();
foreach ($stmt as $row) {
$result[] = array('id' => $row['id'], 'likes' => $row['like1'], 'dislikes' => $row['dislike']);
}
echo json_encode($result);
Remove all other code in test.php that produces output, like this line:
echo '<div class="wrap">';
The only output should be the JSON.
Then in the AJAX call, extract the JSON data and update each corresponding element with its likes and dislikes.
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: "POST", // POST
dataType:'json',
url: "test.php", // the file to call
cache: false, // Not needed for POST
success: function(response) { // on success..
$.each(response, function(i, el) {
var comment_post = $("#comment-post-" + el.id);
comment_post.find(".ld").text(el.likes);
comment_post.find(".ldks").text(el.dislikes);
});
}
});

Hide div once sql query is successful

I am trying to make the div, "yourpick," hide once the POST query is successful. I know I'm checking for the POST in the middle of my form, but can we work around this. Thanks.
echo '<div class="yourpick" style="display:block;">
YOUR PICK:<br><form method="post" action="draft.php">';
echo '<input type="radio" name="pick" value="user1">User1<br>';
if(isset($_POST["pick"])){
$pick = $_POST["pick"];
$picksql = "UPDATE picks SET playerpick='" . $pick . "' WHERE id=$id AND picknum=$picknum";
if ($mysqli->query($picksql) === TRUE) {
echo "Pick Successful!";
echo "<script>document.getElementById('yourpick').style.display = 'none';</script>";
} else {
echo "Error Ocurred. Please contact commisioner.";
}
}
echo "<input type='submit' name='submit' /></form></div>";
It is best imo to use php alternative syntax in the HTML, so if isset($_POST["pick"]), then hide the div:
<?php if(isset($_POST["pick"])): ?>
<div class="yourpick" style="display:block;">
YOUR PICK:<br><form method="post" action="draft.php">
<input type="radio" name="pick" value="user1">User1<br>
<input type="submit" name="submit"></form></div>
<?php endif; ?>
Makes your code all nice and tidy. :)
You do not need Javascript for this:
if (isset($_POST["pick"])) {
$pick = $_POST["pick"];
$picksql = "UPDATE picks
SET playerpick = '$pick'
WHERE id = $id AND picknum = $picknum";
if ($mysqli->query($picksql) === TRUE) {
echo "Pick Successful!";
} else {
echo "Error Ocurred. Please contact commisioner.";
}
}
else {
echo '<div class="yourpick" style="display:block;">'.
'YOUR PICK:<br><form method="post" action="draft.php">'.
'<input type="radio" name="pick" value="user1">User1<br>'.
'<input type="submit" name="submit"></form></div>';
}
Sorry, but I'm not pointing out the obvious security risks of this code.

php information not passing through with sessions and pagination

So I've been looking at this page for hours and hours and I can't seem to figure out what the problem is here. I had this issues with all links previously, where I would lick a link to filter/sort database results, click a page link to go to the next page and it would display the second page without any filtered results. I resolved this for "Most Wins", "Best Save %" and "Best Goals Against" by the use of sessions, but for some reason it is still doing this when I try and filter results via my range sliders form. It works when I adjust the sliders, and submit, but if I click another page, once again, it show all results in the database. Can anyone see as to why it might be doing this? I've tried both post and get methods from the form but it didn't seem to work, but if anyone could provide some advice I would greatly appreciate it!!
Here is the code:
<body>
<header>
<div class="header-container">
<nav>
<img src="images/header_img.png" alt="Golaie Gear Online"/>
<ul>
<li>Browse Goalies</li>
<li>Browse Gear</li>
<li>Admin</li>
</ul>
<form method="get" action="<?php echo "generalsearch.php?q=$searchvalue"; ?>" class="search-field">
<input name="search" type="text" placeholder="Search">
<button type="submit" title="Search" id="submit"><img src="images/header_srch.png" alt="search"/></button>
</form>
</nav>
</div>
<div style="clear:both;"></div>
</header>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<style type="text/css">
#win-range, #gaa-range, #sv-range{
width: 160px;
font-size: 10px;
margin: 0 auto;
}
#win-range a, #gaa-range a, #sv-range a{
margin-top: 0px !important;
padding: 0 !important;
}
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function(){
$("#win-range").slider({
range: true,
min: 1,
max: 1000,
values: [1, 1000],
slide: function(event, ui) {
// in order to pass the user selected values to your app, we will use jQuery to prepopulate certain hidden form elements, then grab those values from the $_POST
$("#minwins").val(ui.values[0]);
$("#maxwins").val(ui.values[1]);
$("#winamount").val(ui.values[0] + " - " + ui.values[1]);
}
});
$("#winamount").val($("#win-range").slider("values", 0) + " - " + $("#win-range").slider("values", 1));
});
$(function(){
$("#gaa-range").slider({
range: true,
min: 0,
max: 10,
values: [0, 10],
slide: function(event, ui) {
// in order to pass the user selected values to your app, we will use jQuery to prepopulate certain hidden form elements, then grab those values from the $_POST
$("#mingaa").val(ui.values[0]);
$("#maxgaa").val(ui.values[1]);
$("#gaaamount").val(ui.values[0] + " - " + ui.values[1]);
}
});
$("#gaaamount").val($("#gaa-range").slider("values", 0) + " - " + $("#gaa-range").slider("values", 1));
});
$(function(){
$("#sv-range").slider({
range: true,
min: 750,
max: 1000,
values: [750, 1000],
slide: function(event, ui) {
// in order to pass the user selected values to your app, we will use jQuery to prepopulate certain hidden form elements, then grab those values from the $_POST
$("#minsv").val(ui.values[0]);
$("#maxsv").val(ui.values[1]);
$("#svamount").val(ui.values[0] + " - " + ui.values[1]);
}
});
$("#svamount").val($("#sv-range").slider("values", 0) + " - " + $("#sv-range").slider("values", 1));
});
</script>
<?php
include("includes/header.php");
include("includes/mysqli_connect.php");
$sortDesc = $_REQUEST['sortstats'];
$sortAsc = $_REQUEST['sortstatslow'];
$minwins = $_GET['minwins'];
$maxwins = $_GET['maxwins'];
$mingaa = $_GET['mingaa'];
$maxgaa = $_GET['maxgaa'];
$minsv = $_GET['minsv'];
$maxsv = $_GET['maxsv'];
// FILTERING YOUR DB
$sortstats = $_GET['sortstats'];
$sortstatslow = $_GET['sortstatslow'];
$getminwins = $_REQUEST['getminwins'];
$getmaxwins = $_REQUEST['getmaxwins'];
$getmingaa = $_REQUEST['getmingaa'];
$getmaxgaa = $_REQUEST['getmaxgaa'];
$getminsv = $_REQUEST['getminsv'];
$getmaxsv = $_REQUEST['getmaxsv'];
// paging
$getcount = mysqli_query ($con,"SELECT COUNT(*) FROM Player");
$postnum = mysqli_result($getcount,0);// this needs a fix for MySQLi upgrade; see custom function below
$limit = 6; //how many blog posts per page you will see.
if($postnum > $limit){
$tagend = round($postnum % $limit,0);
$splits = round(($postnum - $tagend)/$limit,0);
if($tagend == 0){
$num_pages = $splits;
}else{
$num_pages = $splits + 1;
}
if(isset($_GET['pg'])){
$pg = $_GET['pg'];
}else{
$pg = 1;
}
$startpos = ($pg*$limit)-$limit;
$limstring = "LIMIT $startpos,$limit";
}else{
$limstring = "LIMIT 0,$limit";
}
// MySQLi upgrade: we need this for mysql_result() equivalent
function mysqli_result($res, $row, $field=0) {
$res->data_seek($row);
$datarow = $res->fetch_array();
return $datarow[$field];
}
?>
<div class="listingcontainer">
<div class="sidebar">
<h3>Sort By:</h3>
Most Wins
Best Goals Against
Best Save %
<hr/>
<h3>Custom Filter</h3>
<br/>
<div class="custom-filter">
<form name="filters" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="get" id="filters">
<label for="winamount">Win Range:</label>
<input type="text" id="winamount" />
<div style="clear:both;"></div>
<input type="hidden" id="minwins" name="minwins" value="0" />
<input type="hidden" id="maxwins" name="maxwins" value="1000" />
<div id="win-range"></div>
<br/>
<label for="gaaamount">GAA:</label>
<input type="text" id="gaaamount" /><br />
<div style="clear:both;"></div>
<input type="hidden" id="mingaa" name="mingaa" value="0" />
<input type="hidden" id="maxgaa" name="maxgaa" value="10" />
<div id="gaa-range"></div>
<br/>
<label for="svamount">SV %:</label>
<input type="text" id="svamount" /><br />
<div style="clear:both;"></div>
<input type="hidden" id="minsv" name="minsv" value="750" />
<input type="hidden" id="maxsv" name="maxsv" value="1000" />
<div id="sv-range"></div>
<input type="submit" name="submit" id="submit"/>
</form>
</div>
</div>
<div class="main-listings">
<h1>Current NHL Goaltenders</h1>
<?php
session_start();
if($_SESSION['allresults'])
{
$result = mysqli_query($con, "SELECT * FROM Player ORDER BY PlayerID ASC $limstring");
if(isset($sortstats)){//THIS WORKS
session_start();
$_SESSION['sortStatsDesc'] = session_id();
$result = mysqli_query($con,"SELECT * FROM Player ORDER BY $sortstats DESC $limstring ");
$filter = "sortstats={$sortDesc}";
}
if(isset($sortstatslow)) {//THIS WORKS
session_start();
$_SESSION['sortStatsAsc'] = session_id();
$result = mysqli_query($con,"SELECT * FROM Player ORDER BY $sortstatslow ASC $limstring ");
$filter = "sortstatslow={$sortAsc}";
}
if(isset($minwins) || isset($maxwins) || isset($mingaa) || isset($maxgaa) || isset($minsv) || isset($maxsv))//THIS SEEMS TO WORK
{
session_start();
$_SESSION['customFilter'] = session_id();
$result = mysqli_query($con, "SELECT * FROM Player WHERE Wins BETWEEN '$minwins' AND '$maxwins' AND
GAA BETWEEN '$mingaa' AND '$maxgaa' AND SavePerc BETWEEN '$minsv' AND '$maxsv'
ORDER BY PlayerID ASC $limstring") or die (mysql_error());
$filter = "getminwins={$minwins}&getmaxwins={$maxwins}&getmingaa={$mingaa}&getminsv={$minsv}&getmaxsv={$maxsv}";
}
}
else if($_SESSION['sortStatsDesc'])//THIS WORKS
{
$result = mysqli_query($con,"SELECT * FROM Player ORDER BY $sortstats DESC $limstring ");
}
else if($_SESSION['sortStatsAsc'])//THIS WORKS
{
$result = mysqli_query($con,"SELECT * FROM Player ORDER BY $sortstatslow ASC $limstring ");
}
else if($_SESSION['customFilter'])//DON'T KNOW IF THIS IS DOING ANYTHING
{
$result = mysqli_query($con, "SELECT * FROM Player WHERE Wins BETWEEN '$getminwins' AND '$getmaxwins' AND
GAA BETWEEN '$getmingaa' AND '$getmaxgaa' AND SavePerc BETWEEN '$getminsv' AND '$getmaxsv'
ORDER BY PlayerID ASC $limstring");
}
else{
}
while($row = mysqli_fetch_array($result)){
$name = $row['LastName'] . ", " . $row['FirstName'];
$wins = $row['Wins'];
$pid = $row['PlayerID'];
$image = $row['Picture'];
$gaa = $row['GAA'];
$sv = $row['SavePerc'];
echo "<div class=\"player-listing\">";
echo "<div class=\"image-holder\">";
echo "<span class=\"helper\"></span>";
echo "<img src=\"admin/thumbs/$image\" alt=\"$name\">";
echo "</div>";
echo "<div style=\"clear:both;\"></div>";
echo "$name";
echo "<table align=\"center\">";
echo "<tr>";
echo "<td style=\"border-bottom: 1px solid #212121;\">Wins</td>";
echo "<td style=\"border-bottom: 1px solid #212121;\">GAA</td>";
echo "<td style=\"border-bottom: 1px solid #212121;\">SV%</td>";
echo "</tr>";
echo "<tr>";
echo "<td>$wins</td>";
echo "<td>$gaa</td>";
echo "<td>.$sv</td>";
echo "</tr>";
echo "</table>";
echo "</div>";
}
// paging links:
echo "<div class=\"paging\">";
if($postnum > $limit){
echo "<span class=\"page-numbers\"><strong>Pages:</strong> </span>";
$n = $pg + 1;
$p = $pg - 1;
$thisroot = $_SERVER['PHP_SELF'];
if($pg > 1){
echo "<< prev ";
}
for($i=1; $i<=$num_pages; $i++){
if($i!= $pg){
echo "$i ";
}else{
echo "$i ";
}
}
if($pg < $num_pages){
// INSERT QUERY STRING VARIBLE TO CARRY OVER DB QUERY
echo "next >>";
}
echo " ";
}
// end paging
echo "</div>";
?>
<br/>
</div>
<div style="clear:both;"></div>
</div>
EDIT: I fixed the paging issue by adding this into my code:
$getcount = mysqli_query ($con,"SELECT COUNT(*) FROM Player");
if($_SESSION['customFilter']){
$getcount = mysqli_query ($con,"SELECT COUNT(*) FROM Player WHERE Wins BETWEEN '$minwins' AND '$maxwins' AND
GAA BETWEEN '$mingaa' AND '$maxgaa' AND SavePerc BETWEEN '$minsv' AND '$maxsv'");
}
But it's still giving me grief when I click next page. I don't think the filter values are carryying over for some reason.
Remove all the existing session_start() and add one on the first rule of the page, like:
<?php
session_start();
?>
//Your html/js/php
...
...
For session to works the very first instruction you have to call is "session_start()". You should call it only once and at the very beginning of your script.
<?php session_start() ?>
// rest of code PHP/HTML/JS/CSS/anything

Categories