How to get my AJAX results from the input of a textbox populated from mysql live on the page.
I already got it to work with the use of textboxes, so if you check them then the page gets updated with the results of mysql.
The same I would like to use for my textboxes as soon as you type something in or select something from the autocomplete list (this would be even beter).
I have the following code that I want to use for the textbox:
HTML:
<input type="text" name="naam_klant" size="20" id="naam_klant" onkeyup="lookup(this.value);" onblur="fill();" >
<div class="suggestionsBox" id="suggestions" style="display: none;">
<div class="suggestionList" id="autoSuggestionsList">
</div>
</div>
PHP:
$pdo = new PDO('mysql:host=localhost;dbname=records', 'root', '***');
$select = 'SELECT *';
$from = ' FROM overboekingen';
$where = ' WHERE FALSE';
$opts = isset($_POST['filterOpts'])? $_POST['filterOpts'] : array('');
if (in_array("naam_klant", $opts)){
$where .= " OR naam_klant = [$queryString%] ";
}
$sql = $select . $from . $where;
$statement = $pdo->prepare($sql);
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
I am trying to create a live search using ajax, jquery, php and mysql.
The user enter some inputs, it send the search to form_livesearch.php. I got that part worked. Else if the input is empty, then display other query. (I need help with this part)
<div id="container" class="col-md-12">
<div class="row">
<h2>Quick Search</h2>
<input class='form-control' type="text" id='live_search' placeholder='Search our inventory'>
<br>
<br>
<h2 class="" id="searchresult">
</h2>
</div>
</div>
$(document).ready(function(){
$("#live_search").keyup(function(){
var input = $(this).val();
if(input != ""){
$.ajax({
url:"form_livesearch.php",
method:"POST",
data:{input:input},
success:function(data){
$("#searchresult").html(data);
$("#searchresult").css("display","block");
}
});
} else {
// If the input field is empty
// How display another php query here?
}
});
});
Here is the php and mysql I am trying to display when the input field is empty.
<?php
$query = "SELECT * FROM `my_db` . `my_table` WHERE s_category = 'policy' ORDER BY id ASC";
$result = mysqli_query($db,$query);
if(!$result){
die("Query Failed " . mysqli_error($db));
}
if(mysqli_num_rows($result) > 0){
?>
<h3>Policies</h3>
<ul>
<?php
while($row = mysqli_fetch_assoc($result)){
$id = $row['id'];
$s_url = $row['s_url'];
$s_name = $row['s_name'];
$s_category = $row['s_category'];
?>
<li><?php echo $s_name?> <img src="https://www.xxxxxxx.xxx/xxxx/images/pdf.gif" alt="PDF"></li>
<?php
}
?>
</ul>
<?php
}
?>
form_livesearch.php:
if(isset($_POST['input'])){
$input = $_POST['input'];
//to prevent from mysqli injection
// x'='x
$input = stripcslashes($input);
$input = mysqli_real_escape_string($db, $input);
$input = str_replace('%', ' #', $input);
$input = str_replace("'", ' #', $input);
$query = "SELECT * FROM `my_db` . `my_table` WHERE s_name LIKE '%{$input}%' ORDER BY id ASC";
$result = mysqli_query($db,$query);
if(mysqli_num_rows($result) > 0){?>
<table class="table table-bordered table-striped mt-4">
<!--
<thead>
<tr>
<th>id</th>
<th>name</th>
</tr>
</thead>
-->
<tbody>
<?php
while($row = mysqli_fetch_assoc($result)){
$id = $row['id'];
$s_url = $row['s_url'];
$s_name = $row['s_name'];
$s_category = $row['s_category'];
?>
<tr>
<td style="font-size: 14px;"><?php echo $s_name;?> <img src="https://www.xxxxx.xxxx/xxxxx/images/pdf.gif" alt="PDF"></td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php
}else{
echo "<h6 class='text-danger text-center mt-3'>No data Found</h6>";
}
}
?>
You should handle this stuff in the PHP file. and by the way, the input can not be empty as you put the ajax in keyup event.
it just happened when the user use the backspace to delete what he search.
So the form_livesearch.php PHP file should be something like this.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
$output = "";
if(isset($_POST['input'])){
$input = $_POST['input'];
if(!empty($input)){
$input = str_replace('%', ' #', $input);
$input = str_replace("'", ' #', $input);
$input = "%$input%"; // prepare the $input variable
$query = "SELECT * FROM `my_db` . `my_table` WHERE s_name LIKE ? ORDER BY id ASC";
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $input); // here we can use only a variable
$stmt->execute();
}else{
$query = "SELECT * FROM `my_db` . `my_table` WHERE s_category = 'policy' ORDER BY id ASC";
$stmt = $conn->prepare($query);
$stmt->execute();
}
$result = $stmt->get_result(); // get the mysqli result
if($result->num_rows > 0){
if(empty($input))
$output = '<table class="table table-bordered table-striped mt-4"><tbody>';
else
$output = '<h3>Policies</h3><ul>';
while($row = $result->fetch_assoc()){
$id = $row['id'];
$s_url = $row['s_url'];
$s_name = $row['s_name'];
$s_category = $row['s_category'];
if(empty($input))
$output .= '
<tr>
<td style="font-size: 14px;">' . $s_name .' <img src="https://www.xxxxx.xxxx/xxxxx/images/pdf.gif" alt="PDF"></td>
</tr>';
else
$output .= '<li>' . $s_name . ' <img src="https://www.xxxxxxx.xxx/xxxx/images/pdf.gif" alt="PDF"></li>';
}
if(empty($input))
$output .= '</tbody></table>';
else
$output .= '</ul>';
echo $output;
}else{
echo "<h6 class='text-danger text-center mt-3'>No data Found</h6>";
}
}
?>
You can use a separate file to handle 2 types but as they are all about products it's better to have one file.
It's a good practice to return the data and let the frontend build the HTML output but if you want to build HTML in the PHP file, it's better to wrap them in a string.
Also, use the prepare statement of MySQLi to prevent SQL injection. take a look at this example for more information.
And the html file should be something like this:
<div id="container" class="col-md-12">
<div class="row">
<h2>Quick Search</h2>
<input class='form-control' type="text" id='live_search' placeholder='Search our inventory'>
<br>
<br>
<h2 class="" id="searchresult">
</h2>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
// will execute once the page load
getData();
$("#live_search").keyup(function(){
let input = $(this).val();
getData(input);
});
});
function getData(input = ''){
$.ajax({
url:"form_livesearch.php",
method:"POST",
data:{input:input},
success:function(data){
$("#searchresult").html(data);
$("#searchresult").css("display","block");
}
});
}
</script>
I have an input box that serves as a search box, and I populate a select box by querying a SQL database. For example, there are two organizations called "Dummy Organization" and "Dummy 2" in my db. So when the user starts typing "du", the select box fills with those two organizations. What I want to do is to combine these two fields: the input box (that acts as the search box) and the select box (which displays the results). My research shows that selectize.js can be useful, but since I'm new to js, I can't figure out how. Can someone please help me? My code is as below:
js that gets the data from the db:
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
$.post("search.php", {searchVal: searchTxt},function(output4){
$("#output4").html(output4);
}
</script>
The form:
<form action="newbrand.php" method="post" id="form">
<br>
Brand Name: <input type="text" name="bname" required /><br><br>
Search for an Organization: <input type="text" required name="search" onkeyup="searchq()" id="output"><br><br>
Selected Organization:
<select id="output4" name="taskOption"></select>
</form>
The search.php file
<?php
include 'db_connect.php';
$link = mysqli_connect($host, $username, $password, $db);
if(!link){
echo "DB Connection error";
}
$output = '' ;
$output2 = '' ;
if (isset($_POST['searchVal'])){
$searchq = $_POST['searchVal'];
//$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysqli_query($link, "SELECT * FROM `organisations_info` WHERE `Organisation_Name` LIKE '%".$searchq."%' ")or die("Could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<option>No results!</option>';
}else{
while($row = mysqli_fetch_array($query)){
$orgname = $row['Organisation_Name'];
$orgid = $row['Organisation_Id'];
$subs = $row['Subscription_Type'];
?>
<option value="<?php echo $orgid; ?>"><?php echo $orgname; ?></option>
<div><?php echo $subs; ?></div>
<?php
} // while
} // else
} // main if
?>
I am using two values for 1 input box, when user selects multiple boxes the values will be submitted to submit_checkbox.php. I want to save the 2nd value i.e value after "|" sign in the php form. How can I do it ? My code is as follows :-
<form name='checkbox' method="post" action="submit_checkbox.php">
<b><h3>Select option</h3></b>
<input type="hidden" name="qq1[]" value="null">
<input type="checkbox" name="qq1[]" value="ABC|DEF"> A<br>
<input type="checkbox" name="qq1[]" value="GHI|IJK"> B<br>
<input type="checkbox" name="qq1[]" value="LMN|PQR"> C<br>
<input type="submit" value="SUBMIT" >
</form>
And in "submit_checkbox.php" the code is as follows :-
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root1';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db("my_db") or die(mysql_error());
list($value1,$value2)=explode('|',$_POST['qq1']);
$values=implode(',', $value2);
$sql = "INSERT INTO print_chk VALUES ('$values')";
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
else
{
echo "Success";
}
?>
However, I am unable to put the 2nd value in the sql table "print_chk".
Your $_POST['qq1'] is an array, so you have to explode every element of it and then make the string from this. Try something like this, it works for me:
//Get the second part
function GetSecond($v) {
if ($v != 'null') {
$a = explode('|',$v);
return $a[1];
}
else {
return '';
}
}
//Since $_POST['qq1'] is an array, get the second part of each item
$v = array_map('GetSecond',$_POST['qq1']);
//Filter out the empty strings
$v = array_filter($v);
//Implode the list
$values = implode(',',$v);
//Insert to DB
$sql = 'INSERT INTO print_chk VALUES ("'.mysql_real_escape_string($values).'")';
I've got a jQuery $.post script which isn't passing all of the data to the php script it's calling. It worked fine when I only passed two parameters into the data field, but now that I've got more than just two, it's not working any more. The console is showing the values of the fields, but the data isn't being inserted into the database for some reason.
HTML Form
<fieldset for="center">
<label>Center:</label>
<div class="select" name="center" id="center">
<div class="arrow"></div>
<div class="option-menu">
<?php
$query = "SELECT * FROM $centers";
$result = mysqli_query($connect, $query);
$center_name;
while($row = mysqli_fetch_assoc($result)){
$center_name = "{$row['center']}";
echo "<div class='option'>" .$center_name ."</div>";
}
?>
</div>
</div>
</fieldset>
<fieldset for="initials">
<label>Initials:</label>
<input type="text" name="initials" id="initials" />
</fieldset>
<fieldset for="recurrent">
<label>Type:</label>
<div class="select" name="recurrent" id="recurrent">
<div class="arrow"></div>
<div class="option-menu">
<?php
$query = "SELECT * FROM $recurrent";
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_assoc($result)){
$type = "{$row['type']}";
echo "<div class='option'>" .$type ."</div>";
}
?>
</div>
</div>
</fieldset>
PHP Script
ob_start();
require("../includes/header.php");
if($_SERVER["REQUEST_METHOD"] == "POST"){
$center = $_POST["center"];
$recurrent = $_POST["recurrent"];
$initials = $_POST["initials"];
$query = "INSERT INTO `$scenarios`(`initials`, `center`, `recurrent`) VALUES('" .$initials ."', " .$center ."', '" .$recurrent ."')";
mysqli_query($connect, $query);
}
ob_clean();
echo json_encode(array("success" => 1));
jQuery Script
$("input[id='save']").on("click", function(){
var initials = $("#initials").val();
var center = $("#center_menu").val();
var recurrent = $("#recurrent_menu").val();
console.log(initials);
console.log(center);
console.log(recurrent);
$.post("../php/processing.php", {initials: initials, center: center, recurrent: recurrent}, function(response){
if(response.success == "1"){
}
}, "json");
})
First, confirm that you aren't getting the proper values back by writing out the values of the three post variables. Be sure that its a problem with the jquery post.
If it is a jquery problem, which parameter isn't getting passed back?
In your php script, the single quotes are the wrong type of single quotes.
Change:
$query = "INSERT INTO `$scenarios`(`initials`, `center`, `recurrent`) VALUES('" .$initials ."', " .$center ."', '" .$recurrent ."')";
To:
$query = "INSERT INTO '$scenarios'('initials', 'center`, 'recurrent') VALUES('" .$initials ."', " .$center ."', '" .$recurrent ."')";
I'm trying to insert a form in php statement like this
while($row = mysql_fetch_array($result))
{
echo "<form id='send' action='up.php' method='POST'>
<tr>
<td>" . $row['s_no'] ."</td>
<td> <label for='student_name'><textarea name='student_name' >".$row['student_name']."</textarea></label></td>
<td> <textarea name='roll_no'>".$row['roll_no']. "</textarea></td>
<td> <textarea name='company'>".$row['company']. "</textarea></td>
<td> <textarea name='contact_no' >".$row['contact_no']. "</textarea></td>
<td> <textarea name='email'>" .$row['email']. "</textarea></td>
</tr>
<input type='text' name='batch_name' disabled='disabled' size='7' value=" .$_POST['batch_name']. ">
<p align='center'><button id='submit' type='submit'>Update</button></p>
</form>";
}
I'have taken the datas from the database and put as default into the texareas and thus it cab de edited. So i planned to USE UDPDATE query to make the alternations like this:
<html>
<title>Alumini Update</title>
<head>
<?php
$con = mysql_connect("localhost","root","momsgift");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("alumini", $con);
mysql_query("UPDATE $_POST[batch_name] SET contact_no = $_POST[contact_no] WHERE roll_no = '2321'");
mysql_close($con);
?>
But while sending a query the data in the textarea doesnt loaded to the database ( BUt it redirects to the up.php page)
WHat may be the reason??
You are generating invalid HTML.
You cannot wrap a form around a table row without wrapping it around the entire table.
Your browser is error recovering by moving the form element. This is the most likely cause of the unexpected results.
Use a validator on your generated HTML.
In your MySQL update query you are only updating contact_no no other fields.
Also you have left your query open for SQL injections
$batch_number = mysql_real_escape_string($_POST['batch_name']);
$contact_no = mysql_real_escape_string($_POST['contact_no']);
$student_name = mysql_real_escape_string($_POST['student_name']);
$roll_no = mysql_real_escape_string($_POST['roll_no']);
$company = mysql_real_escape_string($_POST['company']);
$email = mysql_real_escape_string($_POST['email']);
mysql_query("UPDATE ('" . $batch_no. "')
SET contact_no = ('" . $contact_no . "'),
student_name = ('" . $student_name. "'),
company = ('" . $company . "'),
email = ('" . $email . "'),
WHERE roll_no = ('" . $roll_no . "')");
This (mysql_real_escape_string) won't solve every problem, and using PDO is a better method, but it's a very good stepping stone.
first write this and see the result,if it show's text of textarea it show's that text is sending in right way.and the problem is in ur sql code.
echo $_POST['contact_no'];
then you can echo the query and copy and run it in phpmyadmin and view error of sql.
//EXAMPLE 1
if (isset($_POST['update']))
{
$result = pg_query($db_con, "UPDATE mydbtable SET mydbrecord = '$_POST[my_var1]' WHERE mydbrecord_id = '$_POST[myfilterbyid_var]'");
if (!$result)
{
echo "Update failed!!";
}
else
{
echo "Update successfull!";
}
}
//EXAMPLE 2
<form name="display" action="" method="post">
<select name="mydropdown" action="test.php" method="post">
<?php
while($row = pg_fetch_assoc)
{
echo "<option id=\"{$row['result_var']}\">{$row['result_var']}</option>";
}
?>
</select>