I am working on a company website where a search bar is used to search the database of customers and employees by there name.
I have the output of the below code (output 1)
but it only searches the firstname and last name individually like this in the output (output 4)i want to make it join together for searching both firstname and lastname.
I want to make a search like this (output 3)
I have this code so far...
index.php
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>INDEX PAGE</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="container all">
<br />
<h2 align="center">COMPANY NAME</h2><br />
<div class="form-group">
<div class="input-group">
<input type="text" name="search_text" id="search_text" placeholder="Search by Customer Details" class="form-control" />
</div>
</div>
<div id="result"></div>
</body>
</html>
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"fetch.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#result').html(data);
}
});
}
$('#search_text').keyup(function(){
var search = $(this).val();
if(search.length>=2){
if(search != '')
{
load_data(search);
}
}
else
{
load_data();
}
});
});
</script>
and 2nd file..
fetch.php
<?php
$connect = mysqli_connect("localhost", "root", "root", "users_db")or die("ERROR");
$output = '';
if(isset($_POST["query"]))
{
$search = mysqli_real_escape_string($connect, $_POST["query"]);
$query = "
SELECT * FROM users_users
WHERE firstname LIKE '%".$search."%'
OR lastname LIKE '%".$search."%'
AND lastname LIKE '%".$search."%'
OR link LIKE '%".$search."%'
";
}
else
{
}
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
$output .= '
<div class="otp">
</div>
';
while($row = mysqli_fetch_array($result))
{
$output .= '
<div class="oup">
<a href="
'.$row["link"].'
">
'.$row["firstname"].'
'.$row["lastname"].'
</a>
</div>
';
}
echo $output;
}
else
{
echo '';
}
?>
the above code has this output...(output 1)
output 1
and after typing the firstname when i press spacebar it blanksout like in (output 2)
output 2
i want to make the search continue after typing the firstname with spacebar in between..
something like this.. in the (output 3)
output 3
i am new at php javascript and sql so try to break it down for me.
thank you in advance.
can you guys give me some more tricks how to optimise more of this code.
Before i give my answer, I should say your code is open to SQL Injection. You should learn about Prepared Statements to solve this security issue.
Now to answer your question. For searching both firstname and lastname you should separate search term before searching. Something like this:
// --- Separate the search items
if ( !empty($search) ){
$searchWords = explode(' ', $search);
$searchTerms = array();
foreach ($searchWords as $word) {
$word = trim($word);
if (!empty($word)) {
$searchTerms[] = "(firstname LIKE '%$word%' OR lastname LIKE '%$word%')";
}
}
}
// --- Search each search items
$query = "SELECT * FROM users_users WHERE".implode(' AND ', $searchTerms);
Try this:
ALTER TABLE users_users ADD FULLTEXT(firstname, lastname, link);
$searchTerm = '+'.str_replace(' ','+',$search).'*';
$query = "SELECT * FROM users where MATCH(`firstname`,`lastname`,`link`) AGAINST (".searchTerm." IN BOOLEAN MODE)";
Related
Hello I'm a beginner in Ajax and PHP so sorry if my question is useless or stupid. But I am trying to do a live search with ajax and I have looked over and over internet but nothing could help me... so here I am! :-) I have 4 files one for the html, one to connect to the database, one for jQuery and the last one for the script in php. I have looked on the console with chrome and I can see that the ajax works but there is no output and I have no idea why... I'll leave you the code below and an early thank you! Also there might be some French in the code but it's just the variables and I will secure my connection to the database later. Thank you again.
Html :
<html>
<head>
<meta charset="utf-8" />
<title>live search test</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" src="search.js"></script>
</head>
<body>
<h1>LIVE SEARCH WITH AJAX TEST</h1>
<div class="search">
<input type="search" name="search" id="recherche">
</div>
<br>
<div class="resultat" id="resultat">
</div>
</body>
</html>
PHP to connect to the database:
<?php
$host="localhost";
$user="root";
$password="";
$db="smartphone";
$conn=mysqli_connect($host,$user,$password,$db);
?>
jQuery:
$(document).ready(function(){
$("#recherche").keyup(function(){
var recherche = $(this).val();
var data = 'motclef = ' + recherche;
if (recherche.length > 1) {
$.ajax({
type : "GET",
url : "fetch.php",
data : data,
success : function(server_response){
$("#resultat").html(server_response).show();
}
});
}
});
});
And the script in PHP:
include'connect.php';
if (isset($_GET['motclef'])) {
$motclef = $_GET['motclef'];
$q = array('motclef' => $motclef. '%');
$sql = "SELECT name FROM smartphone WHERE name LIKE :motclef";
$req = $conn ->prepare($sql);
$req -> execute($q);
$count = $req->rowCount($sql);
if ($count == 1) {
while ($result = $req -> fetch(PDO::FETCH_OBJ)) {
echo 'Smartphone :'.$result ->title.' ';
}
}else {
echo "Aucun resultat trouvé pour:". $motclef;
}
}
?>
Remove whitespace from 'motclef = '
var data = 'motclef= ' + recherche;
Other wise put underscore $_GET['motclef_'] in your PHP code(if you don't remove space then)
if (isset($_GET['motclef_'])) {
$motclef = $_GET['motclef_'];
$q = array('motclef' => $motclef. '%');
$sql = "SELECT name FROM smartphone WHERE name LIKE :motclef";
$req = $conn->prepare($sql);
$req->execute($q);
$count = $req->rowCount($sql);
if ($count == 1) {
while ($result = $req->fetch(PDO::FETCH_OBJ)) {
echo 'Smartphone :'.$result->title.' ';
}
}else {
echo "Aucun resultat trouvé pour:". $motclef;
}
}
Have a live search page as shown in livesearch.php below, when typing entries into the input box am not getting any results show under it. The html code and script in search.php are shown beelow.
search.php
<!DOCTYPE HTML>
<html>
<header>
<link href="css/main.css" rel="stylesheet" type="text/css">
<link href="css/search.css" rel="stylesheet" type="text/css">
</header>
<body>
<div id="searchContainer">
<div class="searchMainTitle">Search Schedules</div>
<div class="searchSubTitle">
<p>Enter any information you wish, this will search all schedule fields.</p>
</div>
<form role="form" method="post">
<input type="text" class="form-control" size="100%" placeholder="Enter Search Term(s) Here" id="keyword" />
</form>
<ul id="liveSearch"></ul>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#keyword').on('input', function() {
var searchKeyword = $(this).val();
if (searchKeyword.length >= 3) {
$.post('livesearch.php', { keywords: searchKeyword }, function(data) {
$('ul#liveSearch').empty()
$.each(data, function() {
$('ul#liveSearch').append('<li>' + this.title + '</li>');
});
}, "json");
}
});
});
</script>
</body>
</html>
The livesearch.php that is being referenced by the script is shown below
livesearch.php
<?php
session_start();
require 'dbconnect.php';
echo "Keyword: ".$_POST['keywords']."<br/><br/>";
$liveSearchArray = array();
if (!empty($_POST['keywords'])) {
$keywords = $connection->real_escape_string($_POST['keywords']);
$sql = "SELECT OWNER_SURNAME,OWNER_FIRSTNAMES,OWNER_TITLE FROM testucm_owners WHERE OWNER_SURNAME LIKE '%".$keywords."%'";
$result = $connection->query($sql);
if ($result->num_rows > 0) {
echo "We Have A Result, There Are ".$result->num_rows." Rows";
while ($obj = $result->fetch_object()) {
$liveSearchArray[] = array('id' => $obj->OWNER_SURNAME, 'title' => $obj->OWNER_TITLE);
}
} else {
echo "No Matches";
}
}
echo json_encode($liveSearchArray);
mysqli_close($connection);
?>
If a manually add a value for keywords into the livesearch.php query I get the correct results, however no resutls display if I enter search terms via search.php. I have partially test this by putting an alert after var searchKeyword = $(this).val();, this shows the correct term as typed in however still no results showing.
I suspect the error may be with this line of code:
$('ul#liveSearch').append('<li>' + this.title + '</li>');
Either that or for some reason the $liveSearchArray is not being passed back to the script, however I'm unable to determine where the error lies or how to fix it. Any help would be greatly appreciated
Maybe you should check the php return data.
here:
echo "We Have A Result, There Are ".$result->num_rows." Rows";
see,the return data is not pure json.
I think that may be the key.
When you expect data for "json", you have to keep the return data is only json ,not anything else.Otherwise ,the ajax will get an parse error which is not displayed directly,and your "success" function will not be executed.And it seems like you don't get the data,but actually it's because you get the wrong format data.
It works like this:
So I was following a tutorial and I came across the current problem. This is my first time using the ajax method. I copied and saved jQuery version 1.7.2.min.js in a folder. My php code seems to be working fine, the only thing that seems off is the code for the ajax part.
This code is in a folder called "includes"
<div id="messages">
<!--Javascript-->
<script type= "text/javascript" src= "script/jquery-1.7.2.min.js"></script>
<script type= "text/javascript" src= "script/auto_chat.js"></script>
</div><!-- Messages -->
This is the javascript in a folder called "script" named auto_chat
$(document).ready(function() {
var interval = setInterval(function() {
$.ajax({
url: 'script/Chat.php' ,
success: function(data) {
$('#messages').html(data);
}
});
}, 1000);
});
There is a file called Chat.php containing code that links to the database.
When it runs it should show all the messages inside of the database. Instead it gives me blank and not even errors. Can someone tell me whats wrong with my method?
This is the my Chat.php
<?php
require('../includes/database/connect.db.php')
function get_msg(){
$query = "SELECT `Sender`,`Message` FROM `chat`.`chat` ORDER BY `Msg_ID` DESC";
$run = mysql_query($query);
$messages = array();
while($message = mysql_fetch_assoc($run)){
$messages[] = array('sender' => $message['Sender'],
'message' => $message['Message']);
}
return $messages;
}
function send_msg($sender, $message) {
if(!empty($sender) && !empty($message)) {
$sender = mysql_real_escape_string($sender);
$message = mysql_real_escape_string($message);
$query = "INSERT INTO `chat` . `chat` VALUES (null,'{$sender}','$message')";
if ($run = mysql_query($query)){
return true;
}else{
return false;
}
}else {
return false;
}
}
if(isset($_POST['send'])){
if(send_msg($_POST['sender'],$_POST['message'])){
echo 'Message Sent';
}else{
echo 'Message Failed to sent';
}
}
$messages = get_msg();
foreach($messages as $message) {
echo '<strong>' . $message['sender'] .' Sent</strong><br />';
echo $message['message']. '<br /><br />';
}
?>
And this is all of my index.php
<!DOCTYPE html>
<?php
require('includes/core.inc.php');
function get_msg(){
$query = "SELECT `Sender`,`Message` FROM `chat`.`chat` ORDER BY `Msg_ID` DESC";
$run = mysql_query($query);
$messages = array();
while($message = mysql_fetch_assoc($run)){
$messages[] = array('sender' => $message['Sender'],
'message' => $message['Message']);
}
return $messages;
}
function send_msg($sender, $message) {
if(!empty($sender) && !empty($message)) {
$sender = mysql_real_escape_string($sender);
$message = mysql_real_escape_string($message);
$query = "INSERT INTO `chat` . `chat` VALUES (null,'{$sender}','$message')";
if ($run = mysql_query($query)){
return true;
}else{
return false;
}
}else {
return false;
}
}
if(isset($_POST['send'])){
if(send_msg($_POST['sender'],$_POST['message'])){
echo 'Message Sent';
}else{
echo 'Message Failed to sent';
}
}
?>
<html lang = "en">
<head>
<!--Page TItle --!>
<title>Chat Application </title>
<link type="text/css" rel= "stylesheet" href= "includes/main.css" />
</head>
<body>
<div id="input">
<form action = "index.php" method = "post">
<label>Enter Name:<input type = "text" name = "sender"/></label>
<label>Enter Message:<input type = "text" name = "message"/></label><br />
<input type = "submit" name = "send" value = "Send Message"/>
</form>
</div>
<div id="messages">
<?php
$messages = get_msg();
foreach($messages as $message) {
echo '<strong>' . $message['sender'] .' Sent</strong><br />';
echo $message['message']. '<br /><br />';
}
?>
<!--Javascript-->
<script type= "text/javascript" src= "script/jquery-1.7.2.min.js"></script>
<script type= "text/javascript" src= "script/auto_chat.js"></script>
</div><!-- Messages -->
</body>
</html>
After a lot of trial and error, we found out that the problem was a simple missing semicolon on chat.php:
require('../includes/database/connect.db.php');
:)
I have a web service written in php but I could not fetch data with jquery getJSON().
It's my web service and works fine.
<?php
include 'config.php';
$sql = "select s.id, s.title, s.content, s.date, s.confirm " .
"from sap s";
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->query($sql);
$sapList = $stmt->fetchAll(PDO::FETCH_OBJ);
$dbh = null;
header('Content-Type: application/json; charset=UTF8');
$data = array('items'=>$sapList);
echo json_encode($data,JSON_UNESCAPED_UNICODE);
//echo '{"items":'. json_encode($sapList,JSON_UNESCAPED_UNICODE) .'}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
?>
I am trying to develop a jQuery mobile app.and source codes:event.js I used for loop in event.js.because I want to pull data from multiple separate services.
var db=openDatabase('servicesDB','1.0','servcesdatabase', 2*1024*1024);
tablo();
var olaylar;
$('#eventListPage').bind('pageinit', function(event) {
console.log("geteventlist fonksiyon running");
getEventList();
});
function getEventList() {
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM services',[],function (tx,sonuc) {
var toplam=sonuc.rows.length;
var kayit="";
var id="";
var ad="";
var url="";
$('#olaylar li').remove();
for (var i=0;i < toplam; i++) {
kayit=sonuc.rows.item(i);
id=kayit.id;
ad=kayit.ad;
url=kayit.url;
$.getJSON(url+'?callback=?', function(data) {
olaylar = data.items;
$.each(olaylar, function(index, olay) {
/*var confirm="";
switch(olay.confirm){
case 0:
confirm="accept";
break;
case 1:
confirm="wait";
break;
case 2:
confirm="reject";
break;
}*/
$('#olaylar').append(
'<li><a href="eventDetails.html?id=' + olay.id + '">' +
'<img src="pics/mr.jpg"/>' +
'<h4>' + olay.title + '</h4>' +
'<p>' + olay.confirm + '</p>' +
'</a></li>');
});
$('#olaylar').listview('refresh');
alert("getjsondan cikti");
});
}
}, hata);
});
}
function tablo(){
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS services('
+'id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,'
+'ad VARCHAR(25) NOT NULL, url VARCHAR(100) NOT NULL)');
});
}
function hata(transaction, err){
alert("Hata oldu : "+err.message);
return false;
}
index.html
<!DOCTYPE HTML>
<html>
<head>
<title>Personel Listesi</title>
<meta name="viewport" content="width=device-width,initial-scale=1" />
<link rel="stylesheet" href="css/styles.css" />
<link rel="stylesheet" href="css/jquery.mobile-1.4.3.css" />
<link rel="stylesheet" href="css/jquery.mobile-1.4.3.min.css" />
</head>
<body>
<div id="eventListPage" data-role="page">
<div data-role="header" data-position="fixed">
<h1>Event List</h1>
</div>
<div data-role="content">
<ul id="olaylar" data-role="listview" data-filter="true"></ul>
</div>
</div>
<script src="js/jquery-2.1.1.min.js"></script>
<script src="js/jquery.mobile-1.4.3.min.js"></script>
<script src="js/events.js"></script>
<script src="js/eventDetails.js"></script>
</body>
</html>
I tried $.getJSON(...){ alert("in getjson"); but that does not work. this alert.getjson function does not work. But it works very well before, now the getjson function returns blank as if no data has been retrieved.. I need your help,thanks!
I am little doubt about '{"items":'. json_encode($sapList,JSON_UNESCAPED_UNICODE) .'}'. I am not sure whether the above piece of code frame proper json.
The better way is create your JSON structure in PHP associate array itself and then generate the JSON in single stroke like as follows,
<?php
// Some code
$data = array('item'=>$sapList);
echo json_encode($sapList);
?>
Note: Since I haven't tested my code and it is GET request, you can test your code by directly type the URL in browsers address-bar. And copy and paste printed code in chrome's console and validate them in Javascript.
OR
Use online JSON validator like http://jsonlint.com/
Here is my index.html page code:-
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<HTML>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</meta>
<title>School</title>
<script type="text/javascript" src="script/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="my_script.js"></script>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div style="margin:auto; width:1000px;">
<div class="flt topblock"> Play School
<br/><br/>
<div>
<form id='myform' method='post' action='welcome.php' >
<span class="flt1 lp_txtlog">Email ID</span>
<input name="username" type="text" id="username" class="flt lp_textbox" />
<br />
<span class="flt1 lp_txtlog2">Password</span>
<input name="password" type="password" id="password" class="flt lp_textbox2" />
button id="submit" class='flt lp_button'>Login</button>
</form>
<div id="ack"></div>
</div>
</div>
</div>
</body>
</html>
Here is my_script.js code :-
$("button#submit").click(function() {
if ($("#username").val() == "" || $("#password").val() == "")
$("div#ack").html("Please enter both username and password");
else
$.post($("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(data) {
$("div#ack").html(data);
});
$("#myForm").submit(function() {
return false;
});
});
and below is my welcome.php code :-
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<?php
$con = mysql_connect('localhost', 'root', 'Wahegurug#9');
mysql_select_db('test', $con);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
$sql = "SELECT * FROM user ";
$res = mysql_query($sql);
if ($row = mysql_fetch_array($res)) {
if ($row['Username'] == $_POST['username']) {
if ($row['Password'] == $_POST['password']) {
echo'login successful';
} else {
echo'login failed';
}
}
}
?>
</body>
</html>
Details are :- I have made this project in Netbeans 7.3 and using xampp server. I have created a simple login page and am trying to use javascript to prevent the page submitting if the wrong credentials are entered.
In my_script.js I'm using a div with id ack to show the user a success or error message.
My problem is that the user is still being redirected to welcome.php (my form's target) even if the wrong credentials are entered. How can I prevent this from happening?
What you need to do is prevent the default action.
Change
$("button#submit").click( function() {
to
$("button#submit").click( function(event) {
event.preventDefault();
Also you are explicitly calling the submit function here:
$("#myForm").submit(function() {
return false;
});
Try removing this code as well, it is likely resolving prior to the $.post call finishes
Lastly your jquery code should be wrapped in a document.ready block ...
$(document).ready(function(){
$("button#submit").click(function(event) {
event.preventDefault();
if ($("#username").val() == "" || $("#password").val() == "")
$("div#ack").html("Please enter both username and password");
else
$.post($("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(data) {
$("div#ack").html(data);
});
});
});
As for your welcome.php page this would probably serve you better.
<?php
$con = mysql_connect('localhost', 'root', 'Wahegurug#9');
mysql_select_db('test', $con);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
$sql = "SELECT * FROM user where Username = '".mysql_real_escape_string($_POST["username"])."'";
$res = mysql_query($sql);
if ($row = mysql_fetch_array($res)) {
if ($row['Password'] == $_POST['password']) {
echo'login successful';
return;
}
}
echo'login failed';
?>
This will only get and check the password of the user in question and will return a failure in all cases. Plus I removed the framing page markup since it is being injected into an existing page.
$(document).ready(function(){
$("button#submit").click(function(event) {
var is_send=true;
var username=$("#username").val();
var password=$("#password").val();
if (username == "" || $(password == "")
{
$("div#ack").html("Please enter both username and password");
is_send=false;
}
else
$.post($("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(data) {
$("div#ack").html(data);
});
if(is_send==false)
{
return false;
}
});
});
try this, it work for me....
you may try like this .
$("button#submit").click( function(e) {
e.preventDefault();//Will prevent the default event of click
});