Jquery(Autocomplete) return query from php - javascript

I have a small problem that I'm not quite sure what the solution would be.
I'm doing an autoComplete using Jquery, I have a php file that takes the data from the database and leaves it in a format that I need like this in the image below.
http://prntscr.com/hgxjsc
in my html I have the following code
<input type="text" id="input_produto" value="" name="input_produto" placeholder="Produto" class="span4 m-wrap">
for better visualization by identation issue
http://prntscr.com/hgxo8z
Anyone who can help in any way, I'll be grateful, I'm new to this area. If you have an example of how to do it, better yet ... Thank you in advance
Excuse me, my English is not very good either.

I would recommend following these steps in order.
For php code;
<?php
//database configuration
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'codexworld';
//connect with the database
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
//get search term
$searchTerm = $_GET['term'];
//get matched data from skills table
$query = $db->query("SELECT * FROM skills WHERE skill LIKE '%".$searchTerm."%' ORDER BY skill ASC");
while ($row = $query->fetch_assoc()) {
$data[] = $row['skill'];
}
//return json data
echo json_encode($data);
?>
For Jquery code;
<script>
$(function() {
$( "#skills" ).autocomplete({
source: 'search.php'
});
});
</script>
For example Html code;
<div class="ui-widget">
<label for="skills">Skills: </label>
<input id="skills">
</div>
Good luck.

Related

Ajax And PHP : Handling Multiple Posts in A Single Page

I am developing a webpage where multiple posts from the Database is shown one by one in a single page much like twitter or facebook.
I need to use Ajax for comments and likes. The comment system should be nested as well.
The problem I am having is each post is having a unique post_id and I need to transfer it through Ajax for inserting the comments into the DB.
The below HTML is inside a PHP for loop for getting the posts from Database. So I have given post_id as every comment element's id to get the unique post comment.
<script>
function addcomment(abc) {
var temp1 = abc;
var post_id = temp1.value; // POST ID
var comment = document.getElementById(post_id).value;
$.ajax({
type: "POST",
url: "addcomment.php",
data: {
post_id:post_id,
comment:comment
},
success: function(response) {
document.getElementsByClassName(post_id).innerHTML = response;
}
});
}
</script>
<div class="comment_section" id="comment_section">
<textarea type="text" id="<?php echo($post_id); ?>" placeholder="comment Here..." value=""></textarea>
<button id="comment_button" value="<?php echo ($post_id); ?>" onclick="return addcomment(this);">Comment</button>
<br>
<span class="<?php echo($post_id); ?>"></span>
</div>
And the addcomment.php looks like this:
<?php
include("connect.php");
$postid = $_POST['post_id'];
$comment = $_POST['comment'];
$sql1 = "INSERT INTO comments (name,comment) VALUES ('$postid','$comment')";
$result = $db->query($sql1);
$sql = "SELECT * FROM comments ORDER BY id DESC LIMIT 0,1";
$result1 = $db->query($sql);
while($row = $result1->fetch_assoc()) {
$post = $row['name'];
$comment_op = $row['comment'];
?>
<?php echo $comment_op; ?>
<br>
<?php echo $post; ?>
<?php } ?>
How can I get the comment when the Comment button clicked and store it in the DB and return the Comment below the comment area using AJAX ?
For display comments on specific post first you create comment section and use
<section id="comments-post_id"></section>
when you successfully add comment via above ajax request code get the response and create comment html and append in your comment section.
$("#comments-post_id").html($response);
make sure you have already create your comment HTML in controller or in ajax file where you get the response.
and for the rendering all post data user inside loop or recursive function to get all comments of your specific post
Need more help feel free and ask :)

PHP doesn't output error from mysql query for non-existent rows for autocomplete

