Live Dynamic search of MySQL table using jquery and php - javascript

I am sure there are a number of articles covering this topic, but every piece of code I try just doesn't seem to work. If this has been answered somewhere else already, I am sorry that I could not find it.
I am trying to create a live search that displays all data in my table until someone starts typing in an input field. As soon as they start typing a key, I want to run a select query on my table to narrow the results if any of the columns contain the string that is currently being typed (kind of like how google starts showing you results as you type in the search bar).
My code seems to work up until I try to use either $.get or $.post to interact with my php file that runs the MySQL search. I am kind of new to web development and have been teaching myself as I go along, but this one has stumped me for 2 days now. Here is the code I currently have (although I have tried about 20 different versions):
jQuery:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
document.getElementById("search").onkeyup(searchScript());
function searchScript(){
var search = $("#search").val();
if(search==""){
return;
}
else{
$.get("resultspage.php",{search : search},function(result){
$("#results").html(result);
}});
}
</script>
<table id="results">
<?php
<...var assignments storing my db login data...>
$con=mysqli_connect($host,$username,$password,$database);
$sql="SELECT * FROM Registration";
if(mysqli_query($con,$sql)){
$result=mysqli_query($con,$sql);
}
else{
echo "error: " . mysqli_error($con);
}
while($row=mysqli_fetch_array($result))
{
<...code that displays the results...>
?>
</table>
My PHP file
$search=$_GET['search'];
<...variables storing log in data...>
$con=mysqli_connect($host,$username,$password,$database);
$sql="SELECT * FROM Registration WHERE CONCAT(fName,lName,storeName,numLocations,primaryPhone,secondPhone,email,products) LIKE %$search%";
if(mysqli_query($con,$sql)){
$result=mysqli_query($con,$sql);
}
else{
echo "error: " . mysqli_error($con);
}
while($row=mysqli_fetch_array($result))
{
<...code that displays results....>
}
Any help would be much appreciated! Thank you.

Recognizing that jquery is another mountain to climb, I would still learn & use it for it's simplicity. Once the data has been retrieved from the server, use jquery to hide the values not starting with or containing the entered value (.match() below), instead of repeated calls to the server.
Not knowing the structure of your table, a framework you might try:
$( "#search" ).keyup(function() {
// Test search letter entry is working
alert( "Handler for .keyup() called." );
var s = $("#search").attr("value"); // Typed in letter
// Pass an array of table contents
// there are a couple ways you could approach the 'gathering' of table items...
$(".individual-item-class").each(function(index, element) {
if (!element.match(/s/))
$(element:parent).css("display","none");
else
$(element:parent).css("display","table-row")
}):
});
This code will not get you off the ground, but pointed in a direction.
You can learn about selectors and a few jquery functions. Used here are each(), attr() and css().

Related

how can i prevent to insert data in database when there is duplicate

This is my php code that will put the inserted data to database and will prevent to insert data if there is duplicate.
include('session.php');
$cid="";
$chat_name=$_POST['chatname'];
$chat_password=$_POST['chatpass'];
$sql3="SELECT * FROM chatroom where chat_name='$chat_name'";
$query=mysqli_query($conn,$sql3);
if(mysqli_affected_rows($query) == 1){
echo("<script>alert('ee');</script>");
}
else{
mysqli_query($conn,"insert into chatroom (chat_name, chat_password, date_created, userid) values ('$chat_name', '$chat_password', NOW(), '".$_SESSION['id']."')");
$cid=mysqli_insert_id($conn);
mysqli_query($conn,"insert into chat_member (chatroomid, userid) values ('$cid', '".$_SESSION['id']."')");
echo $cid;
}
this is jquery code
$(document).on('click', '#addchatroom', function(){
chatname=$('#chat_name').val();
chatpass=$('#chat_password').val();
$.ajax({
url:"add_chatroom.php",
method:"POST",
data:{
chatname: chatname,
chatpass: chatpass,
},
success:function(data){
window.location.href='chat.php';
}
});
});
When I enter a duplicate data the alert in echo don't execute but it continue to put in database although it is duplicate. THANKS FOR THE HELP !
First thing, I would change
if(mysqli_affected_rows($query) == 1){
to
if(mysqli_affected_rows($query) >= 1){
this will make sure that even if there are already duplicates, no more duplicates can be added
There are however some bigger issues with the code that you should address
You should add a uniqueness constraint on your chatname (in the database). This will make it that even if your code is wrong, you will not be able to add duplicate entries to your table.
You are receiving user input and just adding it into your sql querys. This leaves your database open to SQL injection which basically means, anyone can do anything to your database (delete things, add things, etc.). You should look into prepared statements to solve this issue

Minor difficulties with Ajax and PHP interaction

I working in CodeIgniter and I am trying to spit out all of the items I have in a table and order them as they should be using the dropdown. I want it to happen without page reload and without submit buttons, so I am using this jQuery function to make immediately react, when it is changed:
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
alert(data);
});
});
Inside you can see the $.post method, with wich I am trying to send the data to php script (orderValue).
After that, I am getting an alert (not even sure, why do I need it (Maybe to check if everything is ok there))
In PHP, I am receiving the chosen select option and assigning a variable ($data['people']) to the results of MySQL query (that is placed in the model) to be able to access it withing the view. This - $_POST['val'] represents, how can I order the list (select * from people order by $theorder" ($theother is just a variable inside the query function. It recieves the value of $_POST['val'])).
if(isset($_POST['val'])) {
$data['people'] = $this->database->listPeople($_POST['val']);
exit;
}
After that I recieve this variable in the view and I am running foreach loop to take different parts of the array(name of the person, his age, etc..) and placing it in the way they should be.
The problem is - if I do that without ajax, when I have static order by value - everything works fine. I did not mean that was the problem :D, the problem basically is that is doesn't work with ajax... I was trying to recieve the array in the js callback and create a layout using
$.each(eval(data), function() {
$('#container').text('<div>' + eval(res).name + '</div>');
});
But that was also a failure...
How should I organize and create my code to make everything work properly?
I am kinda new to Ajax, so I hope I'll really learn how to do that from you guys. I already searched through the whole internet and have seen a lot of ajax tutorials and other kind of material (e. g. StackOverflow), but I still can't get, how can I do all of that in my particular situation. I have wasted already about 12 hours trying to solve the problem and couldn't do that, so I hope You will tell me if there is any useful salvation.
Thank you for your consideration.
Hi the skinny is you need 3 parts to make ajax work,
serverside code to generate the page
ajax ( clientside ) to make the call and respond
seperate serverside to receive it.
Also it will be easier to replace the table completely then to pick out elements. But that is up to you.
So say we have the page with our ajax call
<script type="text/javascript" >
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
alert(data);
});
});
</script>
Now you seem to have some json response I'll assume you get this from the alert above;
[{"id":"1","name":"Nick","age":"18"},{"id":"2","name":"John","age":"23"}]
I'll also assume that this comes from something like
echo json_encode( array( array('id'=>1, ...), array('id'=>2 ...) .. );
It's important before doing the echo that you tell the server that this is json, you do this using a header, but you cannot output anything before the header, and after the json header all output must be in the json format or it wont work, it's like telling the browser that this is html, or an image etc. what the content is.
Header("Content-Type: application/json");
echo json_encode( ....
You can get away without doing this sometimes, but often you'll need to use eval or something, by telling the browser its json you don't need that. Now doing an alert is great and all but if you see the string data [{"id": .. your header is wrong, you should get something like [object] when you do the alert.
No once we have a factual Json object we can make use of all that wonderful data
<script type="text/javascript" >
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
$.each(data, function(i,v){
alert(v.id);
alert(v.name);
});
});
});
</script>
This should loop through all the data and do 2 alerts, first the id then the name, right. Next it's a simple matter of replacing the content using .text() or .append()
<script type="text/javascript" >
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
$.each(data, function(i,v){
$('#test').append('<p>'+v.id+'</p>');
});
});
});
</script>
<p id="test" ></p>

