mysql ajax search query - php

hello friends i am making a live search with the help of ajax and mysql. the problem is that when we write something suppose a alphabet "a" then it gives live results but when i put a space and then write any alphabet suppose "a" then results does no shows up . how can we ignore the spaces in the search ?? my code is
ajax search.php
<script type="text/javascript">
$(document).ready(function(){
$(".search").keyup(function()
{
var searchbox = $(this).val();
var dataString = 'searchword='+ $.trim(searchbox);
if(searchbox=='')
{
$('#display123').hide();
}
else
{
$.ajax({
type: "POST",
url: "friends/search1.php",
data: dataString,
cache: false,
success: function(html)
{
$("#display123").html(html).show();
}
});
}return false;
});
});
</script>
mysql search1.php
<?php include($_SERVER["DOCUMENT_ROOT"]."/sexy/include/connection.php");
if($_POST)
{
$q=$_POST['searchword'];
$sql_res=mysql_query("select * from users_profile where fname like '%$q%' or Email like '%$q%' order by rand() LIMIT 10");
while($row=mysql_fetch_array($sql_res))
{
$fname=$row['fname'];
$lname=$row['lname'];
$img=$row['profile_pic'];
$country=$row['country'];
$uid=$row['uid'];
$re_fname='<b>'.$q.'</b>';
$re_lname='<b>'.$q.'</b>';
$final_fname = str_ireplace($q, $re_fname, $fname);
$final_lname = str_ireplace($q, $re_lname, $lname);
?>
<div class="display_box" >
<span><img src="<?php echo $img; ?>" width="50" height="50" style="float:left; margin-right:6px" /></span>
<div class="searchtext"><a href="profile.php?f_id=<?php echo $uid;?>"><?php echo $final_fname; ?> <br/>
<span style="font-size:10px; color:#999999"><?php echo $country; ?></span></a></div></div>
<?php
}
}
else
{
}
?>

You can trim whitespaces before using the variable in query, like:
$q= trim($_POST['searchword']); //remove whitespaces from front and end

Related

How to get the output using ajax when the Double outputs displayed one for PHP Echo and another for Ajax request?

