I'm trying to accomplish autocomplete task with the help of ajax (jQuery). Lets have a look at scripts
here is html =>
<input type="text" name="user_key" id="user_key">
here is javascript in the same file =>
<script type="text/javascript">
$(function(){
$("#user_key").autocomplete({
source: function(request,response){
var suggestions = [];
$.ajax({
url: "/ajax/autocomplete.php",
type: "POST",
data: {user_key:$(this).val()},
success: function(result){
$.each(result,function(i,val){
suggestions.push(val.name);
});
},
dataType: "json"
});
response(suggestions);
}
});
});
</script>
and here is php script from autocomplete.php file =>
if (!$connection->connect_errno){
if ($connection->set_charset("utf8")){
if ($r = $connection->query("SELECT name FROM users WHERE name LIKE '" . $_POST['user_key'] . "%'")){
for ($x=0,$numrows = $r->num_rows;$x<$numrows;$x++){
if ($row = $r->fetch_assoc()){
$array[$x] = array("name",$row['name']);
}
}
$r->free();
}
}
}
echo json_encode($array);
PS. It doesn't work. Please help , I've been trying to accomplish this task for the past 2 days,but can't get it to work. Thanks beforehand :)
$array[$x] = array("name",$row['name']);
this is making name and the value from the database both as the elements of the array()
change the code of autocomplete.php to
if (!$connection->connect_errno){
if ($connection->set_charset("utf8")){
if ($r = $connection->query("SELECT name FROM users WHERE name LIKE '" . $_POST['user_key'] . "%'")){
for ($x=0,$numrows = $r->num_rows;$x<$numrows;$x++){
if ($row = $r->fetch_assoc()){
$array[$x] = array("name"=>$row['name']);
}
}
$r->free();
}
}
}
echo json_encode($array);
This will make name as the key for the value fetched from the database
this will help you.
You need to take another look at the autocomplete docs but you will be able to find an answer here: jquery auto-suggestion example doesn't work
Related
So I would like to pass the php array values from this form id to my ajax form. Everything works fine except that it will only display the (1) id number.
Here is my form code: I am passing the $row[topic_id'] as a value to get the id for jquery.
public function forumview($query){
$stmt = $this->db->prepare($query);
$stmt->execute();
$results = $stmt->fetchAll();
if($stmt->rowCount()>0){
foreach($results as $row){
echo '<tr>';
echo '<td style="color: #333;"><span class="pull-right">';
//Problem is here with the $row['topic_id'] portion
if(isset($_SESSION['user_session'])){
echo '<a href="#" class="upVoteArrow"
onclick="upVoteIncrementValue('.$row['topic_id'].');">';
}else{
echo '<a href="#" id="loginForm" class="upVoteArrow" data-
toggle="modal" data-target="#loginModal"><i class="fa fa-arrow-up"></i>
</a>';
}
echo '<span id="voteCount">'.$this->cleanNumber($row['topic_likes']).'</span>';
}
Here is my Ajax call to send the info to my php file
function upVoteIncrementValue(postID){
event.preventDefault();
//var upVoteIncrement = $("#upVoteIncrement").val(); //not needed
$.ajax({
type: "POST",
url: "voting.php",
data: {
"upVoteIncrement": postID,
},
dataType: "json",
cache: false,
success: function(response){
if(response){
var response = $.trim(response);
if(response){
$('#voteCount').html(response);
}
else {
return false;
}
}
}
});
Then here is the php file that handles the call.
if(isset($_POST['upVoteIncrement'])){
$upVoteIncrement = $_POST['upVoteIncrement'];
$stmt = $conn->prepare('UPDATE topics SET topic_likes = topic_likes+1 WHERE topic_id = :id LIMIT 1');
$stmt->bindParam(':id', $upVoteIncrement);
$stmt->execute();
$upVote = $conn->prepare('SELECT topic_likes FROM topics WHERE topic_id = :id LIMIT 1');
$upVote->bindParam(':id', $upVoteIncrement);
$upVote->execute();
$upVoteCount = $upVote->fetchAll();
if($upVote->rowCount() > 0){
foreach($upVoteCount as $row){
$up = $row['topic_likes'];
$results[] = $up;
//exit(); //not needed
}
}
echo json_encode($results);
}
Essentially I am just making a simple up vote system that the user clicks on and it updates the database incrementing by 1. It increments the values and everything works except it will only increment it for the last posted item. So even if I upvote on a topic from earlier it will only add 1 vote to the last inserted topic. Any advice is much appreciated, thanks in advance!
If your using a loop to populate the row id, which it looks like you are here are your problems.
The loop is creating a hidden input element on every iteration of the loop and you are not changing the id of the element. So you will have a bunch of elements all with the same id. That will cause you problems a few different ways.
I changed your PHP code so that each element will have it's own id. I also changed the your javascript function so that the id value is passed to the function itself.
See if this helps:
PHP:
if(isset($_SESSION['user_session'])){
echo '<input type="hidden" id="' . $row['topic_id'] . '" name="upVoteIncrement"
value="' . $row['topic_id'] . '"><a href="#" class="upVoteArrow"
onclick="upVoteIncrementValue(' . $row['topic_id'] . ');">';
}
JS:
function upVoteIncrementValue(postID){
event.preventDefault();
//var upVoteIncrement = $("#upVoteIncrement").val(); //Don't need this anymore.
$.ajax({
type: "POST",
url: "voting.php",
data: {
"upVoteIncrement": postID, //Use the passed value id value in the function.
},
dataType: "html",
cache: false,
success: function(response){
if(response){
var response = $.trim(response);
if(response){
$('#voteCount').html(response);
}
else {
return false;
}
}
}
});
Hope it helps!
I also want to point out that in the code below:
if($upVote->rowCount() > 0){
foreach($upVoteCount as $row){
$up = $row['topic_likes'];
echo $up;
exit();
}
}
You are exiting the script on the first iteration of the loop and you will only ever get one result back.
If you need to return an array of data it should look like this:
if($upVote->rowCount() > 0){
foreach($upVoteCount as $row){
$up = $row['topic_likes'];
$results[] = $up;
//exit();
}
}
echo json_encode($results);
You will then need to set your datatype to json instead of html.
The response in your ajax will now be an array. To see the array:
success: function(response){
if(response){
console.log(response); //Look in your console to see your data.
var response = $.trim(response);
if(response){
$('#voteCount').html(response);
}
else {
return false;
}
}
}
The problem is that in the event handler you addressing element by id, and it's not always the same that you click on.
function upVoteIncrementValue(){
event.preventDefault();
// Always will be last inserted element
var upVoteIncrement = $("#upVoteIncrement").val();
You can use event to get valid element. It's default argument that passed to handler, but remember to define it without braces:
<input onclick="upVoteIncrementValue" />
Then your handler:
function upVoteIncrementValue(event){
event.preventDefault();
var upVoteIncrement = $(event.target).val();
Also if you have several elements with the same ID it's invalid HTML, at least it will hit warning at https://validator.w3.org/ .
So you should set id arg for your element only in case if it's unique, and having this mindset will help you to not hit similar issue again.
I tried to call / search data by ID , from the server using ajax in cordova , but when I click to display the data " undefined" , what's wrong ???
This my html
<input type="text" id="result" value=""/>
<button>get</button>
<div id="result2"></div>
function get (){
var qrcode = document.getElementById ("result").value;
var dataString="qrcode="+qrcode;
$.ajax({
type: "GET",
url: "http://localhost/book/find.php",
crossDomain: true,
cache: false,
data: dataString,
success: function(result){
var result=$.parseJSON(result);
$.each(result, function(i, element){
var id_code=element.id_code;
var qrcode=element.qrcode;
var judul=element.judul;
var hasil2 =
"QR Code: " + qrcode + "<br>" +
"Judul: " + Judul;
document.getElementById("result2").innerHTML = hasil2;
});
}
});
}
This my script on server
include "db.php";
$qrcode= $_GET['qrcode'];
$array = array();
$result=mysql_query("select * from book WHERE qrcode LIKE '%{$qrcode}%'");
while ($row = mysql_fetch_array($result)) { //fetch the result from query into an array
{
$array[] =$row['qrcode'];
$array[] =$row['judul'];
$array[] =$row['jilid'];
}
echo json_encode($array);
}
try to change your parameter in calling ajax
var dataString = {qrcode : qrcode };
Change your php code as below
include "db.php";
$qrcode= $_GET['qrcode'];
$array = array();
$result=mysql_query("select * from book WHERE qrcode LIKE '%{$qrcode}%'");
while ($row = mysql_fetch_array($result)) { //fetch the result from query into an array
{
$array[] =['qrcode'=>$row['qrcode'],'judul'=>$row['judul'],'id_code'=>$row['jilid']];
}
echo json_encode($array);
}
RESOLVED the problem is. I try to replace with this script and the result was the same as I expected.
while ($row = mysql_fetch_object($result)){
$array[]=$row++;
}
echo json_encode($array);
I'm using jquery's ajax function to fetch data from an external php file. The data that is returned from the php file will be used for the autocomplete function. But, instead of the autocomplete function suggesting each particular value from the array in the php file, it returns ALL of them. My jquery looks like this.
jQuery('input[name=past_team]:radio').click(function(){
$('#shadow').fadeIn('slow');
$('#year').fadeIn('slow');
var year = $('#year').val();
$('#year').change(function () {
$('#shadow').val('');
$.ajax({
type: "POST",
url: "links.php",
data: ({
year: year,
type: "past_team"
}),
success: function(data)
{
var data = [data];
$("#shadow").autocomplete({
source: data
});
}
});
});
});
The link.php file looks like this:
<?php
session_start();
require_once("functions.php");
connect();
$type = $_POST['type'];
$year = $_POST['year'];
if($type == "past_team")
{
$funk = mysql_query("SELECT * FROM past_season_team_articles WHERE year = '".$year."'")or die(mysql_error());
$count = mysql_num_rows($funk);
$i = 0;
while($row = mysql_fetch_assoc($funk))
{
$name[$i] = $row['team'];
$i++;
}
$data = "";
for($i=0;$i<$count;$i++)
{
if($i != ($count-1))
{
$data .= '"'.$name[$i].'", ';
} else
{
$data .= '"'.$name[$i].'"';
}
}
echo $data;
}
?>
The autocomplete works. But, it's just that when I begin to enter something in the input field, the suggestion that are loaded is the entire array. I'll get "Chicago Cubs", "Boston Red Sox", "Atlanta Braves", .....
Use i.e. Json to render your output in the php script.
ATM it's not parsed by javascript only concaternated with "," to a single array element. I do not think that's what you want. Also pay attention to the required datastructure of data.
For a working example (on the Client Side see the Remote JSONP example http://jqueryui.com/demos/autocomplete/#remote-jsonp )
below is my $.ajax call to php
$(document).ready(function() {
$('ul.sub_menu a').click(function(e) {
e.preventDefault();
var txt = $(this).attr('href');
$.ajax({
type: "POST",
url: "thegamer.php",
data:{send_txt: txt},
success: function(data){
$('#container').fadeOut('8000', function (){
$('#container').html(data);
$('#container').fadeIn('8000');
});
}
});
});
});
my php code
if(mysql_num_rows($result) > 0){
//Fetch rows
while($row = mysql_fetch_array($result)){
echo $row['img'];
}
}
I m getting this output
images/man/caps/army-black.pngimages/man/caps/army-brown.pngimages/man/caps/army-grey.pngimages/man/caps/army-lthr.pngimages
these are basically image paths now how to loop over them in jquery and fit each image in image tag
any code will be useful
Plz Note I DONT NEED JSON
regards sajid
JSON is probably your best bet here. In PHP do something like this:
$ret = array();
while( $row = mysql_fetch_assoc( $result ) )
{
$ret[] = $row['img'];
}
echo json_encode( $ret );
This will output something like the following
["image1","image2","image3"]
jQuery has a function which can convert this information into a javascript array. So put this code in your success callback.
var result = jQuery.parseJSON( data );
alert( result[1] );
EDIT: A method which does not use JSON
In PHP place each image url on a separate line
echo $row['img'], "\n";
Then in javascript, split the response by the new line character
var result = data.split( "\n" );
simply change your php code:
`if(mysql_num_rows($result) > 0){
while($row = mysql_fetch_array($result)){
echo ""<img src='".$row['img']."' /><br />";
} }
Need a way to make element show in the div,but when i use ajax send data to list.php.it can not work?
PHP:
<?php
mysql_connect('localhost','user','password');
mysql_select_db('fruit');
$days = 3;
for($i=1;$i<=$days;$i++)
{
?>
<ul id="sortable">
<?php
$sql = "select * from menu where columnNo = '$i' order by orderNo ASC";
$result= mysql_query($sql);
//$row=mysql_fetch_assoc($result);
//print_r($row);
while($row=mysql_fetch_assoc($result))
{
echo '<li id="list_' . $row['id'] . '">' . $row['title'] . "</li>\n";//
}
?>
</ul>
<?php
}
?>
jquery:
$(function(){
$("ul").sortable({
connectWith:"ul",
update:function()
{
serial = $("ul").sortable("serialize");
$.ajax({
data: serial,
url:"list.php",
type:"post",
error:function(){
alert("Error!");
},
success:function(data){
$("#serverResponse").html(data);
}
});
//alert(serial);
}
});
$("#sortable").disableSelection();
});
list.php
<?php
mysql_connect('localhost','root','xingxing');
mysql_select_db('fruit');
$list = $_POST['id'];
for($i=0;$i<count($menu);$i++)
{
$sql = "update menu set orderNo= '$i' where id = '$menu[$i]'";
mysql_query($sql);
}
?>
but,the list.php did't work. i don't know why.could anyone can help me ? THX!
Not sure if this will help, but your trying to update on every single reorder event (is this really necessary?).
It might be wise to use a javascript timeout to update after a couple seconds idle time after an update. I personally use this method and it makes things run a lot smoother.
In your jQuery .sortable() setup add the following:
start: function(event, ui){
clearTimeout(allow_update);
},
update: function(event, ui){
allow_update = window.setTimeout(UpdateOrdering, 3000);
}
And then add var allow_update = null; somewhere and an UpdateOrdering function which is called when the timeout expires (in my case 3000 ms), with your update functionality in there.
Hope this helps :)