Update mysql database with jquery array using ajax

I am needing a little help with updating a mysql table from data in an jquery array using ajax. I have tried searching for similar issues but could not find anything, or maybe I do not know the correct terms to search... I'm still fairly new to web dev/coding.
I'll try explain what I am trying to do as clearly as I can. I have a page with seats which users select by clicking on them, upon clicking the seat ID is added in its own span tag in a kind of shopping cart area on the left of the page. This works fine.
Upon checkout my js file is able to pick up these seat ID's in an array, but from here I am unsure of how to properly send this array to the php file, and then for the php file to read the seat ID's from the array and update the relevant seat rows to change the availability from 1 to 0 (this is using ajax).
Here is my code:
checkout.js
$(document).ready(function(){
$('#checkout').click(function(){
var status = sessionStorage.getItem("username");
if(sessionStorage.getItem("username")){
var tickets = [];
$("#myTickets").find("span").each(function(){ tickets.push(this.id); });
var type = "POST",
url = "scripts/sendSeatDetails.php";
console.log(tickets);
$.ajax ({
url:url,
type:type,
data:tickets,
success: function(response){
if(response == 5){
alert("Seat update query failed");
} else {
alert("success");
}
}
});
} else {
alert("Before purchasing please log in. If you do not have an account please register.");
}
});
});
In the console log this shows: ["A2", "A3", "A4"] (if I have selected seats with ID A2, A3, A4 etc).
sendSeatDetails.php
<?php
include("dbconnect.php");
$myseats=$_POST['tickets'];
$query="update seats set status='0' where seatnum=";
for($i=0;$i<count($myseats);$i++){
$query.="'$myseats[$i]'";
if($i<count($myseats)-1){
$query.=" || seatnum=";
}
}
$link = mysql_query($query);
if (!$link) {
echo 5;
}
?>
This returns the alert showing success, but this is not true as the tables are not being updated. Can anyone help me with this or point me in the right direction?
I appreciate your help, and hopefully will be able to contribute to this site when I am at a better skill level in the future.
Many Thanks.
To send an array in jQuery you have to serialize it then parse it in the PHP file:
data: tickets.serialize(),
...
parse_str($_POST['data'], $data);
And then you treat it as an ordinary array.
Run update query one by one.
$myseats=$_POST['tickets'];
$flag=0;// Total successful updates
$myseats=explode(',',$myseats);
for($i=0;$i<count($myseats);$i++){
$query="update seats set status=0 where seatnum='".$myseats[$i]."'";
$link = mysql_query($query);
if (!$link) {
$flag=$flag+1;
}
}
echo $flag;die;
Check response. it will be number of updated rows.

