I am trying to use the jqueryui autocomplete to load services from mysql database on my form but nothing happens?? please help me or tell me where am wrong
my html
<input type="text" id="actual_service" />
my javascript script
$("#actual_service").autocomplete({
source: "http://dev_svr/medportal/search.php?callback=?",
dataType: "jsonp",
minLength: 1
});
this is search.php
$con = mysql_connect('localhost', 'dev', '');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("medrep", $con);
$term = trim(strip_tags($_GET['term']));
$qstring = "select prod_id id,prod_name value FROM product where prod_type='SERVICE' and prod_name LIKE '%".$term."%' ORDER BY prod_name;";
$result = mysql_query($qstring);
while ($row = mysql_fetch_array($result,MYSQL_ASSOC))
{
$row['value']=htmlentities(stripslashes($row['value']));
$row['id']=(int)$row['id'];
$row_set[] = $row;
}
header("Content-type: application/json");
echo json_encode($row_set);
when i load that page nothing happens on that inputbox when i type anything.
this is a sample output of http://dev_svr/medportal/search.php?term=ct when i limit the sql to 3 rows
[{"id":50,"value":"ABDOMEN SUPINE&ERECT(2VIEWS)"},{"id":142,"value":"CT BRAIN"},{"id":115,"value":"CT CERVICAL SPINE"}]
1. Your jQuery code is not correct
You are not getting data from a remote domain, therefore you don't need a JSONP request.
It should be:
$("#actual_service").autocomplete({
source: "http://dev_svr/medportal/search.php",
minLength: 1
});
2. Your JSON object is not correct.
Each json object for the autocomplete should have two values: label and value (no ID). If you want the product id to be the value of the selected item, and the product name to be the text that is shown to the user, then the json object should be like:
[{"value":50,"label":"ABDOMEN SUPINE&ERECT(2VIEWS)"},{"value":142,"label":"CT BRAIN"},{"value":115,"label":"CT CERVICAL SPINE"}]
Edit
From what you mentioned in the comments, try this jQuery code:
$('#actual_service').autocomplete({
source: function( request, response ) {
$.ajax({
url: 'http://dev_svr/medportal/search.php',
dataType: 'jsonp',
data: { term: request.term },
success: function( data ) {
response( data );
}
});
},
minLength: 1
});
Related
I have this page that consists of a list of user posts / message. When a post is liked, I want it to reflect on all other users, and based on my research setInterval can get the job done by refreshing a specific content for a number of seconds. Currently, I'm having trouble looping through all the user messages and show the updated number of likes. What's happening is that the number displayed is constantly changing and looping through all the values for a single post. Example: If I have 1, 0, and 2 likes respectively on three different posts, the number for the first post changes to 1, 0, and 2 instead of just showing "1". I'm kind of a beginner when it comes to AJAX.
Here's my code:
Jquery / Ajax
function refreshPostLikes() {
setInterval(function() {
$(".posts .id").each(function() { //get id for each post
var postid = $(this).attr("value");
updatePostLikes(postid); //pass the postid variable
});
}, 1000);
}
function updatePostLikes(postid) {
$.ajax({
url: "/main/refresh-post-like.php",
type: "post",
data: {postid: postid}, //send data to php file
success: function(data) {
$(".posts .like").html(data); //output number of likes
}
});
}
PHP Query
<?php
require_once('../connection.php');
$postID = $_POST['postid'];
$likeCountQuery = "select count(*) as total_likes from posts_likes WHERE like_status=1 AND post_id=".$postID; //query number of posts with a like
$likeQueryResult = mysqli_query($conn, $likeCountQuery);
while($likeNumber = mysqli_fetch_assoc($likeQueryResult)) {
$likes = $likeNumber['total_likes'];
if($likes != 0) {
echo $likes;
}
else {
echo '';
}
}
?>
Still not sure this is the best way to go, but the reason your code doesn't work is due to omitting the postid when updating the HTML in the success part of your code.
function updatePostLikes(postid) {
$.ajax({
url: "/main/refresh-post-like.php",
type: "post",
data: {postid: postid}, //send data to php file
success: function(data) {
$(".posts .like").html(data); //output number of likes
}
});
}
with this command $(".posts .like").html(data); //output number of likes
You are updating all the divs which have these classes specified with the same value.
Set postid as id for the div and change the command to
$("#postid").html(data); //output number of likes
is constantly changing and looping through all the values for a single
post
This happens because there is no reference to the post that needs to be updated. What you are doing now is to cycle through all the elements that have the ".posts .id" classes, therefore the update applies to all the posts and not the single one. You should modify your function to make it update only that post (try passing it a unique id in html)
Where N is the id of your post. (For example postid)
Then update the value using this
function updatePostLikes(postid) {
$.ajax({
url: "/main/refresh-post-like.php",
type: "post",
data: {
postid: postid
}, //send data to php file
success: function(data) {
//$(".posts .like").html(data); //output number of likes
$("#post-"+postid).html(data); // in this way we're get the right post
}
});
}
function refreshPostLikes() {
$(".posts .id").each(function() { //get id for each post
var postid = $(this).attr("value");
updatePostLikes(postid); //pass the postid variable
});
setTimeout(refreshPostLikes, 1000); //Check every sec if there are update
}
setTimeout(updateChat, 1000); //Start the check
Prevent SQL Injection
Escape is not enough
<?php
require_once ('../connection.php');
$postID = $_POST['postid']; //Escape this value before use inside the query see linked question
// NEVER TRUST USER INPUT
//$likeCountQuery it could be used for perform a SQL Injection NEVER TRUST USER INPUT
//NEVER !!!
$likeCountQuery = "SELECT COUNT(*) AS total_likes FROM posts_likes WHERE like_status=1 AND post_id=".$postID; //query number of posts with a like
$likeQueryResult = mysqli_query($conn, $likeCountQuery);
while ($likeNumber = mysqli_fetch_assoc($likeQueryResult))
{
$likes = $likeNumber['total_likes'];
if ($likes != 0)
{
echo $likes;
}
else
{
echo '';
}
}
?>
I don't know what I'm doing wrong. I tried to use autocomplete with json, but I always get the complete data. I expect filtered data from the user input.
JS:
$( "#tags" ).autocomplete({
source: "/script.php",
minLength: 2,
select: function(event, ui) {
var url = ui.item.id;
if(url != '#') {
location.href = '/blog/' + url;
}
},
open: function(event, ui) {
$(".ui-autocomplete").css("z-index", 1000);
}
});
PHP:
$result = $paed_db->prepare('SELECT data FROM table');
$result->execute();
$a_json = array();
while($data = $result->fetch(PDO::FETCH_OBJ)) {
$a_json_row["value"] = $data->data;
array_push($a_json, $a_json_row);
}
$json = json_encode($a_json);
print $json;
exit;
JQueryUI does nothing to filter the results - you need to do the search in your query on the PHP script. JQueryUI sends the user input via a GET request, so you can access it using:
$search = $_GET['term'];
(See http://api.jqueryui.com/autocomplete/#option-source)
So you can then use that $search variable in your prepared query to select the appropriate rows from the table. For example, if you had a column called name that you wanted to search on:
$result = $paed_db->prepare('SELECT data FROM table WHERE name LIKE :search');
$result->execute(array('search' => '%'.$search.'%'));
It is because you are always returning everything. Look at your query. You don't filter the query by the user input from the autocomplete. The user's input is passed automatically as a URL param called term. Your query should use that to filter the data. See more here: http://api.jqueryui.com/autocomplete/#option-source
I need a PHP array that stores data from MySQL and later use in JQuery.
The sample data from MySQL table
student_id class_id score
001 01 A
001 02 B
002 02 A
In JQuery, I would like to access these data as data.student_id[i].class_id[i].score
How can I construct the PHP array?
My current codes in view_student.php (can choose more than one student_id, class_id)
$student_id = $_POST['student_id'];
$class_id= $_POST['class_id'];
$student_array = array();
for($j=0;$j<sizeof($student_id);$j++) {
$query = "SELECT class_id, score FROM student";
$query .= " WHERE student_id='".$student_id[$j]."'";
for($i=0;$i<sizeof($class_id);$i++){
if($i==0) {
$query .= " AND class_id=".$class_id[$i];
} else {
$query .= " OR class_id=".$class_id[$i];
}
}
if($student_sql=$connection->query($query)){
$student_php = array();
$student_row_php = array();
while($student_row_sql=$student_sql->fetch_array(MYSQLI_ASSOC)){
$student_row_php["student_id"]=$sale_row_sql['student_id'];
$student_row_php["score"]=$sale_row_sql['score'];
array_push($student_php, $student_row_php);
}
}
$student_array[$student_id[$j]]=$student_php;
}
echo json_encode($student_array);
In JavaScript, I need data.student_id[0].class_id[0].score instead of data.001[0].score
<script>
$(document).ready(function() {
$('form').submit(function(event) {
event.preventDefault(); /
var postForm = new FormData(this);
$.ajax({
type : 'POST',
url : 'view_student.php',
data : postForm,
processData: false,
contentType: false,
dataType : 'json',
success : function(data) {
$('#score').html('<font color="#FFFFFF"> <strong>'+data.001[0].score+'</strong> </font>');
}
});
});
});
Try to add this so that it resets the key indexing:
$student_array = array_values($student_array); // simple reindex
echo json_encode($student_array);
Since in the end they are already grouped by the students id, $student_id[$j] (contains 001, 002, etc), reset your keys so that you can access them thru your numeric indices, instead of using .001 which is the student id
Hi dear friends,
I hope u are all fine.
I want to make a next button for getting more data from mysql database.
For example:
$sql = mysql_query("SELECT * FROM table LIMIT 0,7");
It get 7 rows.For next data code is that.
$sql = mysql_query("SELECT * FROM table LIMIT 7,7");
I can i do that using ajax.
As you can see in many website like facebook,When you click on comment it give a limited
comment and when you click on more comment it give more and so on.In this proccess you can see
that the other content of page does not change.It means it can use ajax and how can I do that in ajax.
Please help me.Thanks.
your ajax would be something like this
var numberOfdata = 0;
$('#button').click(function () {
$.ajax({
url: 'load.php',
data: {
'limit' : numberOfdata,
// other data ...
},
type : 'post',
// other parameters...
}).success(function (data) {
// adding data to your website
numberOfdata += 7;
});
});
and in your server side, you could do something like this
... other operations
mysql_query("SELECT * FROM table LIMIT " . $_POST['limit'] . ",7");
... continuting the work
Note: You should be able to handle SQL injections on your own.
Edit: please note that mysql_query is not recommended.
You have to send the current comments count via Ajax, get the new ones from the response and display them.
Javascript:
$(document).ready(function() {
$('a.pagination-more').click(function() {
var current_comments_count = $(this).data("current_comments_count");
$.ajax({
type: "POST",
url: "pagination/pagination_ajax_more.php",
data: { "limit_start":current_comments_count },
beforeSend: function() {
$('a.pagination-more').html('<img class="loading-gif" src="pagination/loading.gif" />');
},
success: function(html){
$("#more").remove(); // This is the "More" button. It is appended to the end again in the 'html' variable
$("ul#updates").append(html);
if($("a#end")[0]) {
$("div#more").remove();
}
}
});
return false;
});
});
On the PHP side you just get $limit_start, get results from the database and echo the html like:
$limit_start = $_POST['limit_start'];
$query = mysql_query("SELECT COUNT(*) FROM `table` LIMIT 0, $limit_start");
$current_comments_count = mysql_num_rows($query);
$query = mysql_query("SELECT * FROM `table` LIMIT $limit_start, 7");
while($row = mysql_fetch_assoc($query)) {
echo '<li>
blah blah...
</li>';
}
if(mysql_num_rows($query) == 7)
echo '<div id="more"><a data-current_comments_count="$current_comments_count" class="button pagination-more" href="#">More</a></div>';
else
echo '<div id="more"><a id="end" class="button pagination-more" href="#">The button will be removed from jQuery...</a></div>';
Of course it is strongly recommended to secure your application and not to use only mysql_query(). This code is working but I removed some other stuff and didn't test it now. So, some errors may occur.
search.php
$text = $mysqli->$_POST['term'];
$query = "SELECT name FROM males WHERE name LIKE '%" . $text . "%' ORDER BY name ASC";
$result = $mysqli->query($query);
$json = '[';
$first = true;
while($row = $result->fetch_assoc())
{
if (!$first) { $json .= ','; } else { $first = false; }
$json .= '{"value":"'.$row['name'].'"}';
}
$json .= ']';
echo $json;
index.php
1) HTML
<body>
Text: <input type="text" id="autocomplete" />
</body>
2) jQuery
$( "#autocomplete" ).autocomplete({
source: function(request, response) {
$.ajax({ url: "http://localhost/testing/auto/search.php",
data: { term: $("#autocomplete").val()},
dataType: "json",
type: "POST",
success: function(data){
response(data);
}
});
},
minLength: 2
});
When I type 2 letters, it gives me all the names in my database even if these two letters do not match any of the names.
How does that happen and how do I fix it?
Looks like my comment worked as an answer, hence this answer.
What does $mysqli->$_POST['term'] do? I think you should have $text = $_POST['term'];. This should work.
Change the PHP to
$text = $_POST['term'];
$query = "SELECT name FROM males WHERE name LIKE '%" . $mysqli->real_escape_string($text) . "%' ORDER BY name ASC";
$result = $mysqli->query($query);
echo json_encode($result->fetch_all(MYSQLI_ASSOC));
You forgot to escape the input to prevent SQL injections. Additionally, use #mu's answer to fix your front-end code.
Your source callback isn't doing what you think it is. The current contents of the autocompleter are in request.term, not in $("#autocomplete").val(). You're sending an empty value for term back to your PHP and then your SQL looks like:
SELECT name FROM males WHERE name LIKE '%%' ORDER BY name ASC
which of courses matches everything in your males table. Your source callback should look like this:
source: function(request, response) {
$.ajax({
url: "http://localhost/testing/auto/search.php",
data: { term: request.term },
dataType: "json",
type: "POST",
success: function(data) {
response(data);
}
});
}
The jQuery-UI widget probably manipulates the DOM a fair bit so the #autocomplete input element may not have anything useful in it until the autocompleter has a final value for it.
For reference, here's what the fine manual has to say:
The third variation, the callback, provides the most flexibility, and can be used to connect any data source to Autocomplete. The callback gets two arguments:
A request object, with a single property called term, which refers to the value currently in the text input. For example, when the user entered "new yo" in a city field, the Autocomplete term will equal "new yo".
First make sure that your search.php is working. Switch to $_GET['term'] and run the page directly until you get the data you wanted.
I would personally change the query from from LIKE '%text%' to LIKE 'text%'.
After that use Firebug to examine the parameters that are transferred to the search.php with an AJAX call. BTW, are you sure that your jquery code is correct?
I think is your sql query. U were using
$query = "SELECT name FROM males WHERE name LIKE '%$text%' ORDER BY name ASC"
if your name list like
Aaron
Alexander
Maartha
...
If you type 'AA', the above query will result : Aaron, Maartha. Because the query will search matching given string between the whole strings.
% text % means the query result will ignore the left and right result.
if you're looking for names field data you supposed to use query
$query = "SELECT name FROM males WHERE name LIKE '$text%' ORDER BY name ASC"
If you type 'AA, it will result : Aaron.
Note that jQuery only returns what you're asking to the database.
Use $_REQUEST['term'] instead $_POST['term'].