PHP JavaScript MYSQL: Two search filed with autocompletement - javascript

In my website the user need to put in the apposite field the Name and the Set of a card. Foor doing this, i've implemented a search field for the 2 inpunt field that can help the user, linked to the Mysql database. The problem is when the user select a value: This value appears in both the serch filed like in the photo that I provide below.
The user select the name:
Result on both the search field
This codes in php/Javascript is for the input fields.
<div class="col-4">
<div class="form-group">
<!-- Doveva esserci name="search"-->
<input class="form-control" id="set_name" type="text" name="set_name" placeholder="Exact Set Name in English">
<div class="list-group" id="show-list">
<!-- Here autocomplete list will be display -->
</div>
<!-- country = set_name, countryList = show-list -->
</div>
</div>
<!-- script per auto completamento query = searchText-->
<script>
$(document).ready( function(){
$("#set_name").keyup(function(){
var searchText = $(this).val();
if(searchText != '')
{
$.ajax({
url:'php/action.php',
method:'POST',
data:{query_set:searchText},
success:function(data)
{
$("#show-list").fadeIn();
$("#show-list").html(data);
}
});
}
else{
$("#show-list").fadeOut();
$("#show-list").html('');
}
});
$(document).on('click','li',function(){
$("#set_name").val($(this).text());
$("#show-list").fadeOut();
});
});
</script>
<!-- <a href='#' class='list-group-item list-group-item-action'> -->
<div class="col-4">
<div class="form-group">
<input class="form-control" type="text" id="card_name" name="card_name" placeholder="Exact Card Name in English">
<div class="list-group" id="show-list-card">
<!-- Here autocomplete list will be display -->
</div>
</div>
</div>
<!-- script per auto completamento query = searchText-->
<script>
$(document).ready( function(){
$("#card_name").keyup(function(){
var searchText = $(this).val();
if(searchText != '')
{
$.ajax({
url:'php/action.php',
method:'POST',
data:{query_card:searchText},
success:function(data)
{
$("#show-list-card").fadeIn();
$("#show-list-card").html(data);
}
});
}
else{
$("#show-list-card").fadeOut();
$("#show-list-card").html('');
}
});
$(document).on('click','li',function(){
$("#card_name").val($(this).text());
$("#show-list-card").fadeOut();
});
});
</script>
This php code instead is in another file, to select the right value from the database, but i think it is irrilevant to solve the problem.
<?php
require "dbh.php";
if(isset($_POST['query_set'])){
$input_text = $_POST['query_set'];
$sql = "SELECT DISTINCT Set_name FROM card WHERE Set_name LIKE '%$input_text%' ";
$result = $connessione->query($sql);
$output = '<ul class="list-unstyled"';
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$output .= '<a><li>' . $row['Set_name'] .'</li></a>';
}
}
else{
$output .= '<li>Set Not Found</li>';
}
$output .= '</ul>';
echo $output;
}
if(isset($_POST['query_card'])){
$input_text = $_POST['query_card'];
$sql = "SELECT DISTINCT Card_name FROM card WHERE Card_name LIKE '%$input_text%' ";
$result = $connessione->query($sql);
$output = '<ul class="list-unstyled"';
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$output .= '<a><li>' . $row['Card_name'] .'</li></a>';
}
}
else{
$output .= '<li>Card Not Found</li>';
}
$output .= '</ul>';
echo $output;
}

I think that the problem is that:
$(document).on('click','li',function(){
$("#set_name").val($(this).text());
$("#show-list").fadeOut();
});
and its equivalent for #card_name attach events to any li; both of these event handlers will run any time an li is clicked.
I've not used jQuery in a while, but perhaps:
$("#show-list").on('click','li',function(){
$("#set_name").val($(this).text());
$("#show-list").fadeOut();
});
and the equivalent for #card_name would work.

Related

Button click not returning data or initializing modal