JQuery UI Autocomplete is not returning any results to the page

I'm using the JQuery UI Autocomplete Widget to show suggested searches to users as they type into my search bar. However I'm getting a problem whereby the results are not appearing to the user as they type.
This is my script:
var $j = jQuery.noConflict();
$j(document).ready(function(){
$j("#tag_search").autocomplete({
source:'autocomplete_tags.php',
dataType: 'json',
minLength:1
});
});
This is the autocomplete_tags.php:
require_once '../includes/preheader.php';//connects to db
$term = $_GET["term"];//Get the search terms.
//Select tags from the database based on the specified search keyword
$query = "SELECT * FROM tag WHERE NAME LIKE '".$term."%' ORDER BY NAME ASC";
$json=array();
$db->query($query);//Query the DB.
//Parse through the results and store in an array
while($db->next()){
$json[]=array(
'id' => $db->get('id'),
'value'=>$db->get("name"),
'label'=>$db->get("description")
);
}
//Autocomplete JQuery UI expects a Json Array so encode and echo.
echo json_encode($json);
If I visit this url I can see a json array in the browser with the results, which makes me believe that it is working as it should, but for some reason the results are not showing.
http://my-site.tld/includes/autocomplete_tags.php?term=ag
Output:
[{"id":"29","value":"Agriculture","label":"This is a tag about agriculture and farming"}]
Also, I've checked in my console that the file is being found correctly when the user is typing and I am getting a 200 response code.
Does anyone know what might be causing this? I've implemented a similar feature on another site and it worked no problem. Could it be a styling issue?
Ok, very stupid of me not to realise this but rather than deleting the question, for anyone else who might be trying to do the same thing you must make sure that you include the jquery-ui css file. Just place this in the header of your site:
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.0/themes/smoothness/jquery-ui.css" />
In terms of my post above, all the code was correct and working as it should, the only thing missing was the above stylesheet.

