Here i have simple search engine to search usernames. when people type username i want them to see results below search box and have them taken to search page only after they hit enter (like facebooks search engine).
html
<div class="search">
<form action="search.php" method="GET">
<input type="text" name="Search" size="50">
<input type="submit" value="Search">
</form>
</div>
php (search.php)
<?php
require 'includes/connection.php';
$term = $_GET['Search'];
$query_ver = "select * from Members where Name like '%$term%'";
$query = mysqli_query($dbc, $query_ver);
while($row = mysqli_fetch_array($query)) {
$name = $row['Name'];
}
echo $name;
?>
so is there a way to display $name below search box only with php and html
HTML
<div class="search">
<form action="search.php" method="GET">
<input type="text" name="search" size="50" class="search">
<input type="submit" value="Search">
</form>
</div>
Javascript
<script type="text/javascript" src="jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(function(){
$(".search").keyup(function()
{
var searchid = $(this).val();
var dataString = \'search=\'+ searchid;
if(searchid!=\'\')
{
$.ajax({
type: "POST",
url: "result.php",
data: dataString,
cache: false,
success: function(html)
{
$("#result").html(html).show();
}
});
}return false;
});
jQuery("#result").live("click",function(e){
var $clicked = $(e.target);
var $name = $clicked.find(\'.name\').html();
var decoded = $("<div/>").html($name).text();
$(\'#searchid\').val(decoded);
});
jQuery(document).live("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search")){
jQuery("#result").fadeOut();
}
});
$(\'#searchid\').click(function(){
jQuery("#result").fadeIn();
});
});
</script>
search.php
<?php
include('db.php');
if($_POST)
{
$q = mysql_real_escape_string($_POST['search']);
$strSQL_Result = mysql_query("select id,name,email from live_search where name like '%$q%' or email like '%$q%' order by id LIMIT 5");
while($row=mysql_fetch_array($strSQL_Result))
{
$username = $row['name'];
$email = $row['email'];
$b_username = '<strong>'.$q.'</strong>';
$b_email = '<strong>'.$q.'</strong>';
$final_username = str_ireplace($q, $b_username, $username);
$final_email = str_ireplace($q, $b_email, $email);
?>
<div class="show" align="left">
<img src="https://fbcdn-sphotos-e-a.akamaihd.net/hphotos-ak-prn1/27301_312848892150607_553904419_n.jpg" style="width:50px; height:50px; float:left; margin-right:6px;" /><span class="name"><?php echo $final_username; ?></span> <br/><?php echo $final_email; ?><br/>
</div>
<?php
}
}
?>
for reference here is good solution
LINK1
LINK2
Related
I have the below two files.
How do I get AJAX to populate a label and a value
For example if value is Chicago, IL. How do I get the value to be only Chicago on Submitting the form?
Below the field populates as, for example, Chicago, IL
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/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.6/css/bootstrap.min.css" />
</head>
<body>
<br /><br />
<div class="container" style="width:600px;">
<h2 align="center"></h2>
<br /><br />
<label>Search Country</label>
<input type="text" name="city" id="city" class="form-control input-lg" autocomplete="off" placeholder="Type City Name" />
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#city').typeahead({
source: function(query, result)
{
$.ajax({
url:"TypeaheadTest2.php",
method:"POST",
data:{query:query},
dataType:"json",
success:function(data)
{
result($.map(data, function(item){
return item;
}));
}
})
}
});
});
</script>
Below is file TypeaheadTest2.php
<?php
$connect = mysqli_connect("localhost", "", "", "");
$request = mysqli_real_escape_string($connect, $_POST["query"]);
$query = "
SELECT * FROM state WHERE state LIKE '".$request."%' OR city LIKE '%".$request."%'
";
$result = mysqli_query($connect, $query);
$data = array();
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$data[] = $row['city'] . ' ' . $row['state'];
}
echo json_encode($data);
}
?>
If I am getting you right, you are so close to what you are expecting.
I see that you are concatenating the city and state name on the server side. But you want to display only city name on typeahead options.
I would suggest you pass on the city name and state name as separate attributes of an object from PHP and then use them as you want on Javascript side.
Here is the sample code,
PHP:
<?php
$connect = mysqli_connect("localhost", "", "", "");
$request = mysqli_real_escape_string($connect, $_POST["query"]);
$query = "
SELECT * FROM state WHERE state LIKE '".$request."%' OR city LIKE '%".$request."%'
";
$result = mysqli_query($connect, $query);
$data = array();
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
$data[] = array('city'=>$row['city'], 'state'=>$row['state']);
}
echo json_encode($data);
}
?>
Javascript:
$(document).ready(function(){
$('#city').typeahead({
source: function(query, result) {
$.ajax({
url:"TypeaheadTest2.php",
method:"POST",
data:{query:query},
dataType:"json",
success:function(data) {
result($.map(data, function(item){
return item.city;
}));
}
});
}
});
});
I need to make a autocomplete input in materialize css page,
I've tried this code but did not work. Do you have any idea how to make this possible?
From here Autocomplete Textbox using jQuery, PHP and MySQL
index.php
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#skills" ).autocomplete({
source: 'search.php'
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="skills">Skills: </label>
<input id="skills" type="text">
</div>
search.php
<?php
$dbHost = 'localhost';
$dbUsername = 'u969692298_dogs';
$dbPassword = 'dogs123';
$dbName = 'u969692298_dogs';
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
$searchTerm = $_GET['term'];
$query = $db->query("SELECT * FROM kennels WHERE name LIKE '%".$searchTerm."%' ORDER BY name ASC");
while ($row = $query->fetch_assoc()) {
$data[] = $row['name'];
}
echo json_encode($data);
?>
What about something like this:
The result from this snippet suggests country name when you start typing in input box with materialize css framework.
Example with API GET request
$(document).ready(function() {
//Autocomplete
$(function() {
$.ajax({
type: 'GET',
url: 'https://restcountries.eu/rest/v2/all?fields=name',
success: function(response) {
var countryArray = response;
var dataCountry = {};
for (var i = 0; i < countryArray.length; i++) {
//console.log(countryArray[i].name);
dataCountry[countryArray[i].name] = countryArray[i].flag; //countryArray[i].flag or null
}
$('input.autocomplete').autocomplete({
data: dataCountry,
limit: 5, // The max amount of results that can be shown at once. Default: Infinity.
});
}
});
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/css/materialize.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/js/materialize.min.js"></script>
<div class="row">
<div class="col s12">
<div class="input-field">
<input type="text" id="autocomplete-input" class="autocomplete" autocomplete="off" name="name">
<label for="autocomplete-input">Country Name</label>
</div>
</div>
</div>
Above code by Jaikhlang Brahma answer
Example with POST request
Jquery
$(document).ready(function() {
//Autocomplete
var inp_val = document.getElementById("myInput").value;
var dataString = "name="+inp_val;
$(function() {
$.ajax({
type: 'POST',
url: 'suggest-country.php',
data: dataString,
success: function(response) {
var countryArray = response;
var dataCountry = {};
for (var i = 0; i < countryArray.length; i++) {
//console.log(countryArray[i].name);
dataCountry[countryArray[i].name] = countryArray[i].flag; //countryArray[i].flag or null
}
$('input.autocomplete').autocomplete({
data: dataCountry,
limit: 5, // The max amount of results that can be shown at once. Default: Infinity.
});
}
});
});
});
HTML
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/css/materialize.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/js/materialize.min.js"></script>
<div class="row">
<div class="col s12">
<div class="input-field">
<input type="text" id="autocomplete-input" class="autocomplete" autocomplete="off" name="name">
<label for="autocomplete-input">Country Name</label>
</div>
</div>
</div>
PHP (suggest-country.php)
<?
header('Content-type: text/html; charset=UTF-8');
$dbHost = 'localhost';
$dbUsername = 'u969692298_dogs';
$dbPassword = 'dogs123';
$dbName = 'u969692298_dogs';
$conn = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
$query = trim(str_replace(" ", " ", $_POST['name']));
$str = htmlspecialchars($query);
$q = filter_var($str, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$sql = $conn->prepare("SELECT * FROM kennels WHERE name = ? ORDER BY name ASC");
$sql->bind_param("s", $q);
$sql->execute();
$rs = $sql->get_result();
$arr = array();
while($row = $rs->fetch_assoc()){
$arr["name"] .= $row["name"];
$arr["flag"] .= $row["flag"];
}
// echo "<pre>".json_encode($arr)."</pre>";
echo json_encode($arr);
?>
This PHP code is pretty secure and working nicely.
For more relevancy use MYSQL FULL TEXT SEARCH or replace this SQL query
$sql = $conn->prepare("SELECT * FROM kennels WHERE name = ? ORDER BY name ASC");
$sql->bind_param("s", $q);
$sql->execute();
To this
$sql = $conn->prepare("SELECT *, " . " MATCH(name) AGAINST(? IN BOOLEAN MODE) AS relevance " . " FROM kennels" . " ORDER BY relevance DESC LIMIT 8");
$sql->bind_param("s", $q);
$sql->execute();
$rs = $sql->get_result();
Hope this is helpful to you, I know how old this post is, but I want to help other newbies who are experiencing this problem.
Thank you 😊
when I echo the php variable it work properly , but when I try to insert the data into database it doesn't work , what is the solution please I get stuck
I got this error on console
POST http://localhost/validate.php 500 (Internal Server Error)
send # jquery-3.1.1.min.js:4
ajax # jquery-3.1.1.min.js:4
(anonymous) # jquery.PHP:26
dispatch # jquery-3.1.1.min.js:3
q.handle # jquery-3.1.1.min.js:3
HTML/JQUERY
<form action="" id="myForm">
<input type="text" id="name" ><br/>
<input type="text" id="age" ><br/>
<input type="submit" value="Submit">
</form>
<div id="result"></div>
<script>
$(function() {
$("#myForm").submit(function(e) {
e.preventDefault();
var name = $('#name').val();
var age = $('#age').val();
$.ajax({
url: 'validate.php',
method: 'POST',
data: {postname:name, postage:age},
success: function(res) {
$("#result").append(res);
}
});
});
});
</script>
PHP
<?php
include 'mysqldb.php';
$name = $_POST['postname'];
$age = $_POST['postage'];
$sql = "insert into uss (first, last) values('".$name."','".$age."')";
$result = $conn->query($sql);
echo $result ;
?>
mysqldb.php
<?php
$conn = mysql_connect('localhost', 'root', 'password' , 'datab');
if (!$conn) {
die("Connection failed: ".mysqli_connect_error());
}
?>
Please add the details of the error message you get.
Make little changes to your code so that it can show the query error if any
<?php
include 'mysqldb.php';
$name = $_POST['postname'];
$age = $_POST['postage'];
$sql = "INSERT INTO `uss` (`first`, `last`) VALUES('{$name}','{$age}')";
if($conn->query($sql))
{
echo "Record inserted";
}
else
{
echo $conn->error;
}
?>
Sugesstions: Your query have the chances of the SQL Injection. Make it secure.
if you are using ajax , try the following,
<form >
<input type="text" id="name" ><br/>
<input type="text" id="age" ><br/>
<input type="submit" value="Submit" id="submit">
</form>
<div id="result"></div>
$("#submit").click(function(){
var name = $('#name').val(); // getting name
var age = $('#age').val();
$.ajax({
url : "validate.php",
type: "POST",
data: {name:name, age:age},
success: function(data)
{
$("#result").html(data);
}
});
});
in your controller function,echo the result
<?php
include 'mysqldb.php';
$name = $_POST['postname'];
$age = $_POST['postage'];
$sql = "insert into uss (first, last) values('$name','$age')";
$result = $conn->query($sql);
echo $result;
?>
jQuery Ajax
Form with id myFrom
<form action="" id="myForm">
<input type="text" id="name" ><br/>
<input type="text" id="age" ><br/>
<input type="submit" value="Submit">
</form>
<div id="result"></div>
jQuery Ajax section
$(function() {
$("#myForm").submit(function(e) {
e.preventDefault();
var name = $('#name').val(); // getting name
var age = $('#age').val(); // getting age
/* Ajax section */
$.ajax({
url: 'validate.php',
method: 'POST',
data: {postname:name, postage:age},
success: function(res) {
$("#result").append(res);
}
});
});
});
validate.php
<?php
include 'mysqldb.php';
$name = $_POST['postname'];
$age = $_POST['postage'];
//check ajax response by `echo $name` and `$age`
$sql = "insert into uss (first, last) values('".$name."','".$age."')";
$result = $conn->query($sql);
echo $result ;
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<form >
<input type="text" id="name" ><br/>
<input type="text" id="age" ><br/>
<input type="button" value="Submit" onclick="postdata();">
</form>
<div id="result"></div>
<script type="text/javascript">
function postdata() {
alert("ashad");
var name = $('#name').val();
var age = $('#age').val();
$.post('validate.php',{postname:name,postage:age},
function(data){
$('#result').html(data);
});
}
</script>
<?php
include 'mysqldb.php';
$name = $_POST['postname'];
$age = $_POST['postage'];
//check ajax response by `echo $name` and `$age`
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else
{
$sql = "insert into uss(first, last) values('$name','$age')";
$result = $conn->query($sql);
}
echo $result ;
?>
I have this code here which is supposed to help me update a phone number.
It doesn't do it though, well, i get the successfully changed message but no insertion on the database.
Here is my code:
index.php
<script type="text/javascript" >
$(function() {
$(".submit").click(function() {
var phone = $("#phone").val();
var dataString = 'phone='+ phone ;
if(phone=='') {
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
} else {
$.ajax({
type: "POST",
url: "update-phone.php",
data: dataString,
success: function() {
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
<div class="modal" style="display: none;">
<?php
if (empty($phone)) {
?>
<form method="post" name="form">
<input id="phone" name="phone" type="text" />
<div>
<input type="submit" value="Submit" class="submit"/>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Registration Successfully</span>
</div>
</form>
update-phone.php
<?php
require_once('db.php');
if($_POST) {
$phone = $_POST['phone'];
mysql_query("UPDATE users SET phone = '$phone' WHERE ID = 5884 ");
}else {}
?>
What am i missing?
Thanks
Try this..
<?php
require_once('db.php');
if($_POST) {
$phone = $_POST['phone'];
mysql_query("UPDATE `users` SET `phone` = '$phone' WHERE `ID` = 5884 ");
}else {}
?>
Have you tried inspecting the ajax request with firebug/developer tools/etc?
Try adding echo mysql_error(); right after your mysql_query.
Not 100% sure but it could be the if ($_POST) should be replaced with if (isset($_POST['phone']))
Try the following php:
<?php
require_once('db.hp');
if (isset($_POST['phone']))
{
$phone = $_POST['phone'];
mysql_query("UPDATE users SET phone = '$phone' WHERE ID = 5884 ");
echo mysql_error();
}
else
{
echo "Failed";
}
?>
EDIT: Have you confirmed if it actually updates the DB?
Also you should also sanitise your input and consider rolling with mysqli instead of mysql_*
I made a simple sample on how to insert using AJAX and retrieving it then append it in a <div> after getting it. But I am having trouble on getting all the content of the table, it's returning a null values.
<div id="wrap-body">
<form action method="post">
<input type="text" name="username" id="username">
<input type="text" name="msg" id="msg">
<input type="button" id="submit" value="Send">
</form>
<div id="info">
</div>
</div>
jQuery:
<script>
$(document).ready(function (){
$('#submit').click(function (){
var username = $('#username').val();
var msg = $('#msg').val();
$.ajax({
type: 'POST',
url: 'get.php',
dataType: 'json',
data:'username='+username+'&msg='+msg,
success: function (data){
$('#info').append("<p> you are:"+data.username+"</p> <p> your message is:"+data.mesg);
}
});
});
});
</script>
PHP:
<?php
$host='localhost';
$username='root';
$password='12345';
$db = 'feeds';
$connect = mysql_connect($host,$username,$password) or die("cant connect");
mysql_select_db($db) or die("cant select the".$db);
$username = $_POST['username'];
$msg = $_POST['msg'];
$insert = "INSERT INTO info(user_name,message) VALUES('$username','$msg')";
if(#!mysql_query($insert)){
die('error insertion'.mysql_error());
}
$get = "SELECT * FROM info ";
$result=mysql_query($get)or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$return = $row['user_name'];
$return = $row['message'];
}
echo json_encode($return);
?>
Your while should create array and then do json_encode
Try below code
$data=array();
while ($row = mysql_fetch_array($result))
{
$data[] = array(
'username'=>$row['user_name'],
'mesg'=>$row['message']
);
}
echo json_encode($data);
exit
Now write your javascript success handler as below
$.ajax({
type: 'POST',
url: 'get.php',
dataType: 'json',
data:'username='+username+'&msg='+msg,
success: function (data){
$.each(data, function(i, item) {
$('#info').append("<p> you are:"+data[i].username+"</p> <p> your message is:"+data[i].mesg);
});​
}
});
There are several issues you have to fix, but you have to start with returning the same type as expected by the ajax call:
$return = array()
if ($row = mysql_fetch_array($result))
{
$return['username'] = $row['user_name'];
$return['mesg'] = $row['message'];
}
echo json_encode($return);