consult with typeahead.js database - javascript

Would like to query the database with typeahead.js v.0.10.2 .
I tried ,but I failed, I've bundled with the plugin.
JS:
$(document).ready(function() {
$('input.typeahead').typeahead({
name: 'user-search',
remote: 'data.php' // you can change anything but %QUERY
minLength: 1, // send AJAX request only after user type in at least 3 characters
limit: 10 // limit to show only 10 results
});
});
PHP:
$dato = $_POST['query'];
require("connect.inc.php");//database
$query = mysql_query("SELECT artist FROM music WHERE artist REGEXP '^$dato'");
$array = array();
while($fila = mysql_fetch_array($query)) {
$array = $fila['artist'];
}
return json_encode($array);

instead of return json_encode($array); use echo return json_encode($array);

Related

i have code like this for auto complete feature but am not able fetch the data from the data base.kindly help me out

My aim is to fetch location from the database once user start entering in the input tetc field
i have done all the coding properly but the also am not able to fetch the data from the database.
<!--My java script code-->
$(function() {
$( "#LocationName" ).autocomplete({
source: 'search.php'
});
});
<!--My Search.php code-->
<?php
include('dbConnect.php');
$searchTerm = $_GET['term'];
$sql = mysql_query ("SELECT LocationName,From arealistmain WHERE LocationName LIKE ?");
$array = array();
while ($row = mysql_fetch_array($sql)) {
$array[] = array (
'value' => $row['LocationName'].'',
);
}
//RETURN JSON ARRAY
echo json_encode ($array);
?>
First of all don't use mysql_* functions as they were deprecated in PHP 5.5 and removed in PHP 7 instead use mysqli_* functions.
Second thing you should always sanitize user input don't just do $searchTerm = $_GET['term']; read more about this
Then your SQL query should read
$query = "SELECT LocationName From arealistmain WHERE LocationName LIKE '%$searchTerm%';";
The comma before FROM removed and the $searchTerm is enclosed in two percentage signs to match all
Update your query to below code
$sql = mysql_query ("SELECT LocationName From arealistmain WHERE LocationName LIKE '%".$searchTerm."%'");
$array = array();
while ($row = mysql_fetch_array($sql)) {
$array[] = $row['LocationName'];
}

d3.js How to pass parameter to php for query condition

I attempt to combine d3, mysql php Tutorial.
I want to use mysql to store data, and use d3 table to display the result.
Following the tutorial I successfully connected the sql, and display it.
However, in my example, the where condition of sql in queryData.php is hard encoded.
As show below: WHERE pathwayID='1643685' && symbol='VIF'
I need to pass the parameter '1643685' and 'VIF' from d3 file to php file, how should I do?
And how should I modify queryData.php, thanks.
d3 file
d3.json("queryData.php", function(error, jsonData) {
....
});
queryData.php
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
// load in mysql server configuration (connection string, user/pw, etc)
include 'mysqlConfig.php';
// connect to the database
#mysql_select_db($database) or die( "Unable to select database");
//Query
$myquery = "
SELECT `pathwayID`, `proteinID`, `uniprotID`, `symbol`, `displaySymbol`, `reactomeID`, `cellularLocation` FROM `protein` WHERE pathwayID='1643685' && symbol='VIF'
";
$result = mysql_query($myquery);
if ( ! $result ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($result); $x++) {
$data[] = mysql_fetch_assoc($result);
}
echo json_encode($data);
mysql_close();
?>
mysqlConfig.php
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
$username="root"; //replace with your mySql username
$password=""; //replace with your mySql password
$database="pathway"; //replace with your mySql database name
$host="localhost"; //replace with the name of the machine your mySql runs on
$connection=mysql_connect($host,$username,$password);
?>
Finally, I solved this by using ajax to post parameter.
$.ajax({
url: "./php/querybyPathwayId.php",
type: "GET",
data: {
pathwaydbId: dbId
},
dataType: "json",
success: function (jsonData) {
operation(jsonData);
},
error: function () {
}
});
and modified the querycentance
$pathwayId = $_GET["pathwaydbId"];
$myquery = "
SELECT `pathwayID`, `proteinID`, `uniprotID`, `symbol`, `displaySymbol`,
`reactomeID`, `cellularLocation` FROM `protein` WHERE pathwayID='$pathwayId'
";

Using ajax to display new database inputs without refreshing the page