I have created a form to display all records from my database with the ability to add a new user, edit, and delete. The delete works fine. However, the add and edit functions are supposed to show a bootstrap modal with either blank fields for the add user, or all the information to edit a user. The modal isn't appearing and I can't understand why. There are no errors displayed in the console. I know I have the correct database configuration since the delete function works.
Driving me crazy :)
I've attached my code to see if anyone knows what I'm missing.
Thanks!!
profile.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Staff Profile Form</title>
<meta charset="utf-8">
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
<script src = "jquery/jquery-3.3.1.js"></script>
<script>
// Update the users data list
function getUsers(){
$.ajax({
type: 'POST',
url: 'userAction.php',
data: 'action_type=view',
success:function(html){
$('#userData').html(html);
}
});
}
// Send CRUD requests to the server-side script
function userAction(type, id){
id = (typeof id == "undefined")?'':id;
var userData = '', frmElement = '';
if(type == 'add'){
frmElement = $("#modalUserAddEdit");
userData =
frmElement.find('form').serialize()+'&action_type='+type+'&id='+id;
}else if (type == 'edit'){
frmElement = $("#modalUserAddEdit");
userData = frmElement.find('form').serialize()+'&action_type='+type;
}else{
frmElement = $(".row");
userData = 'action_type='+type+'&id='+id;
}
frmElement.find('.statusMsg').html('');
$.ajax({
type: 'POST',
url: 'userAction.php',
dataType: 'JSON',
data: userData,
beforeSend: function(){
frmElement.find('form').css("opacity", "0.5");
},
success:function(resp){
frmElement.find('.statusMsg').html(resp.msg);
if(resp.status == 1){
if(type == 'add'){
frmElement.find('form')[0].reset();
}
getUsers();
}
frmElement.find('form').css("opacity", "");
}
});
}
// Fill the user's data in the edit form
function editUser(id){
$.ajax({
type: 'POST',
url: 'userAction.php',
dataType: 'JSON',
data: 'action_type=data&id='+id,
success:function(data){
$('#id').val(data.id);
$('#name').val(data.name);
$('#location').val(data.location);
$('#specialty').val(data.specialty);
}
});
}
// Actions on modal show and hidden events
$(function(){
$('#modalUserAddEdit').on('show.bs.modal', function(e){
var type = $(e.relatedTarget).attr('data-type');
var userFunc = "userAction('add');";
if(type == 'edit'){
userFunc = "userAction('edit');";
var rowId = $(e.relatedTarget).attr('rowID');
editUser(rowId);
}
$('#userSubmit').attr("onclick", userFunc);
});
$('#modalUserAddEdit').on('hidden.bs.modal', function(){
$('#userSubmit').attr("onclick", "");
$(this).find('form')[0].reset();
$(this).find('.statusMsg').html('');
});
});
</script>
</head>
<body>
<?php
// Include and initialize DB class
require_once 'db.php';
$db = new DB();
// Fetch the users data
$users = $db->getRows('monctonfir');
?>
<div class="container">
<div class="row">
<div class="col-md-12 head">
<h5>Users</h5>
<!-- Add link -->
<div class="float-right">
<a href="javascript:void(0);" class="btn btn-success" data-
type="add" data-toggle="modal" data-target="#modalUserAddEdit"><i
class="plus"></i> New User</a>
</div>
</div>
<div class="statusMsg"></div>
<!-- List the users -->
<table class="table table-striped table-bordered">
<thead class="thead-dark">
<tr>
<th>ID</th>
<th>Name</th>
<th>Location</th>
<th>Specialty</th>
<th>Profile Image</th>
<th>Action</th>
</tr>
</thead>
<tbody id="userData">
<?php if(!empty($users)){ foreach($users as $row){ ?>
<tr>
<td><?php echo '#'.$row['id']; ?></td>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['location']; ?></td>
<td><?php echo $row['specialty']; ?></td>
<td><?php echo $row['file']; ?></td>
<td>
UPDATE
DELETE
</td>
</tr>
<?php } }else{ ?>
<tr><td colspan="5">No user(s) found...</td></tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
<!-- Modal Add and Edit Form -->
<div class="modal fade" id="modalUserAddEdit" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Add New User</h4>
<button type="button" class="close" data-dismiss="modal">×
</button>
</div>
<!-- Modal Body -->
<div class="modal-body">
<div class="statusMsg"></div>
<form role="form">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="name" id="name" placeholder="Enter your name">
</div>
<div class="form-group">
<label for="location">Location</label>
<input type="text" class="form-control" name="location" id="location" placeholder="Enter your work site">
</div>
<div class="form-group">
<label for="specialty">Specialty</label>
<input type="text" class="form-control" name="specialty" id="specialty" placeholder="Enter your specialty">
</div>
<input type="hidden" class="form-control" name="id" id="id"/>
</form>
</div>
<!-- Modal Footer -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-success" id="userSubmit">SUBMIT</button>
</div>
</div>
</div>
</div>
</body>
</html>
userAction.php
<?php
// Include and initialize DB class
require_once 'DB.php';
$db = new DB();
// Database table name
$tblName = 'monctonfir';
// If the form is submitted
if(!empty($_POST['action_type'])){
if($_POST['action_type'] == 'data'){
// Fetch data based on row ID
$conditions['where'] = array('id' => $_POST['id']);
$conditions['return_type'] = 'single';
$user = $db->getRows($tblName, $conditions);
// Return data as JSON format
echo json_encode($user);
}elseif($_POST['action_type'] == 'view'){
// Fetch all records
$users = $db->getRows($tblName);
// Render data as HTML format
if(!empty($users)){
foreach($users as $row){
echo '<tr>';
echo '<td>#'.$row['id'].'</td>';
echo '<td>'.$row['name'].'</td>';
echo '<td>'.$row['location'].'</td>';
echo '<td>'.$row['specialty'].'</td>';
echo '<td>edit
delete</td>';
echo '</tr>';
}
}else{
echo '<tr><td colspan="5">No user(s) found...</td></tr>';
}
}elseif($_POST['action_type'] == 'add'){
$msg = '';
$status = $verr = 0;
// Get user's input
$name = $_POST['name'];
$location = $_POST['location'];
$specialty = $_POST['specialty'];
// Validate form fields
if(empty($name)){
$verr = 1;
$msg .= 'Please enter your name.<br/>';
}
if(empty($location) || !filter_var($email, FILTER_VALIDATE_EMAIL)){
$verr = 1;
$msg .= 'Please enter your work site.<br/>';
}
if(empty($specialty)){
$verr = 1;
$msg .= 'Please enter your specialty.<br/>';
}
if($verr == 0){
// Insert data in the database
$userData = array(
'name' => $name,
'location' => $location,
'specialty' => $specialty,
);
$insert = $db->insert($tblName, $userData);
if($insert){
$status = 1;
$msg .= 'User data has been inserted successfully.';
}else{
$msg .= 'Some problem occurred, please try again.';
}
}
// Return response as JSON format
$alertType = ($status == 1)?'alert-success':'alert-danger';
$statusMsg = '<p class="alert '.$alertType.'">'.$msg.'</p>';
$response = array(
'status' => $status,
'msg' => $statusMsg
);
echo json_encode($response);
}elseif($_POST['action_type'] == 'edit'){
$msg = '';
$status = $verr = 0;
if(!empty($_POST['id'])){
// Get user's input
$name = $_POST['name'];
$location = $_POST['location'];
$specialty = $_POST['specialty'];
$location = $_POST['location'];
// Validate form fields
if(empty($name)){
$verr = 1;
$msg .= 'Please enter your name.<br/>';
}
if(empty($location)){
$verr = 1;
$msg .= 'Please enter a your work site.<br/>';
}
if(empty($specialty)){
$verr = 1;
$msg .= 'Please enter your specialty<br/>';
}
if($verr == 0){
// Update data in the database
$userData = array(
'name' => $name,
'location' => $location,
'specialty' => $specialty,
);
$condition = array('id' => $_POST['id']);
$update = $db->update($tblName, $userData, $condition);
if($update){
$status = 1;
$msg .= 'User data has been updated successfully.';
}else{
$msg .= 'Some problem occurred, please try again.';
}
}
}else{
$msg .= 'Some problem occurred, please try again.';
}
// Return response as JSON format
$alertType = ($status == 1)?'alert-success':'alert-danger';
$statusMsg = '<p class="alert '.$alertType.'">'.$msg.'</p>';
$response = array(
'status' => $status,
'msg' => $statusMsg
);
echo json_encode($response);
}elseif($_POST['action_type'] == 'delete'){
$msg = '';
$status = 0;
if(!empty($_POST['id'])){
// Delate data from the database
$condition = array('id' => $_POST['id']);
$delete = $db->delete($tblName, $condition);
if($delete){
$status = 1;
$msg .= 'User data has been deleted successfully.';
}else{
$msg .= 'Some problem occurred, please try again.';
}
}else{
$msg .= 'Some problem occurred, please try again.';
}
// Return response as JSON format
$alertType = ($status == 1)?'alert-success':'alert-danger';
$statusMsg = '<p class="alert '.$alertType.'">'.$msg.'</p>';
$response = array(
'status' => $status,
'msg' => $statusMsg
);
echo json_encode($response);
}
}
exit;
?>
Bootstrap lists modals under components requiring JavaScript (i.e. bootstrap.min.js)
take a look at the docs: https://getbootstrap.com/docs/4.0/getting-started/introduction/
Try adding this before the closing body tag:
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

How to populate li value into another dropdown after you select from first dropdown?

My problem is that I can get the value of the <li> tag from my database but I cannot figure out how I can use it to populate another dropdown using ajax and php? (I am not trying to create a selection dropdown)
I have 2 dropdown list, the first dropdown list is to select MOVIE and the second dropdown list is to select DATE. So when I select MOVIE, the second dropdown list will populate the date of the MOVIE which I select.
I've found a solution that uses the <select> tag and <option> tag. However, this doesn't really solve my problem. What I really want to do is add an image into my dropdown list.
So how can I do this using the <ul> tag and <li> tag in the dropdown list?
Below is my code:
HTML:
////////////////select movie//////////////////
<div class="select_movie" style="float:left;">
<div class="nice-select dropdown-toggle" id="selectmovie" data-toggle="dropdown" tabindex="0" style="margin-left: 200px; margin-top: 29px;"><span class="current">Select Movie</span>
<ul class="dropdown-menu scrollable-menu ul_movie" id="m_movie" >
<?php
$sql = "SELECT id,name,date,time,image FROM movie";
$res = mysqli_query($conn, $sql);
if(mysqli_num_rows($res) > 0) {
while($row = mysqli_fetch_object($res)) {
echo '<li data-value="' . $row->id . '"class="option" style="margin-top:10px; margin-bottom:10px;"><img src="' . $row->image . '" style="width:50px; height:80px; margin-right:10px;">' . $row->name . '</li>';
}
}
?>
</ul>
</div>
</div>
////////////////select date//////////////////
<div class="select_date" style="float:left">
<div class="nice-select dropdown-toggle" data-toggle="dropdown" tabindex="0" style="margin-left: 150px; margin-top: 29px;"><span class="current">Select Date</span>
<ul class="dropdown-menu scrollable-menu ul_date" id="selectdate" >
</ul>
</div>
</div>
Javascript:
<script>
$(document).on('click', '.ul_movie li', function () {
// alert('movie');
var movie_id = $(this).attr('data-value');
console.log(movie_id)
if(movie_id !== "") {
$.ajax({
url:"get_datetime.php",
data:{m_id:movie_id},
type:'POST',
success:function(response) {
// var resp = $.trim(response);
$('.ul_date li').html(response);
}
});
}
else {
$('.ul_date li').html("<li value=''>------- Select --------</li>");
alert("tghhh") ;
}
});
</script>
PHP:
<?php include("database/conn.php"); ?>
<?php
if(isset($_POST['m_id'])) {
$sql = "select `id`,`date` from movie where
`id`='".mysqli_real_escape_string($conn, $_POST['m_id'])."'";
$res = mysqli_query($conn, $sql);
//to test what value given
echo "<option value=''>".$_POST['m_id']."</option>";
if(mysqli_num_rows($res) > 0) {
echo "<option value=''>------- Select --------</option>";
while($row = mysqli_fetch_object($res)) {
// echo "<li data-value='" . $row->id . '"class="option" >' . $row->date . '</li>';
echo "<li data-value='".$row->id."' class='option'>".$row->date."</li>";
}
}
else{
echo "<option value=''>No showing time</option>";
}
} else {
header('location: ./');
}
?>
Use $('#selectdate').html(response); instead of $('.ul_date li').html(response);

PHP search using AJAX with checkbox

How do I let AJAX know what I have checked with checkbox? I have a list of categories that are selected from a database. So how do let the AJAX know what I have checked?
This is my search PHP:
<div class ="search-category-container">
<div class ="search-category-header featured-header">
<label class ="featured-font">category</label>
</div>
<div class ="search-category-content">
<?php
$result=mysqli_query($connection,"SELECT * FROM category");
while($row= mysqli_fetch_array($result)) { ?>
<label class="checkbox category-list ">
<input type="checkbox" name="category_list[]" value="<?php echo $row['name']; ?>" form="search-form"><?php echo $row['name']; ?>
</label>
<?php
}
?>
</div>
</div>
This is my search function using on search before without AJAX. Now I was trying to use AJAX to get data can I use back the function?
<?php
if($filter == "post" && $time == "all" && $status == "all" && isset ($_POST['category_list'])) {
foreach ($_POST['category_list'] as $category) {
$result = mysqli_query($connection, "SELECT * FROM category WHERE name IN ('$category')")or die(mysqli_error($connection));
while($row= mysqli_fetch_array($result)) {
$getCategory = $row['id'];
$getPostIDRow = mysqli_query($connection, "SELECT * FROM post_category WHERE category_id = '$getCategory'") or die(mysqli_error($connection));
while($row2= mysqli_fetch_array($getPostIDRow)) {
$getPostID = $row2['post_id'];
$result2 = mysqli_query($connection,"SELECT * FROM post WHERE title LIKE '%$search%' AND id = '$getPostID'") or die(mysqli_error($connection));
$count2 = mysqli_num_rows($result2);
if($count2>0) {
while($row2= mysqli_fetch_array($result2)) {
$postID = $row2['id'];
$result3 = mysqli_query($connection, "SELECT * FROM user_post WHERE post_id = '$postID'") or die(mysqli_error($connection));
while($row3 = mysqli_fetch_array($result3)) {
$getUserName = mysqli_query($connection, "SELECT * FROM user WHERE id = '".$row3['user_id']."'")or die(mysqli_error($connection));
while($row4 = mysqli_fetch_array($getUserName)) {?>
<div class ="post-container" id="search-container">
<div class ="post-header-container">
<div class ="post-header">
<a href ="post.php?id=<?php echo urlencode($row2['id']);?>&user=<?php echo $row3['user_id']; ?>">
<p class ="post-header-font"><?php echo ($row2['title']); ?></p>
</a>
</div>
<div class ="post-user">
<p class ="faded-font">by : <?php echo $row4['username']; ?></p>
</div>
</div>
<div class ="post-content-container">
<p class ="post-content-font">
<?php echo ($row2['summary']); ?>
</p>
</div>
<div class ="post-info-container">
<div class ="post-info">
<span class ="glyphicon glyphicon-eye-open"> views: <?php echo ($row2['views']);?></span>
</div><div class ="post-info">
<span class ="glyphicon glyphicon-pencil"> answers:</span>
</div><div class ="post-info">
<span class ="glyphicon glyphicon-ok"> status: <?php echo ($row2['status']);?></span>
</div>
</div>
</div><?php
}
}
}
}
}
}
}
?>
This is AJAX search function
$(document).ready(function(){
function search() {
var searchWord = $("#search").val();
var filter = $("#filter:checked").val();
var time = $("#time:checked").val();
var status = $("#status:checked").val();
$.ajax({
type:"post",
url:"searchFunction.php",
data:"search="+searchWord+"&filter="+filter+"&time="+time+"&status="+status,
success:function(data) {
$("#searchContainer").html(data);
$("#search").val("");
}
});
}
$("#searchButton").click(function(){
search();
});
$("#search").keyup(function(e){
if(e.keyCode == 13) {
search();
}
});
});
To answer you ajax question I highly recommend changing your code to use the 'form' DOM for user experience and easier maintenance, just fyi and use the serialize function which will also send out the 'checked' checkboxes.
https://api.jquery.com/serialize/
function search() {
var postData = $('myForm').serialize(); // i.e <form id="myForm">
$.ajax({
type:"post",
url:"searchFunction.php",
data: postData,
success:function(data) {
$("#searchContainer").html(data);
$("#search").val("");
}
});
}
That will do all the work for you automatically instead of having to run a bunch of jQuery selection calls and putting together the HTTP query your self. If you ever need to know what your ajax is running. Go in inspector mode of your browser and look for "Network" tab, click that and you should see the ajax call to that search file, with everything you need to know. What HTTP request and response headers are and body.
P.s make sure you return false on the submit event and that the name of the fields on your HTML form match the $_POST key names for the ajax.
$("#myForm").on('submit', function(){
search();
return false;
});
Good luck!

PHP + MYSQL instant search with radio button filtering

I have with the help of this guide https://www.youtube.com/watch?v=_AqM9U3mi9A created a working search form that displays instant search results (without having to press submit button) with PHP and MYSQL.
Then I wanted to filter the search results depending on what radio button is pressed. Now I also got this to work (partly with the help of this guide https://www.youtube.com/watch?v=DVS4qoB98U8) but ONLY when pressing submit on my search form. It does not work with instant search results for some reason, and that is my problem.
index.php (form):
<form class="form-custom" role="search" action="index.php" method="POST">
<div class="form-group">
<label for="all" class="radio-btn">
<input id="all" class="radio-custom" type="radio" name="searchfilter" value="all" checked="checked"> ALL
</label>
<label for="sports" class="radio-btn">
<input id="sports" class="radio-custom" type="radio" name="searchfilter" value="sports"> SPORTS
</label>
<label for="e-sports" class="radio-btn">
<input id="e-sports" class="radio-custom" type="radio" name="searchfilter" value="e-sports"> E-SPORTS
</label>
<label for="show-business" class="radio-btn">
<input id="show-business" class="radio-custom" type="radio" name="searchfilter" value="show-business"> SHOW BUSINESS
</label>
</div>
<div class="form-group">
<input type="text" name="search" autocomplete="off" class="form-control form-control-custom" placeholder="Search..." onkeyup="searchq();">
<button type="submit" name="submit" value="" class="btn btn-default btn-form-custom">Submit</button>
</div>
</form>
<div class="test" id="output">
<!-- this is where instant search results are supposed to appear -->
</div>
index.php (jquery - requiered for instant search results to work):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
$.post("search.php",{searchVal: searchTxt}, function(output){
$("#output").html(output);
});
}
</script>
search.php (PHP code):
<?php
include_once("connect.php");
$output = '';
if (isset($_POST['searchVal']) && isset($_POST['searchfilter']) && trim($_POST['searchVal']) != '' && strlen('searchVal') > 3 ){
$searchq = $_POST['searchVal'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
if($_POST['searchfilter'] == "all") {
$sqlCommand = "(SELECT * FROM sports WHERE Title LIKE '%$searchq%') UNION (SELECT * FROM e_sports WHERE Title LIKE '%$searchq%') UNION (SELECT * FROM show_business WHERE Title LIKE '%$searchq%')";
} else if($_POST['searchfilter'] == "sports") {
$sqlCommand = "SELECT * FROM sports WHERE Title LIKE '%$searchq%'";
} else if($_POST['searchfilter'] == "e-sports") {
$sqlCommand = "SELECT * FROM e_sports WHERE Title LIKE '%$searchq%'";
} else if($_POST['searchfilter'] == "show-business") {
$sqlCommand = "SELECT * FROM show_business WHERE Title LIKE '%$searchq%'";
}
$query = mysql_query($sqlCommand) or die(mysql_error());
$count = mysql_num_rows($query);
if($count == 0){
$output .= '<p class="p-nof">No results found</p>';
}else{
$output .= '<ul ="dropdown">';
$output .= '<p>Search results: '.$count.'</p>';
while($row = mysql_fetch_array($query)){
$title = $row['Title'];
$url = $row['url'];
$id = $row['id'];
$output .= '<a class="searchresult" href="'.$url.'"><li> '.$title.'</li></a>';
}
$output .= '</ul>';
}
}
echo($output);
?>
Thanks in advance for any help!
EDIT:
I changed the javascript to the following:
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
var searchFilter = $("input[name='searchfilter']").val();
$.post("search.php",{searchVal: searchTxt, searchfilterVal: searchFilter}, function(output){
$("#output").html(output);
});
}
</script>
With this change the instant search results are working like before but the radio button filtering is not working. It seems that it's only using the data from the first radio input and ignoring the rest. When I click the other radio buttons it continues to use the data from the one listed first in the form. It does not change as I click.
I still need help with this! Thanks in advance!
Adjust your JS to post the value of searchFilter
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
var searchFilter = $("input[name='searchfilter']").val();
$.post("search.php",{searchVal: searchTxt, searchFilter: searchfilter}, function(output){
$("#output").html(output);
});
}
</script>

AJAX comment system Validation problems

So i am haveing this page where it is displaying articles andunderneet each article it will have a textarea asking allowing the user to insert a comment.I did the AJAX and it works fine.Some of the validation works fine aswell(Meaning that if the textarea is left empty it will not submit the comment and display an error).The way i am doing this validation is with the ID.So i have multi forms with the same ID.For the commets to be submited it works fine but the validtion doesnt work when i go on a second form for exmaple it only works for the first form
AJAX code
$(document).ready(function(){
$(document).on('click','.submitComment',function(e) {
e.preventDefault();
//send ajax request
var form = $(this).closest('form');
var comment = $('#comment');
if (comment.val().length > 1)
{
$.ajax({
url: 'ajax_comment.php',
type: 'POST',
cache: false,
dataType: 'json',
data: $(form).serialize(), //form serialize data
beforeSend: function(){
//Changeing submit button value text and disableing it
$(this).val('Submiting ....').attr('disabled', 'disabled');
},
success: function(data)
{
var item = $(data.html).hide().fadeIn(800);
$('.comment-block_' + data.id).append(item);
// reset form and button
$(form).trigger('reset');
$(this).val('Submit').removeAttr('disabled');
},
error: function(e)
{
alert(e);
}
});
}
else
{
alert("Hello");
}
});
});
index.php
<?php
require_once("menu.php");
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script src="comments.js" type="text/javascript" ></script>
<?php
$connection = connectToMySQL();
$selectPostQuery = "SELECT * FROM (SELECT * FROM `tblposts` ORDER BY id DESC LIMIT 3) t ORDER BY id DESC";
$result = mysqli_query($connection,$selectPostQuery)
or die("Error in the query: ". mysqli_error($connection));
while ($row = mysqli_fetch_assoc($result))
{
$postid = $row['ID'];
?>
<div class="wrapper">
<div class="titlecontainer">
<h1><?php echo $row['Title']?></h1>
</div>
<div class="textcontainer">
<?php echo $row['Content']?>
</div>
<?php
if (!empty($row['ImagePath'])) #This will check if there is an path in the textfield
{
?>
<div class="imagecontainer">
<img src="images/<?php echo "$row[ImagePath]"; ?>" alt="Article Image">
</div>
<?php
}
?>
<div class="timestampcontainer">
<b>Date posted :</b><?php echo $row['TimeStamp']?>
<b>Author :</b> Admin
</div>
<?php
#Selecting comments corresponding to the post
$selectCommentQuery = "SELECT * FROM `tblcomments` LEFT JOIN `tblusers` ON tblcomments.userID = tblusers.ID WHERE tblcomments.PostID ='$postid'";
$commentResult = mysqli_query($connection,$selectCommentQuery)
or die ("Error in the query: ". mysqli_error($connection));
#renderinf the comments
echo '<div class="comment-block_' . $postid .'">';
while ($commentRow = mysqli_fetch_assoc($commentResult))
{
?>
<div class="commentcontainer">
<div class="commentusername"><h1>Username :<?php echo $commentRow['Username']?></h1></div>
<div class="commentcontent"><?php echo $commentRow['Content']?></div>
<div class="commenttimestamp"><?php echo $commentRow['Timestamp']?></div>
</div>
<?php
}
?>
</div>
<?php
if (!empty($_SESSION['userID']) )
{
?>
<form method="POST" class="post-frm" action="index.php" >
<label>New Comment</label>
<textarea id="comment" name="comment" class="comment"></textarea>
<input type="hidden" name="postid" value="<?php echo $postid ?>">
<input type="submit" name ="submit" class="submitComment"/>
</form>
<?php
}
echo "</div>";
echo "<br /> <br /><br />";
}
require_once("footer.php") ?>
Again the problem being is the first form works fine but the second one and onwaord dont work properly
try this:
var comment = $('.comment',form);
instead of
var comment = $('#comment');
That way you're targeting the textarea belonging to the form you're validating
ps.
remove the id's from the elements or make them unique with php, all element id's should be unique

Categories