autocomplete bootstrap php mysql ajax
autocomplete bootstrap php mysql from databse
data not fetching from database not showing suggestion
my code not showing any result please help to complete my code
i have change many time my code
<!DOCTYPE html>
<html>
<head>
<title>Webslesson Tutorial | Autocomplete Textbox using Bootstrap Typehead with Ajax PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
</head>
<body>
Autocomplete Textbox using Bootstrap Typeahead with Ajax PHP
Search Country
// script
$(document).ready(function(){
$('#country').typeahead({
source: function(query, result)
{
$.ajax({
url:"autoselect_jquery5.php",
method:"POST",
data:{query:query},
dataType:"json",
success:function(data)
{
result($.map(data, function(item){
return item;
}));
}
})
}
});
});
</script>
// autoselect_jquery5.php
<?php
include 'database.php';
if (isset($_POST['query'])) {
// $search_query = $_POST['query'];
$search_query = mysqli_real_escape_string( $_POST["query"]);
$query = "SELECT * FROM transporter WHERE address LIKE '%".$search_query."%' LIMIT 12";
// $query = "SELECT * FROM transporter WHERE address LIKE %'
$search_query ' LIMIT 12";
$result = mysqli_query($link, $query);
$data = array();
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$data[] = $row["address"];
}
echo json_encode($data);
}
}
?>
You have multiple errors in your file. I have commented this up fully to help others who come across this question.
<?php
//Assume this line is correct and that you have a database.php file containing your log in credientials
include 'database.php';
//If Statement says - run this next piece of code if $_POST['query'] is set to something
if (isset($_POST['query']))
{
// $search_query = $_POST['query']; - Commented OUT
//This line attempts to sanatise the input from the posted data
$search_query = mysqli_real_escape_string( $_POST["query"]);
//This line constructs the whole SQL statement ( BAd methodology here, but thats a different topic)
$query = "SELECT * FROM transporter WHERE address LIKE '%".$search_query."%' LIMIT 12";
//You've commented out the next line and its of no use
// $query = "SELECT * FROM transporter WHERE address LIKE %'
//This line has a syntax error - but is also of no use - Should delete but should read $search_query = ' LIMIT 12';
//$search_query ' LIMIT 12";
/// This line queries the database
$result = mysqli_query($link, $query);
//This line declares $data will be an array
$data = array();
//If the DB returns some rows
if(mysqli_num_rows($result) > 0)
{
// While there are results
while($row = mysqli_fetch_assoc($result))
{
//add to the $data array
$data[] = $row["address"];
}
//Output $data in JSON format to be interpreted as a response from your ajax call
echo json_encode($data);
}
}
?>
Related
I would like to update the data in the frontend when it is changed in the database. The code I'm using is given below:
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<div id="test">
<?php
include('conn.php');
$query = "SELECT name FROM user_details WHERE user_id = 1;";
if(mysqli_fetch_assoc(mysqli_query($conn, $query))["name"] == "MyName")
echo 'Hi <b>MyName!</b>';
else
echo 'You are not <b>MyName</b>.';
?>
</div>
<script>
setInterval(function(){
$.get("/test.php", function(data){
let $data = $(data);
$("#test").append($data.find("#test > *"));
});
}, 1000);
</script>
However, when the data is updated, it does not get updated in the frontend unless refreshed. When I use jQuery's load() function, it works perfectly. Why does this not work?
As I suggested in the comment, if you create a stand alone PHP Script, it might be like:
getUserName.php
<?php
$id = (int)$_GET['id'];
include('conn.php');
$query = "SELECT name FROM user_details WHERE user_id = $id;";
$myName = "";
if ($result = mysqli_query($conn, $query)) {
while ($row = mysqli_fetch_assoc($result)) {
$myName = $row;
}
}
mysqli_free_result($result);
mysqli_close($conn);
header('Content-Type: application/json');
echo json_encode($myName);
?>
This is a very basic example and I would strongly advise you switch to using prepared statements to avoid the risk of SQL Injection.
In your HTML you can now do:
<script>
setInterval(function(){
$.getJSON("/getUserName.php", { id: 1 }, function(data){
$("#test").append(data.name);
});
}, 1000);
</script>
This will ping the script every second and you will have a list of names appearing.
I'm new in Ajax and JSON notation, so I'm trying to get data from differents tables of a Database, data like country names, state names, departament name, job position etc. and I've seen examples how through JSON can get data but just from a single table, can you give me a little help how can I do it with more than one table and keep it in an array.
<?php
$host = "localhost";
$user = "usuer";
$pass = "password";
$databaseName = "jsonExample";
$tableName = "variables";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$result = mysql_query("SELECT * FROM $tableName"); //query
//$array = mysql_fetch_row($result); //fetch result
if(mysql_num_rows($result) <= 0){
}else{
while($obj = mysql_fetch_row($result)){
$array[] = $obj;
}
}
echo json_encode($array);
?>
Html file:
<html>
<head>
<script language="javascript" type="text/javascript" src="jquery.js"></script>
</head>
<body>-->
<h2> Client example </h2>
<h3>Output: </h3>
<div id="output">this element will be accessed by jquery and this text will be replaced</div>
<script id="source" language="javascript" type="text/javascript">
$(function ()
{
$.ajax({
url: 'api.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
var id = data[0]; //get id
var vname = data[1]; //get name
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname); //Set output element html
//recommend reading up on jquery selectors they are awesome http://api.jquery.com/category/selectors/
}
});
});
</script>
</body>
</html>
If you want to have the results from multiple queries in one array you can add each result to a key. F.i. if you querying table table1 to tablen ...
// define the array that will contain all result sets
$array = [];
// create an array for the result set coming from table 1
$array['table1']= [];
$result = mysql_query("SELECT * FROM table1");
if(mysql_num_rows($result) <= 0){
}else{
while($obj = mysql_fetch_row($result)){
$array['table1'][] = $obj;
}
}
// create an array for the result set coming from table 2
$array['table2']= [];
$result = mysql_query("SELECT * FROM table2");
if(mysql_num_rows($result) <= 0){
}else{
while($obj = mysql_fetch_row($result)){
$array['table2'][] = $obj;
}
}
::
::
// create an array for the result set coming from table n
$array['tablen']= [];
$result = mysql_query("SELECT * FROM tablen");
if(mysql_num_rows($result) <= 0){
}else{
while($obj = mysql_fetch_row($result)){
$array['tablen'][] = $obj;
}
}
// return the results formatted as json
return json_encode($array);
In javascript you can access the results for table1 with data->table1.
Tip
Use mysqli instead of mysql. It is the improved version of mysql. Check the answers for this question for some background.
I have the following scripts that displays database records via json. it works very fine.
My question is how do i create a secure API with it so that when users place the api say
http://www.waco.com/profile.php?id=0990999&security=xxxxxxxxx in their website,
it will pull the information from my server and display it on their site. below is the entire working code
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script>
$(document).ready(function(){
var formhtml = "logreq=1";
var postURL= 'profile.php';
$.ajax({
type: "POST",
url: postURL,
data: formhtml,
dataType: JSON,
success: function(html){
var output= '<table class="logtable"><tbody><thead><th>Log</th><th>Username</th><th>Date</th><th>Event</th></thead>';
var logsData = $.parseJSON(html);
for (var i in logsData.logs){
output+="<tr><td>" + logsData.logs[i].title + "</td><td>" + logsData.logs[i].user + "</td><td>" + logsData.logs[i].date+ "</td><td>" + logsData.logs[i].log+"</td></tr>";
}
//write to container div
$("#log_container").html(output);
},
error: function (html) {
alert('Oops...Something went terribly wrong');
}
});
});
</script>
</head>
<body>
<div id="log_container">
</div>
</body>
</html>
<?php
$db = mysqli_connect("localhost","root","","profile_database");
//MSG
$query = "SELECT * FROM logs LIMIT 20";
$result = mysqli_query($db, $query);
//Add all records to an array
$rows = array();
while($row = $result->fetch_array()){
$rows[] = $row;
}
//Return result to jTable
$qryResult = array();
$qryResult['logs'] = $rows;
echo json_encode($qryResult);
mysqli_close($db);
?>
please i need help.
I am assuming that your example is an oversimplification, and that you will be looking into preventing SQL injections as well as any additional validation to ensure that you are getting the data you are expecting.
With that said, I would place your PHP code in a separate file for the user to call and drop your code into it like so:
if(isset($GET['id']) && isset($GET['security'])){
$id = $GET['id']; $secure = $GET['security']; // TODO: escape these strings
$db = mysqli_connect("localhost","root","","profile_database");
//MSG
$query = "SELECT * FROM logs LIMIT 20 Where id = $id And security = $secure";
$result = mysqli_query($db, $query);
//Add all records to an array
$rows = array();
while($row = $result->fetch_array()){
$rows[] = $row;
}
//Return result to jTable
$qryResult = array();
$qryResult['logs'] = $rows;
echo json_encode($qryResult);
mysqli_close($db);
}
Hope that helps. This is good place to start. I would also look into PHP frameworks like CodeIgniter or Cake that will help you build your API properly.
Using Chain SELECT works great from SELECT to SELECT, I'm trying to do SELECT to INPUT.
My mainpage.php
<label>Manufacturer</label>
<select>My Select statement is here</select>
<label>Model</label>
<select name="modelname">My Select statement is fed from the select above</select>
<label>Rating</label>
<input name="rating"></input>
This is the jQuery I have in the <head> section on the mainpage.php
<script>
$(document).ready(function(){
$("select#modelname").change(function(){
var id = $("select#modelname option:selected").attr('value');
$.post("assets/configs/getdata.php", {id:id}, function(data){
$("input[name='rating']").html(data);
console.log(data);
});
});
});
</script>
and finally the getdata.php
<?php
include "db.php";
$modelid = $_POST[id];
$sql = "SELECT EfficiencyRating FROM AllModels WHERE ModelID = '$modelid' ";
$res = odbc_exec($cnn, $sql);
while ($row = odbc_fetch_array($res)) {
$row_array[] = $row['EfficiencyRating'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
?>
Using the console log when this message is returned, how can I fix this?
HP Warning: array_push() expects parameter 1 to be array, null given in assets\configs\getdata.php on line 12
Try with this.
$res = odbc_exec($cnn, $sql);
$return_arr = array();
while ($row = odbc_fetch_array($res)) {
$return_arr[] = $row['EfficiencyRating'];
}
echo json_encode($return_arr);
JS Part
// Slightly modify the Request
$.post("assets/configs/getdata.php", {id:id}, function(data){
// JSON Object
console.log(data);
$("input[name='rating']").val(data);
}, 'json');
You need to declare $return_arr before the while statement. Also, I personally feel what you are doing is just not right. The proper way would be this...
$res = odbc_exec($cnn, $sql);
$return_arr = array(); //<----------- Here
while ($row = odbc_fetch_array($res)) {
array_push($return_arr,$row['EfficiencyRating']);
}
echo json_encode($return_arr);
I have a problem in using Samrtm Mysql and Jquery or Ajax
and if I use a div auto reloader
it shows a php error ..
these are my files:
accept.html (Template)
{literal}
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#invite').load('accept.php').fadeIn("slow");
}, 1000);
</script>
{/literal}
<div id="invite">
<fieldset>
<legend>Invites</legend>
{section name=ct loop=$invites}
You have an invite {$sender.user}<br />
Accept | Cancel
{/section}
</fieldset>
</div>
accept.php (Main file)
<?php
$time = date("i:s",time("s"));
$sql_select_invite = mysql_query("SELECT * FROM invite WHERE recid = '$_SESSION[id]' AND accept = '0' AND endtime > '$time'");
while($invite = mysql_fetch_array($sql_select_invite)){
$sender = mysql_fetch_array(mysql_query("SELECT * FROM member WHERE id = '$invite[sendid]'"));
$contest->assign("sender", $sender);
$invites[] = $invite;
}
$contest->assign("invites", $invites);
?>
and when I use the Jquery thing or Ajax
it shows this error:
Warning: mysql_fetch_array(): supplied
argument is not a valid MySQL result
resource in
C:\AppServ\www\somefo\accept.php
on line 6
Fatal error: Call to a member function
assign() on a non-object in
C:\AppServ\www\somefo\accept.php
on line 11
I don't know why it shows this .. and I hope you answer me
and what or how to solve this problem
Thanks ..
For php:
<?php
$sql = mysql_connect(......); // connect to your server
if (!$sql) {
die('Can\'t connect to database');
}
// select your database
mysql_select_db('your_db', $sql) or die('Can\'t select database');
$time = date("i:s",time("s"));
$sql_select_invite_query = "SELECT * FROM invite WHERE recid = '$_SESSION[id]' AND accept = '0' AND endtime > '$time'";
// print it if you want to see sql query to test it in phpmyadmin
echo $sql_select_invite_query;
// --------------------------------------------------------------
$sql_select_invite = mysql_query($sql_select_invite_query, $sql);
if (!$sql_select_invite) { // check for error in query
die(mysql_error()); // and print it
}
$invites = array(); // don't forget to make an empty array
while($invite = mysql_fetch_array($sql_select_invite, $sql)){
// this place is not good, just make it as you do before, with checks
$sender = mysql_fetch_array(mysql_query("SELECT * FROM member WHERE id = '$invite[sendid]'"));
$contest->assign("sender", $sender);
$invites[] = $invite;
}
$contest->assign("invites", $invites); // in your case there is no $invite
// array cause mysql_fetch_array returned
// false and it is not defined before [while]
?>
For JS to test:
setInterval( function () {
$('#invite').load('accept.php', function() {
alert('loaded'); // it is to check content is loaded
}).fadeIn("slow");
}, 1000);