I have a form that currently is able to auto complete base on user input, it queries the MySQL database and successfully lists all possible matches in the table and give suggestions. Now I want to handle rows that do not exist. I am having trouble to get my PHP file to echo the error. Here is what I have so far:
I'm guessing in my auto search function in my javascript in main.php I need to return the error message to the page?
search.php
<?php
//database configuration
$host = 'user';
$username = 'user';
$password = 'pwd';
$name = 'name';
//connect with the database
$dbConnection = new mysqli($host,$username,$password,$name);
if(isset($_GET['term'])){
//get search term
$searchTerm = '%'.$_GET['term'].'%';
//get matched data from skills table
if($query = $dbConnection->prepare("SELECT * FROM nametbl WHERE name LIKE ? ORDER BY name ASC")) {
$query->bind_param("s", $searchTerm);
$query->execute();
$result = $query->get_result();
//$row_cnt = $result->num_rows;
//echo $row_cnt;
if($result -> num_rows){
while ($row = $result->fetch_assoc()) {
$data[] = $row['name'];
}
//return json data
echo json_encode($data);
mysqli_close($dbConnection);
}
else { echo '<pre>' . "there are no rows." . '</pre>'; }
}
else {
echo '<pre>' . "something went wrong when trying to connect to the database." . '</pre>';
}
}
?>
main.php
<div id="gatewayInput">
<form method="post">
<input type="text" id="name" name="name" placeholder="Name..."><br><br>
<?php
include("search.php");
?>
</div>
...
...
...
<script src ="../../../jqueryDir/jquery-3.2.1.min.js"></script>
<script src ="../../../jqueryDir/jquery-ui.min.js"></script>
<script type="text/javascript">
//auto search function
$(function() {
$( "#name" ).autocomplete({
source: 'search.php'
});
});
1.your method type is post in the form
in main.php
and in the search.php, you have used "if(isset($_GET['term'])){"
this needs to be fixed I guess. either both needs to be POST or GET.
Again you are using include method which the whole code in search.php will be made in-line and treated as a one file main.php. so you need not use GET or Post method.
How does get and Post methods work is
3.1) you have a html or PHP which submits the data from browser(main.php), and this request is being served by an action class(search.php)
example :- in main.php
3.2) now in search.php you can use something like if(isset($_POST['term'])){
You can use num_rows (e.g. if ($result -> num_rows)) to see if the query returned anything.

Autocomplete jQuery not working on live server

I'm using jquery UI autocomplete for a search on my site. It's working properly without any problems while is on localhost. But on the live server it doesn't get any results. I have reviewed many posts on this topic, but I am still stymied as to why this doesn't work. I don't know if I can tell you the name of web hosting I use or not.
HTML code: index.php
<input type="text" placeholder="" name="ser" class="form-control" id="hotels" value="" required />
javascript code
<script type="text/javascript">
$(function() {
$( "#hotels" ).autocomplete({
source: 'scripts/chresults.php'
});
});
</script>
chresults.php
<?php
$dbHost = '';
$dbUsername = '';
$dbPassword = '';
$dbName = '';
//connect with the database
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
//get search term
$searchTerm = $_GET['term'];
//get matched data from skills table
$query = $db->query("SELECT * FROM hotels WHERE hotel LIKE '%".$searchTerm."%' or hotelen LIKE '%".$searchTerm."%' or city LIKE '%".$searchTerm."%'limit 5") or die ('mysql_error');
while ($row = $query->fetch_assoc())
{
$results['city'] = $row['city'];
$results[] = $row['hotel'].' , '.$row['city'];
}
//return json data
$json_string = json_encode($results, JSON_PRETTY_PRINT);
echo $json_string;
?>

Creating a unique variable for data

Hi guys so i have created a simple comment box for my site now. It works perfectly, however the problem i am having is that i have different pages which are going to require different comment box. I cant seem to figure out how to get the comment box to be unique for every page. So right now my database holds this :
Called comments:
id
comment
comment1
comment_date
Now my idea is that everything was stored into comment, so i added comment1 for other page to store the info. However i have no clue how to edit the php file to get it to work with comment1. Any help on this would be great.
HTML:
<div class="comment_container">
<div class="comments">
<?php
include_once("comments.php");
?>
</div>
<div class="comments_form">
<table>
<tr><td><textarea id="comment_text"></textarea></td>
<td><input type="button" id="comment_process" value="Post Comment"/></td></tr>
</table>
</div>
</div>
JS:
$(document).ready(function() {
$('#comment_process').click(function() {
if ($('#comment_text').val() != "") {
$.post("comments.php?action=post", {
comment: $('#comment_text').val()
}, function(data) {
$('.comments').html(data);
$('#comment_text').val("");
});
}
});
});
PHP:
include_once("connect.php");
function convert ($date) {
$converteddate = date("F j, Y g:ia", strtotime($date." +1day"));
return $converteddate;
}
function getComments(){
$comments = "";
$sql = mysql_query("SELECT * FROM comments") or die(mysql_error());
if(mysql_num_rows($sql) == 0){
$comments = "<div class='each_comment'>There are no comments</div>";
} else {
while($row = mysql_fetch_assoc($sql)){
$comments .= "<div class='each_comment'><small><em>".convert($row['comment_date'])."</em></small><br />".$row['comment']."</div>";
}
}
return $comments;
}
function postComments($comment){
$comment = mysql_real_escape_string(strip_tags($comment));
$sql = mysql_query("INSERT INTO comments (comment, comment_date ) VALUES ('".$comment."', now())");
return true;
}
if((isset($_GET['action'])) && ($_GET['action']== "post")){
postComments($_POST['comment']);
}
echo getComments();
Thanks again for the help
DISCLAIMER
For future visitors:
Don't copy this code, as it has several issues that go beyond answering the question.
What you need to add is an identifyer for the type of comment. (Type could be replaced with something more suitable to your case like 'product', 'user', ... whatever the difference is/what they are related to)
So in your database add that new column:
comments
--------
id
comment
type
comment_date
Now you need to pass around that type through all your calls, and it shall be specified in your 'HTML'-Page (which actually is php...).
<div class="comment_container">
<div class="comments">
<?php
// specify the type needed on that page
$type = 1;
include_once("comments.php");
echo getComments($type);
?>
</div>
<div class="comments_form">
<table>
<tr><td><textarea id="comment_text"></textarea></td>
<td><input type="button" id="comment_process" value="Post Comment"/></td></tr>
</table>
</div>
</div>
<script>
// specify the type in javascript
var type=1;
$(document).ready(function() {
$('#comment_process').click(function() {
if ($('#comment_text').val() != "") {
// add the type here:
$.post("comments.php", {
comment: $('#comment_text').val(),
type: type,
action: 'post'
}, function(data) {
$('.comments').html(data);
$('#comment_text').val("");
});
}
});
});
</script>
and in comments.php:
//....some code left out here
function getComments($type){
$comments = "";
$sql = mysql_query("SELECT * FROM comments where type=$type") or die(mysql_error());
if(mysql_num_rows($sql) == 0){
$comments = "<div class='each_comment'>There are no comments</div>";
} else {
while($row = mysql_fetch_assoc($sql)){
$comments .= "<div class='each_comment'><small><em>".convert($row['comment_date'])."</em></small><br />".$row['comment']."</div>";
}
}
return $comments;
}
function postComments($comment, $type){
$comment = mysql_real_escape_string(strip_tags($comment));
$sql = mysql_query("INSERT INTO comments (comment, comment_date, type ) VALUES ('".$comment."', now(), ".$type.")");
return true;
}
if((isset($_POST['action'])) && ($_POST['action']== "post")){
postComments($_POST['comment'], $_POST['type']);
// send all the comments back to client
echo getComments($_POST['type']);
}
// moved to html-file: echo getComments($type);
NOTE
There are several issues with that code.
First don't use mysql functions. For real. Unsecure and deprecated/deleted as of php7. Use mysqli or pdo. Furthermore your sql can be hacked with sql injection. Read about prepared statements.
The general structure of that code is not very good.
Try to seperate output and formating from getting data.
For example it would be much better if a function called 'getComments' only would get the comments from the database, then let others decide what to do with that data. The less one function does the better.
Please read about coding styles, maybe start learning object oriented programming.
I hope this still helps you to get a clue of where to go!

Get value from select and compare with the DB to obtain a price

I'm using a select to choose from different products, then with that value I perform a DB query consult to obtain the price of the product and then set a input tag with it.
<section id="products">
quantity: <input type="number" id="quantity"><br><br>
<section id="selectProd">
<?php
$query = $conn->query("SELECT name FROM Products ORDER BY name");
?>
Product: <select id="comProduct" class="comProduct">
<?php while ($option = $query->fetch_object()) { ?>
<option><?php echo $option->name; ?></option>
<?php } ?>
</select>
<script>
$(document).on("ready",function(){
$("#comProduct").on("click", function(){
var value = $("#comProduct option:selected").text();
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "BERAKA";
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$valuephp = $_GET['value'];
$query = $conn->query("SELECT price FROM products where name='$valorphp'");
?>
document.getElementById("ppu").value = "<?php $query->fetch_object(); ?>";
});
});
</script>
</section> <br>
Price per unit: <input type="text" id="ppu" >
</section>
Don't know why it's not working, Please help
You are vulnerable to sql injection attacks. Sit back and relax - your problem will become moot when your server gets pwn3d.
As well, your code is highly flawed:
document.getElementById("ppu").value = "<?php $query->fetch_object(); ?>";
Your fetch call doesn't DO anything useful. fetch will RETURN an object, but since you don't capture that object or output it in any way, the DB row data will simply be lost. Even if the fetch call DID by some miracle do output, you can't just dump a PHP object into a Javascsript code context.
You need something more like this:
<?php
...
$row = $query->fetch_object();
$price = $row->price;
?>
document.getElementById('ppu').value = <?php echo json_encode($price); ?>;
Never EVER dump text from PHP directly into a JS context without using json_encode(). You're at risk of dumping invalid text into the JS code block, which will trigger a JS syntax error, and kill the entire <script> block that this bad code is in. Always use json_encode() so that no matter what you're dumping into the JS code, that value will be VALID javascript.

Categories