I appplied autoComplete function to search box but when i key in some value in the search box, it always gv me the same result.
I realized i did not loop through the database, that's why i keep getting the same result.
I changed my query so that i can get what i want but the result still the same.
here is my ajax for autocomplete, and i'm not sure is it the right way to do it? But the search function is working except it do not display all the data.
function autoComplete(){
$('#keywords').autocomplete({
source: 'autoComplete.php',
minLength : 3,
select: function(event, ui) {
console.log(ui);
$('#chosenEvent').append(ui.item.value + "\n");
}
});
Here is the php code
<?php
// include the file for the database connection
include_once("database_conn_getOffers.php");
function autoC($conn){
$sql = "select eventTitle from te_events_special_offers eventTitle ORDER BY eventTitle";
$rsOffer = mysqli_query($conn, $sql);
//$offer = mysqli_fetch_all($rsOffer, MYSQLI_ASSOC);
$titles = array();
while($title = mysqli_fetch_assoc($rsOffer)){
$titles[] = $title;
}
foreach ($titles as $title)
return json_encode($title);
}
echo autoC($conn)
?>
Here is the link that i refer to click here
Thanks for your help!
So now, i changed the ajax method with the following code and it works but i still have no idea what wrong with my previous ajax code.
I also modified the php code by remove the foreach and added implode method
$.ajax({
method :"get",
url :"autoComplete.php"
})
.done(function(data, status, jqxhr){
var eventList;
console.log(data);
eventList = data.split(',');
$("#keywords").autocomplete({
minLength :2 ,
source : eventList,
select: function(event,ui){
console.log(ui);
}
//end autocompoete
});
});
Please try first to have results to encode, then we'll used them. Run this code along no other one at the same time, and tell us what you get (I assumed that you have columns ID + TITLE, if not, correct the code before using). Also, you original query seems weird -> $sql = "SELECT eventTitle FROM te_events_special_offers eventTitle ORDER BY eventTitle"; /* check bold part of it */
Plus : you should really think about prepared statements and error_reporting
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include"config.inc.php";
$mysqli = mysqli_connect("$host", "$user", "$mdp", "$db");
if (mysqli_connect_errno()) { echo "Error connecting : " . mysqli_connect_error($mysqli); }
$query = " SELECT idTitle, eventTitle FROM te_events_special_offers ORDER BY eventTitle "; /* check names used here and adapt to yours */
$stmt = $mysqli->prepare($query);
$results = $stmt->execute();
$stmt->bind_result($idTitle, $eventTitle);
$stmt->store_result();
if ($stmt->num_rows > 0) {
$events = array();
$event = array();
while($stmt->fetch()){
echo"[ $idTitle -> $eventTitle ]<br />";
$event["id"] = "$idTitle";
$event["title"] = "$eventTitle";
array_push($events, $event);
}
}
else
{ echo"[ no data ]"; }
print_r($events);
echo json_encode($events);
?>
Related
I am working on a web application where it allows you to post a simple comment to the database on a form submit, what I want to do is generate a new list of all comments written and use AJAX to replace a div where comments are to be stored, this to show the newest written comment after submitting it.
$(document).ready(function() {
$('#postCommentForm').submit(function (e)
{
e.preventDefault();
console.log("JS Submitted");
function addCommentAJAX_call(commentTitleBox,commentBox,source_name,place_id,city_id)
{
$.ajax(
{
url : "funcsAJAX.php",
type : "post",
dataType : "json",
data : {
'commentTitleBox' : commentTitleBox,
'commentBox' : commentBox ,
'source_name' : source_name ,
'place_id' : place_id ,
'city_id' : city_id
},
success : function(response)
{
console.log(response);
$('#g').html(response);
},
});
}
var commentTitleBox = $('#commentTitleBox').val();
var commentBox = $('#commentBox').val();
var source_name = $('#source_name').val();
var place_id = $('#place_id').val();
var city_id = $('#city_id').val();
addCommentAJAX_call(commentTitleBox,commentBox,source_name,place_id,city_id);
});
});
This is the jQuery code I use to pull data from the form and post it to the webserver, note that the success part is unfinished as it never fired for me, #g is the div which contents I want to replace.
Next is the handler for the AJAX call
extract($_POST);
#addCommentAJAX_call handler
$user = 'user';
$pass = 'pass';
try
{
$db = new PDO('mysql:host=localhost;dbname=twincities;charset=utf8',$user,$pass);
}
catch(PDOException $e)
{
die("<h3>connection to be failed, not surprising really heres why ".$e->getMessage());
}
addComment($db,$city_id,$place_id,$commentTitleBox,$commentBox,$source_name);
$allComments = showCommentsForAJAX($db,$city_id,$place_id);
$db->connection = null;
echo json_encode($allComments);
This will create PDO object and then addComment() will add the comment to the database, it works fine with no issues.
showCommentsForAJAX() is the function I want to use that returns the comments from the database
function showCommentsForAJAX($db,$cityID,$placeID)
{
try
{
if($cityID && $placeID)
{
$query = "select * from comment where place_place_id = :place_place_id and city_city_woeid = :city_city_woeid";
$queryVars = ['place_place_id' => $placeID,'city_city_woeid' => $cityID];
}
else if($cityID)
{
$query = "select * from comment where city_city_woeid = :city_city_woeid";
$queryVars = ['city_city_woeid' => $cityID];
}
$query = $query." ORDER BY `timestamp` desc";
$stmt = $db->prepare($query);
$stmt->execute($queryVars);
$returnHTML = "";
$returnHTML = $returnHTML . '<div id=comments>';
while($comment = $stmt->fetch())
{
$returnHTML = $returnHTML . '<div id=commentIDis'.$comment['comment_id'].'>
<h3>'.$comment['title'].'</h3>
<br>
<p>'.$comment['content'].'</p>
<br>
<p>-'.$comment['source_name'].'</p>
<br>
';
$returnHTML = $returnHTML . '</div>';
}
$returnHTML = $returnHTML . '</div>';
return $returnHTML;
}
catch(PDOException $e)
{
die("<h3> ROLLBACK something broke, not surprising really heres why ".$e->getMessage());
}
}
I want to based off the entries in the database, to build the comments' HTML and return that to AJAX, I am not sure how to encode the result for AJAX to understand it, and I believe that the logic for $returnHTML is incorrect and there is a better method of doing what I want but I am not sure how to achieve that, I have done a similar thing using Flask before where I used jinja templating to generate the HTML and successfully replace the contents of a div, but due to this university project I need to use PHP.
Suggestions to code layout are also very appreciated
I'm making search in BD MySQL, but I can't get result I need. This is php code
$mass = json_decode(file_get_contents('php://input'), true);
foreach ($mass as $mass_item) {
if($mass_item['name']=="Наименование" && isset($mass_item['val']))
$exp=$mass_item['val'];
}
$query = "SELECT * FROM Companies WHERE LOWER(name) RLIKE
LOWER('".$exp."') ";
$result = mysql_query($query) or die();
while($row=mysql_fetch_array($result)){
echo json_encode($row);
}
This is an angular code
`
$http.post("search.php", value).then(function success (response) {
console.log(response);
console.log(response.data);
},function error (response){
console.log(response.data);
}
);`
As a result in console I see empty row "". But if I add one more echo before or in while, like echo $row['name'] in console will be all
expected result. I need to get query in json format to work with it. Please help.
you are trying to echo every row, change php code to something like that:
$resultJson = [];
while($row=mysql_fetch_array($result)){
$resultJson[] = $row;
}
echo json_encode($resultJson);
die;
I want to check if a user has favourited an item but I'm unsure how to return the result of a database query to ajax.
I will show different html depending on the result.
Php
$query = "SELECT itemID from favourites WHERE userid = '" . $user. "'";
$result = mysql_query($query);
echo json_encode($result);
Jquery
$.ajax({
url: "inc/functions.php",
type: "POST",
data: {--result--},
success: function () {
// if result found in database
$('favourite').hide();
// if result not found
$('favourite').show();
}
});
I can't figure out how to display $result in the jquery code.
Any help much appreciated.
$result in this case is a PHP object representing a result.
You will have to use a fetch() method in order to extract the result before sending it back to your JS.
See this link. There's a list of all fetch-family method right above the comments.
Also, you will need to make a connection with you database beforehand using mysqli_connect (or mysql_connect in your case).
As stated in the comments, you should however use mysqli* functions family instead of mysql*.
Thanks to the comments for info regarding mysqli. I updated the code and solved the ajax part.
For anyone else stuck, I got it working like this:
PHP
require ("../../connection.php");
$sql = "SELECT * FROM favourites WHERE userID = ? AND itemID = ?";
$user = $_POST['userID'];
$item = $_POST['itemID'];
$statement = $db->prepare($sql);
if($statement === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $db->error, E_USER_ERROR);
}
$statement->bind_param('ii',$user,$item);
$statement->execute();
$statement->bind_result($user,$item);
while($statement->fetch()){
echo 1;
}
$statement->close();
Jquery
$.ajax({
url: "inc/userList.php",
data: userList,
type: "POST",
success: function (result) {
if (result == 1){
$('#addItem').css('display', 'none');
$('#removeItem').css('display', 'inline-block');
} else {
$('#addItem').css('display', 'inline-block');
$('#removeItem').css('display', 'none');
}
}
});
I have a code to make a query over my db, and get back the response and put them in fields over my html. I want to send the response via JSON, then create the fields using that information. But when I echo my json_encode($json_output) I only get a [true].
If anyone can explain me why I'll be appreciated.
Javascritp code:
$($cadView).find('#cadForm').on('submit', function(e){
e.preventDefault();
var str = $('#srBar').val();
if(str == ""){
alert("Campo de busca vazio.");
}else{
$.post($('#cadForm').attr('action'), {q : str}, function(data){
alert(data);
});
}
PHP code:
<?php
$q = $_POST['q'];
require('connect.php');
$i = 0;
$sql="SELECT `_nome`, `_endereco`, `_telefone`, `_imgstring`, `_dtAcesso`, `_descricao`, `_fkIdUser` FROM `tbvisitante` WHERE _nome = ?";
$stmt= $conn->prepare($sql);
$stmt->bind_param('s', $q);
if ($stmt){
$stmt->execute();
$stmt->bind_result($rName, $rEndereco, $rTelefone, $rImgString, $rDtAcesso, $rDescricao, $rFkIdUser);
while ($row = $stmt->fetch()){
$json_output[] = $row;
echo json_encode($json_output);
}
}
mysqli_close($conn);
?>
http://php.net/manual/en/mysqli-stmt.fetch.php
mysqli_stmt::fetch returns null or a boolean. You are binding the result to variables, those are what you're supposed to use.
Otherwise you may look into get_result instead of fetch.
I have a dropdown list that is populated from a mySQL database using PHP. How do I preselect the first option in the dropdown bearing in mind that these values may not always be the same?
This is the code in my HTML:
function loadparameters(selobj, url, nameattr) {
$(selobj).empty();
$.getJSON(url, {}, function (data) {
$.each(data, function (i, obj) {
$(selobj).append($("</option><option>
</option>").val(obj[nameattr]).html(obj[nameattr]));
});
});
}
$(function () {
loadparameters($('select#parameterType').get(0),
'GetParameter.php?GetParameter=parameterType', 'parameterType');});
..and the PHP Script:
<?php
if(!empty($_GET['GetParameter']))
{
$list = $_GET['GetParameter'];
$qry='';
switch($list)
{
case 'parameterType':
{
$qry = "SELECT parameterType FROM Parameters";
break;
}
}
if(empty($qry)){ echo "invalid params! "; exit; }
$dbconn = mysql_connect('*******','*******','******')
or die("DB login failed!");
mysql_select_db('*****', $dbconn)
or die("Database does not exist! ".mysql_error($dbconn));
$result = mysql_query($qry,$dbconn)
or die("Query $qry failed! ".mysql_error($dbconn));
$rows = array();
while($rec = mysql_fetch_assoc($result))
{
$rows[] = $rec;
}
mysql_free_result($result);
mysql_close($dbconn);
echo json_encode($rows);
}
?>
The only thing that seems wrong in your code is this line
$(selobj).append($("</option><option></option>").val(obj[nameattr]).html(obj[nameattr]));
Why do you close close/open/close the option tag?
Shouldn't it be that way? (I've indented the code for readability)
$(selobj).append(
$("<option></option>") // only open/close tag
.html(obj[nameattr]) // this injects HTML
);
OR
$(selobj).append(
$("<option></option>") // only open/close tag
.text(obj[nameattr]) // this only injects text
);
If you fix this, then the first option should be preselected. The reason why it isn't preselected is because your browser might automatically fix this issue by itself with an empty option.
Also, I find the syntax below more readable:
var option = $("<option></option>").text(obj['nameattr']);
$(selobj).append(option);