I successfully fetch the data from the database. The problem is that, I want to display the results using Ajax request. The results/Output which displayed twice, I mean the *first output which displayed through Ajax (#the bottom of index.php), and the Second output displayed through PHP ECHO (**#**the bottom of the page). What can I do to get a single output through Ajax without adding another file and without refreshing the page?
index.php
<head>
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<script type="text/javascript" src="javas.js"></script>
</head>
<body>
<div id="table_content"></div>
<?php
include ("db.php");
error_reporting(~E_NOTICE);
function ShowForm($AnswerCommentId) {
echo '<form id="myForm">';
echo '<input id="user" name="user" />';
echo '<textarea id="text" name="text"></textarea>';
echo sprintf('<input id="ParentId" name="ParentId" type="hidden" value="%s"/>', ($AnswerCommentId));
echo '<button type="button" OnClick=SendComment()>Comment</button>';
echo '</form>';
}
$query="SELECT * FROM `comm` ORDER BY id ASC";
$result = mysqli_query($conn,$query);
if (isset($_REQUEST['AnswerId'])) $AnswerId = $_REQUEST['AnswerId'];
else $AnswerId = 0;
$i=0;
while ($mytablerow = mysqli_fetch_row($result)){ $mytable[$i] = $mytablerow; $i++; }
function tree($treeArray, $level, $pid = 0) {
global $AnswerId;
foreach($treeArray as $item){
if ($item[1] == $pid){
echo sprintf('<div class="CommentWithReplyDiv" style="margin-left:%spx;">',$level*60);
echo sprintf('<p>%s</p>', $item[2]);
echo sprintf('<div>%s</div>', $item[3]);
if ($level<=2) echo sprintf('Reply', $item[0]);
if ($AnswerId == $item[0]) echo sprintf('<div id="InnerDiv">%s</div>', ShowForm($AnswerId));
echo '</div><br/>';
tree($treeArray, $level+1, $item[0]); // Recursion
}
}
}
tree($mytable,0,0);
?>
Comment
<div id="MainAnswerForm" style="display:none;width:40%; margin:0 auto;"><?php ShowForm(0); ?></div>
<div id="AfterMainAnswerForm"></div>
<script>
$(document).ready(function(){
$("#Link").click(function () {
$("#InnerDiv").remove();
$("#MainAnswerForm").slideToggle("normal");
return false;
});
});
</script>
</body>
Page.php
<?php
include ("db.php");
$user = $_POST['user'];
$text = $_POST['text'];
$ParentId = $_POST['ParentId'];
$action = $_POST['action'];
if ($action=="add") $query= mysqli_query($conn,"INSERT into `comm` VALUES (NULL,'{$ParentId}','{$user}','{$text}',NOW())");
?>
Javas.js
function show_messages(){
$.ajax({
url: "index.php",
cache: false,
success: function(html){
$("#table_content").html(html);
}
});
}
function AnswerComment (id){
$.ajax({
type: "POST",
url: "index.php",
data: "AnswerId="+id,
success: function(html){
$("#table_content").html(html);
}
});
}
function SendComment (){
var user1 = $("#user").val();
var text1 = $("#text").val();
var ParentId1 = $("#ParentId").val() + "";
$.ajax({
type: "POST",
url: "page.php",
data: "user="+user1+"&text="+text1+"&ParentId="+ParentId1+"&action=add",
success: function(html){
show_messages();
}
});
return false;
}
OK I think its more simple than you think
while you're using .html() it should change all the content of your div but while you're using <div id="table_content"></div> then the <?php ?> your code will show both - one appended to the div and under it the one which echoed by php ... so instead of using
<div id="table_content"></div>
<?php ?>
just wrap the <?php ?> inside the div
<div id="table_content">
<?php ?>
</div>
Alternative way: by using jquery wrapAll() but while Id must be unique you'll need to .remove() the #table_content element first then wrap all your code inside a new #table_content div .. see the example below
$(document).ready(function(){
$('#table_content').remove();
$('.CommentWithReplyDiv').wrapAll('<div id="table_content"></div>');
});
#table_content{
margin : 50px;
background : red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="table_content"></div>
<div class="CommentWithReplyDiv">1</div>
<div class="CommentWithReplyDiv">2</div>
<div class="CommentWithReplyDiv">3</div>
<div class="CommentWithReplyDiv">4</div>

Retrieve and display multiple and different mysql queries using jquery ajax

I have several div tags that I would like to be updated with several different mysql queries.
My code below only updates one of these divs, how can I expand it to 1-6 and also leave room for expansion in the future for more divs?
I also need to be able to update each div individually with a specific query for a specific table.
<html>
<div id="1"> </div>
<div id="2"> </div>
<div id="3"> </div>
<div id="4"> </div>
<div id="5"> </div>
<div id="6"> </div>
//...and so on
</html>
<script type="text/javascript">
$(document).ready(function () {
function display($id) {
$.ajax({
async: false,
type: "POST",
url: "apifile.php",
data: {id:$id},
dataType: "json",
success: function(msg) {
if(msg.success) {
$($id).next(".one").html(msg);
} else {
alert("error");
}
}
});
}
</script>
<?php
mysql_connect(host, user, pass);
mysql_select_db(name);
mysql_query("select round((count(*)*100)/(select count(*) from test),1) as percent from test group by field1 order by percent desc");
$reply['success'] = "Success";
if($return = display($id)) {
$reply['success'] = "Success";
} else {
$reply['error'] = "Error";
}
echo json_encode($reply);
?>
you can store the data/messages/otherinfo from each query in different portions of your $reply array
query1 goes here ...
$reply[1]['success'] = "Success";
if($return = display($id)) {
$reply[1]['success'] = "Success";
} else {
$reply[1]['error'] = "Error";
}
query2 goes here ...
$reply[2]['success'] = "Success";
$reply[2]['data'] = "3,4,5";
query3 goes here ...
$reply[3]['success'] = "Success";
$reply[3]['data'] = "beans,soup,guac";
echo json_encode($reply);
You can add a class to the div and run the ajax on class
$( ".div" ).each(function() {
var div_id = $(this).attr('id');
display(div_id);
});

Append content to div via jquery

My project is a kind of blog, with posts and comments area. I'm trying to make it async with jquery ajax. My problem is that when a new comment gets inserted asynchronously it appears in the div twice, and all the other comments disappear. If i refresh the page it looks fine.
VIEW:
<section id="comments_section_<?php echo $p1['post_id'];?>"> //THIS IS THE OUTPUT WHERE NEW COMMENTS WILL BE APPENDED
<?php
$data['comments'] = $this->model_mutamba->getComments($p1['post_id']);
if($data['comments'] != ""){ ?>
<div class="comments_container" id="comments_container_<?php echo $p1['post_id'];?>">
<?php foreach ($data['comments'] as $c){
$user_img3 = $this->model_mutamba->getUserPicId($c->aluno_id);
?>
<div>
<img style="height:32px;" src="<?php echo site_url();?>img/users/portfolio/<?php echo $user_img3;?>" alt="" class="align-left" />
<p>
<?php echo $this->model_mutamba->addSmilies($c->comment);?>
<br>
<span class="comments_date">
<?php
$c_date = explode('-', substr($c->comment_date,0,-8));
$date_num_word = monthNumToWords($c_date[1]);
echo substr($c->comment_date, 11,-3)." ".$c_date[2]." de ". $date_num_word . " ". $c_date[0];?>
</span>
</p>
</div>
<?php } ?>
</div>
<?php } ?>
</section>
JS:
function comment(post_id,input){
var comment = $(input).val();
var output = '#comments_section_'+post_id;
if(comment != ""){
$.ajax({
type:"POST",
url:base_url+"mutamba/insertNewComment",
data: {comment: comment, post_id:post_id},
cache:false,
success:function(response){
$(output).html(response);
$(output).append(response);
}
});
}
}
CONTROLLER:
function insertNewComment(){
if($this->session->userdata('is_logged_in')){
$email= $this->session->userdata('email');
$comment= $this->FilterData($this->input->post('comment'));
$post_id= $this->FilterData($this->input->post('post_id'));
$this->load->model('model_mutamba');
if($this->model_mutamba->insertNewComment($email,$comment,$post_id)){
$this->load->model('model_user');
$count = $this->model_mutamba->countPostComments($post_id);
?>
<script>
var count = '<?php echo $count;?>';
var comments_count = '<?php echo "#comments_count_".$post_id;?>';
var content = "";
if(count == 1){
content = '<span class="comments_count">'+count+'</span> Comentário';
}else{
content = '<span class="comments_count">'+count+'</span> Comentários';
}
$(comments_count).html(content);
</script>
<?php
$this->load->model('model_user');
$user_img = $this->model_user->getUserPic($email);
echo '
<div>
<img style="height:32px;" src="'.site_url().'img/users/portfolio/'.$user_img.'" alt="" class="align-left" />
<p>
'.$this->model_mutamba->addSmilies($comment).'
<br>
<span class="comments_date">';
$date = date(date('Y-m-d H:i:s'));
$c_date = explode('-', substr($date,0,-8));
$date_num_word = monthNumToWords($date[1]);
echo substr($date, 11,-3)." ".$c_date[2]." de ". $date_num_word . " ". $c_date[0].'
</span>
</p>
</div>';
}
}else{
redirect("inicio");
}
}
Will appreciate any help,
Thanks in advance
This is happening because in your AJAX success callback, you are adding response to the output TWICE - once with .html() and then again with .append().
.html(response) removes the previous HTML in your webpage, thats why you dont see other comments and it adds response to it.
With .append(response), it is adding response to the bottom of the div, that is the reason you are seeing the response twice!
Remove $(output).html(response) from the success callback and it will work fine.
So, your function needs to look like this:
function comment(post_id,input){
var comment = $(input).val();
var output = '#comments_section_'+post_id;
if(comment != ""){
$.ajax({
type:"POST",
url:base_url+"mutamba/insertNewComment",
data: {comment: comment, post_id:post_id},
cache:false,
success:function(response){
$(output).append(response);
}
});
}
}
function comment(post_id,input){
var comment = $(input).val();
var output = '#comments_section_'+post_id;
if(comment != ""){
$.ajax({
type:"POST",
url:base_url+"mutamba/insertNewComment",
data: {comment: comment, post_id:post_id},
cache:false,
success:function(response){
//$(output).html(response); //Comment this line or the line below it.
$(output).append(response);
}
});
}
}
<div id="appenddiv">
<h1>append</h1>
</div>
<script type="text/javacript">
$("#appenddiv").append('<b>hello world</b>');
</script>

ajax a href onclick get php variable and execute php file

Before I ask this question, I have already referred to the example of this question. However, it seems doesn't work. Without using ajax, I can get my post deleted but after implement ajax, the deleteAtc.php seems to be not working.
My delete page code (delete.php)
<h4>Select an Article to Delete:</h4>
<?php foreach ($articles as $article) { ?>
<span><?php echo $article['article_title']; ?></span> Delete<br />
<script type="text/javascript">
$(function(){
$('#link').click(function(){
var id = <?php echo $article['article_id']; ?>;
$.ajax({
type: "GET",
url: "deleteAtc.php",
data: "id"+id+,
sucess: function() {
$('#sucess').html(data);
}
})
return false;
});
});
</script>
<div id="success"></div><br />
<?php } ?>
While my deleteAtc.php code:
<?php
session_start();
include_once('../includes/connection.php');
if (isset($_SESSION['logged_in'])) {
if (isset($_GET['id'])) {
$id = $_GET['id'];
$query = $pdo->prepare('DELETE FROM articles WHERE article_id = ?');
$query->bindValue(1, $id);
$query->execute();
echo "Article deleted";
}
}
?>
What I'm trying to do here is to delete the record without redirect to deleteAtc.php, it will remove out the record and replace Article Deleted
May I know where did I go wrong in ajax side?
Please refer below for updated question
Based on the answer below, here is my updated code:
delete.php
<h4>Select an Article to Delete:</h4>
<div id="message"></div>
<?php foreach ($articles as $article) { ?>
<span><?php echo $article['article_title']; ?></span>
Delete<br />
<?php } ?>
script
<script type="text/javascript">
$(function(){
$('.link').click(function(){
var elem = $(this);
$.ajax({
type: "GET",
url: "deleteAtc.php",
data: "id="+elem.attr('data-artid'),
dataType:"json",
success: function(data) {
if(data.success){
elem.hide();
$('#message').html(data.message);
}
}
});
return false;
});
});
</script>
deleteAtc.php
<?php
session_start();
include_once('../includes/connection.php');
if (isset($_SESSION['logged_in'])) {
if (isset($_GET['id'])) {
$id = $_GET['id'];
$query = $pdo->prepare('DELETE FROM articles WHERE article_id = ?');
$query->bindValue(1, $id);
$query->execute();
//Also try to handle false conditions or failure
echo json_encode(array('success'=>TRUE,'message'=>"Article deleted"));
}
}
?>
Somehow, if I delete two record at a time, only the first record echo the result, the second result deleted doesn't echo out the result.
Am wondering, possible to add jquery animation to .show the success message and .hide the record deleted?
First of all IDs are not meant to be duplicated, use class selector instead. Also you could make use of custom data attributes to store the id of the article.
Try
<h4>Select an Article to Delete:</h4>
<div id="message"></div>
<?php foreach ($articles as $article) { ?>
<span><?php echo $article['article_title']; ?></span>
Delete<br />
<?php } ?>
Script
<script type="text/javascript">
$(function(){
$('.link').click(function(){
var elem = $(this);
$.ajax({
type: "GET",
url: "deleteAtc.php",
data: "id="+elem.attr('data-artid'),
dataType:"json",
success: function(data) {
if(data.success){
elem.hide();
$('#message').html(data.message);
}
}
});
return false;
});
});
</script>
And in server side
<?php
session_start();
include_once('../includes/connection.php');
if (isset($_SESSION['logged_in'])) {
if (isset($_GET['id'])) {
$id = $_GET['id'];
$query = $pdo->prepare('DELETE FROM articles WHERE article_id = ?');
$query->bindValue(1, $id);
$query->execute();
//Also try to handle false conditions or failure
echo json_encode(array('success'=>TRUE,'message'=>"Article deleted"));
}
}
?>
The above script won't work you have to change like below. You are repeating the same identifier function again and again. Keep the jquery script out of foreach loop. You have to add the class property with the article id.
<h4>Select an Article to Delete:</h4>
<?php foreach ($articles as $article) { ?>
<span><?php echo $article['article_title']; ?></span> <a href="#" id="link" class='<?php echo $article['article_id']; ?>' >Delete</a><br />
<div id="success"></div><br />
<?php } ?>
<script type="text/javascript">
$(function(){
$('#link').click(function(){
var id = $(this).prop('class');
$.ajax({
type: "GET",
url: "deleteAtc.php",
data: "id="+id,
sucess: function() {
$('#sucess').html(data);
}
})
return false;
});
});
</script>
You create several links with id="link". ID must be unique.
You have to write
id="link<? echo $article['article_id']; ?>"
as well as
$('#link<? echo $article["article_id"]; ?>').click(function() {...})
<script language="javascript">
$(document).ready(function() {
$(".delbutton").click(function(){
var element = $(this);
var del_id = element.attr("id");
var info = 'id=' + del_id;
if(confirm("Sure you want to delete this record? There is NO undo!"))
{
$.ajax({
type: "GET",
url: "products/delete_record.php",
data: info,
cache: false,
success: function(){
setTimeout(function() {
location.reload('');
}, 1000);
}
});
$(this).parents(".record").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow");
}
return false;
//location.reload();
});
});
</script>

Issue with AJAX "load more" button: disappears once clicked

EDIT: thanks everyone for your help. It still doesn't work though.
This script works fine if i change the table to an ordered list. (tr = ol and td = li) That's why i really think the issue comes from the append part of the code. Any ideas?
Everything seems to work fine except for the "load more" button that disappears after it's been clicked. The new posts load but the users cannot click on the button again to load more posts. I've looked on SO but couldn't find a fix for my issue.
If I remove this line:
$("#more"+ID).remove();
then the button does show up but the gif image keeps on loading forever and the button is not clickable...
Here's the index.php code:
<table id="update_list" >
<tbody>
<?php
$result=query("SELECT * FROM postlist ORDER BY postid DESC LIMIT 9");
foreach ($result as $row)
{
$postid=$row['postid'];
$post=$row['post'];
?>
<tr id="<?php echo $postid ?>">
<td>
<?php echo $post; ?>
</td>
</tr>
<?php } ?>
</tbody>
</table>
<div id="more<?php echo $postid; ?>" class="morebox">
more
</div>
</div>
</body>
<script type="text/javascript">
$(function() {
$('.more').live("click",function()
{
var ID = $(this).attr("id");
if(ID)
{
$("#more"+ID).html('<img src="/loading.gif" />');
$.ajax({
type: "POST",
url: "loadmore.php",
data: "lastpost="+ ID,
cache: false,
success: function(html){
$("#update_list >tbody").append(html);
$("#more"+ID).remove();
}
});
}
else
{
$(".morebox").html('The End');
}
return false;
});
});
</script>
</html>
Here is the loadmore php page:
<?php
include("includes/config.php");
if(isset($_POST['lastpost']))
{
$lastpost=$_POST['lastpost'];
$result=query("SELECT * from postlist WHERE postid < '$lastpost' ORDER BY postid DESC
LIMIT 5");
foreach ($result as $row){
$postid=$row['postid'];
$post=$row['post'];
?>
<tr id="<?php echo update$postid ?>">
<td>
<?php echo $post; ?>
</td>
</tr>
<?php } ?>
<div id="more<?php echo $postid; ?>" class="morebox">
more
</div>
<?php }?>
Any tips on what i'm doing wrong here ?
Thanks !
Try this:
$(function() {
$('.more').live("click",function()
{
var ID = $(this).attr("id");
if(ID)
{
$("#more"+ID).find("a").hide().insertAfter('<img src="/loading.gif" />'); //hide a link and insert image after it
$.ajax({
type: "POST",
url: "loadmore.php",
data: "lastpost="+ ID,
cache: false,
success: function(html){
$("#update_list >tbody").append(html);
$("#more"+ID).find("img").remove(); // remove img
$("#more"+ID).find("a").show(); //and show link
}
});
}
else
{
$(".morebox").html('The End');
}
return false;
});
});
You are removing the load more button after button clicked
$("#update_list >tbody").append(html);
//$("#more"+ID).remove(); remove this line

Categories