Ajax and jquery not sending data correctly to php

I created a basic form that uses jquery (ajax) to send data to php. PHP should insert a new record based on the data to a mysql database. The reason for this is because I want to make insertions to the database without having to submit the whole form and then use the submit action for something else later. It seems that the jquery works fine since the alert() shows the correct output for the variables, but the PHP does not insert the data and I don't get an error. I can't figure out why this isn't working? I think it is a problem with my $post() because the function underneath does not execute but I can't pinpoint the error. Any help debugging this would be really appreciated. Or if anyone knows another way to get the same functionality that would be great too? Thanks. (The code below works fine now. I figured out it was a type cast error, and I fixed it. Hopefully someone can find this useful!)
<script type="text/javascript">
function submitgrade(){
alert("In it");
var classID = $("#classSelect").val();
var student = $("#studentSelect").val();
var exam = $("#Exam").val();
var grade = $("#grade").val();
alert(classID+" - "+student+" - "+exam+" - "+grade);
$.post('submitgrade.php',{postclassSelect:classID,poststudentSelect:student,postExam:exam,postgrade:grade}, /*1*/
function(data){
$("#grade").html("");
});
};
</script>
<?php /*submitgrade.php*/
$con=mysqli_connect("localhost","root","","studentbase");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$classID = $_POST['postclassSelect'];
$studentID = $_POST['poststudentSelect'];
$examID = $_POST['postExam'];
$grade = $_POST['postgrade'];
echo $studentID[0]." examID: ". $examID[0];
$gradequery = "INSERT INTO grade VALUES(".intval($studentID).", '".$classID."', ".intval($examID).", ".intval($grade).");";
$result = $con->query($gradequery);
while($row = $result->fetch_assoc())
{
echo "<br /><p>Grade of ". $grade." submitted for exam ". $row['exam_id'] ." in ". $row['class_ID'] ."</p>";
}
?>
Have you include this line in your html page ??
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
An example is here again, may help you
<script>
$(document).ready(function(){
$("input").keyup(function(){
txt=$("input").val();
$.post("my_page.asp",{suggest:txt},function(result){
$("span").html(result);
});
});
});
but your code seems correct too buddy !!
I suggest to continue debugging by attaching an error handler to your $.post call, your code could look this:
$.post('submitgrade.php', {postclassSelect:classID,poststudentSelect:student,postExam:exam,postgrade:grade})
.done(function(response) {
// success
}).fail(function(response) {
// failure
});
Further more you should check:
Is the script running on a server? ajax might not work on a file:/// address
Is the path from javascript location to php file correct?
what do the browser developer tools say about the request that is initiated?
I fixed it. It was actually just a syntax error in my SQL and a type difference error with one of my database columns. The $grade variable is passed into PHP as a string. Once I wrapped all of my variables in intval() it worked as intended. Stare at the code to long, sometimes you go blind. Haha.
Thank you omnidan for the tip about sanitization. Here is a good guide that I used to apply it to my app:
http://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data

Categories