I am using ajax to post comments to a certain page, I have everything working, except for when the user posts a comment I would like it to show immediately without refreshing. The php code I have to display the comments is:
<?php
require('connect.php');
$query = "select * \n"
. " from comments inner join blogposts on comments.comment_post_id = blogposts.id WHERE blogposts.id = '$s_post_id' ORDER BY comments.id DESC";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$c_comment_by = $row['comment_by'];
$c_comment_content = $row['comment_content'];
?>
<div class="comment_box">
<p><?php echo $c_comment_by;?></p>
<p><?php echo $c_comment_content;?></p>
</div>
<?php } ?>
</div>
</div>
<?php
}
}
and the code I have to post comments is:
<?php
$post_comment = $_POST['p_post_comment'];
$post_id = $_POST['p_post_id'];
$post_comment_by = "Undefined";
if ($post_comment){
if(require('connect.php')){
mysql_query("INSERT INTO comments VALUES (
'',
'$post_id',
'$post_comment_by',
'$post_comment'
)");
echo " <script>$('#post_form')[0].reset();</script>";
echo "success!";
mysql_close();
}else echo "Could no connect to the database!";
}
else echo "You cannot post empty comments!"
?>
JS:
function post(){
var post_comment = $('#comment').val();
$.post('comment_parser.php', {p_post_comment:post_comment,p_post_id:<?php echo $post_id;?>},
function(data)
{
$('#result').html(data);
});
}
This is what I have for the refresh so far:
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('.comment_box').load('blogpost.php');
}, 3000);.
});
Now what I want to do is to use ajax to refresh the comments every time a new one is added. Without refreshing the whole page, ofcourse. What am I doing wrong?
You'll need to restructure to an endpoint structure. You'll have a file called "get_comments.php" that returns the newest comments in JSON, then call some JS like this:
function load_comments(){
$.ajax({
url: "API/get_comments.php",
data: {post_id: post_id, page: 0, limit: 0}, // If you want to do pagination eventually.
dataType: 'json',
success: function(response){
$('#all_comments').html(''); // Clears all HTML
// Insert each comment
response.forEach(function(comment){
var new_comment = "<div class="comment_box"><p>"+comment.comment_by+"</p><p>"+comment.comment_content+"</p></div>";
$('#all_comments').append(new_comment);
}
})
};
}
Make sure post_id is declared globally somewhere i.e.
<head>
<script>
var post_id = "<?= $s_post_id ; ?>";
</script>
</head>
Your new PHP file would look like this:
require('connect.php');
$query = "select * from comments inner join blogposts on comments.comment_post_id = blogposts.id WHERE blogposts.id = '".$_REQUEST['post_id']."' ORDER BY comments.id DESC";
$result = mysql_query($query);
$all_comments = array() ;
while ($row = mysql_fetch_array($result))
$all_comments[] = array("comment_by" => $result[comment_by], "comment_content" => $result[comment_content]);
echo json_encode($all_comments);
Of course you'd want to follow good practices everywhere, probably using a template for both server & client side HTML creation, never write MySQL queries like you've written (or that I wrote for you). Use MySQLi, or PDO! Think about what would happen if $s_post_id was somehow equal to 5' OR '1'='1 This would just return every comment.. but what if this was done in a DELETE_COMMENT function, and someone wiped your comment table out completely?

jquery ui autocomplete special characters

I created a small jquery example with jquery UI autocomplete
$(function() {
//autocomplete
$(".selector").autocomplete({
source: "getdata.php",
minLength: 1
});
})
getdata.php:
<?php
if (isset($_GET['term'])){
$return_arr = array();
try {
$connectionInfo = array('Database'=>'db','UID'=>'sa','PWD'=>'pw');
$connection = sqlsrv_connect('db-server',$connectionInfo);
if($connection)
{
$result = sqlsrv_query( $connection, 'SELECT TOP 10 test FROM table WHERE test like ? ',array('%'.$_GET['term'].'%'));
while($row = sqlsrv_fetch_array($result)){
$row = array_map('utf8_encode', $row);
$return_arr[] = $row['test'];
}
}
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
}
?>
and it works but the problem is that the data source is not Unicode so the strings don't show up correctly I don't know what kind of transformation to use.
If possible I would like to keep the same encoding as in database (Windows-1250) as this project might also insert stuff back from the website to the db
I tried just to dump the original strings but then I get values with special characters as null in json when the return array get's transformed
You can encoder your data before display it in autocomplete

JSON Encode Failure

PHP PAGE:
<?php
include "linkpassword.inc";
function showVotes()
{
$showresult = mysql_query("SELECT * from mms") or die("Invalid query: " . mysql_error());
$row = mysql_fetch_assoc($showresult);
}
function addVote()
{
$sql= "UPDATE mms SET votes = votes+1 WHERE color = '".$_POST['color']."'";
$result= mysql_query($sql) or die(mysql_error());
return $result;
}
addVote();
showVotes();
?>
I am trying to get the output of the array to load into a JavaScript page where I can break up the array into seperate divs that have IDs assigned to them. Here is what I tried
<script>
$(document).ready(function () {
$('.answer').click(function (e) {
var color = $(this).attr("data-color");
$.ajax({
type: 'POST',
url: 'mm.php',
data: { color: color},
dataType: 'json',
cache: false,
success: function(showVotes) {
$('#rvotes').html(showVotes[0]);
},
error: function (jqXHR) {
}
})
})
});
</script>
Where am I going wrong??
From what you've posted in comments, what you have is an array of objects.. not html, as your function seems to indicate. Depending on what you want done, the answer would be either of the following, to access that object's properties:
showVotes[0].votes
Or
showVotes[0]['votes']
Eg:
$('#rvotes').html(showVotes[0].votes);
Or etc.
Second attempt:
Firstly, change your current 'showVotes' function to this:
function showVotes()
{
$showresult = mysql_query("SELECT * from mms") or die("Invalid query: " . mysql_error());
while ($row = mysql_fetch_assoc($showresult)) {
$response[] = $row;
}
return json_encode($response);
}
Secondly, remove your 'connected successfully' text from the page, as well as any other text generated by anything else(aka, the other function which returns a result pointer). I may be wrong, but it would seem to me that the generation of this other text is causing the returned json to be interpreted as malformed.
Quick explanation on PDO:
try {
$dbh = new PDO("mysql:host=localhost;dbname=dbname", "user", "password");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (\PDOException $e) {
echo "Error! Could not connect to database: " . $e->getMessage() . "<br/>";
die();
}
Connecting to the database.. This is how I've learned to do it, though I've been warned(and downvoted) to not check for errors this way, though it was never explained why.
Database interaction:
$stmt = $dbh->prepare("UPDATE mms SET votes = votes+1 WHERE color = :color");
$stmt->bindParam(":color",$_POST['color']);
$stmt->execute();
Result use:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$response[] = $row;
}
And so on and so forth. PDO escapes the values for you, so you don't have to worry about injection attacks.

Categories