I have javascript as follows :
<script type="text/javascript">
function lookup(inputString) {
if(inputString.length == 0) {
$('#suggestions').hide();
} else {
$.post("./index.php?menu=getmyFavList&ajax=ajax"
, {queryString: ""+inputString+""}
, function(data){
if(data.length >0) {
$('#suggestions').show();
$('#autoSuggestionsList').html(data);
}
});
}
}
function fill(thisValue) {
$('#inputString').val(thisValue);
setTimeout("$('#suggestions').hide();", 200);
}
</script>
And my corresponding php code is
$sql = "SELECT
u.UM_index
, u.UM_first_name
, u.UM_last_name
, p.bz_pro_city
, p.bz_pro_country
FROM
tbl_user_master As u
, tbl_profile AS p
WHERE
u.UM_index = p.bz_pro_id
AND
UM_first_name LIKE '%" . $q . "%'
AND
UM_is_active = 'yes'
";
$res = mysql_query($sql) or die("unable to execute query");
while($row = mysql_fetch_array($res))
{
echo '<li onClick="fill(\''.$row['UM_first_name']
. ' ' . $row['UM_last_name'] . '\');">'
. $row['UM_first_name']
. ' ' . $row['UM_last_name']
. ',' . $row['bz_pro_city']
. '</li>';
}
And the HTML for is like :
<input type="text" name="reciever_name" size="37" id="inputString" onkeyup="lookup(this.value)" onblur="fill()" />
Now my problem is I need to pass the index of the selected user which is in tbl_user_master. How can I do this (of course hiding the index from the sender)?
Why not put the index in an <input type="hidden"> and add it to your querystring?
Edit
What you need to do is change what happens when a user selects an item.
In your while you'll need to change the echo to
echo "
<li onclick=\"fill('{$row['UM_first_name']} {$row['UM_last_name']}'
, '{$row['UM_index']}')\">
{$row['UM_first_name']} {$row['UM_last_name']}, {$row['bz_pro_city']}
</li>"
And change your JavaScript fill function to
function fill(thisvalue, thisid){
$('#inputString').val(thisValue);
$('#selectedID').val(thisid);
setTimeout("$('#suggestions').hide();", 200);
}
You'll also need to add
<input type="hidden" name="thisid" id="thisid" value=""/>
When the form is submitted, you would access the ID of the selected item using $_POST['thisid']
Related
I'm doing an input with autocomplete where my user can select multiple users from database and I want to submit those select users in my form where action goes to a php file that does a INSERT in the database.
So this is the input, I want the selected users to show up in p#selecionados but user selects one at a time:
<form id="formCriaJogo" method="post" action="./components/insert.php">
<label>Other users</label>
<input type="text" name="autor" id="autor" placeholder="Write users name" />
<div id="autorLista"></div>
<p id="selecionados"></p>
<button type="submit">Insert</button>
</form>
And this is jquery code to do the autocomplete:
$(document).ready(function() {
$('#autor').keyup(function() {
var query = $(this).val();;
if (query != '') {
$.ajax({
url: "./components/search.php",
method: "POST",
data: {
query: query
},
success: function(data) {
$("input#autor").css("margin-bottom", '0');
$("#autorLista").css("display", 'block');
$('#autorLista').fadeIn();
$('#autorLista').html(data);
},
error: function(error) {
console.log(error);
}
});
}
});
$('input#autor').on('change', function() {
alert($('input[name=autor]:checked', '#formCriaJogo').val());
});
});
Also, here is search.php that does the search:
<?php
include_once "../connection/connection.php";
if (isset($_POST['query'])) {
$link = new_db_connection();
$stmt = mysqli_stmt_init($link);
$output = '';
$input = $_POST['query'];
$query = "SELECT id_user, nome_user FROM users WHERE nome_user LIKE CONCAT(?, '%')";
mysqli_stmt_prepare($stmt, $query);
mysqli_stmt_bind_param($stmt, 's', $input);
mysqli_execute($stmt);
mysqli_stmt_bind_result($stmt, $id_user, $name_user);
mysqli_stmt_store_result($stmt);
if (mysqli_stmt_num_rows($stmt) > 0) {
while (mysqli_stmt_fetch($stmt)) {
$output .= "<input type='radio' value='" . $id_user . "' name='autor'>" . $name_user . "<br>";
}
} else {
$output .= '<p>The user your looking for doesn't exist.</p>';
}
echo $output;
}
Now the clicked input type=radio value which contains users' id and name I want the user name in p#selecionados just to show them what he selected and also send id and name of user selected when submitting my form.
You can create an array in jquery so , whenever you select an option from autocomplete box.. put that value inside that array in jquery .I have use checkbox instead of radio-button in below code and whenever user select any option that data will get inserted in array i.e:index and when insert button is clicked the selected data will get display in p#selecionados tag and also an ajax will call to send your selected data to php page.Also i have added value='" . $id_user."," . $name_user . "' you can split this using .split() with delimiter , to get both userid and username.Sample code :
var index = [];
//when check-box is changed
$('input[name=autor]').change(function() {
//checking if checkbox is check put it in array
if ($(this).is(':checked')) {
index.push($(this).val());
console.log(index)
} else {
//if uncheck remove the element from array
if ((index1 = index.indexOf($(this).val()) !== -1)) {
index.splice($.inArray(index1, index), 1);
console.log("remove");
}
}
});
//when insert button is click
$("button").click(function() {
//clear the p tag content
$("p#selecionados").html("");
for (var i = 0; i < index.length; i++) {
//append all selected check box
$("p#selecionados").append(index[i] + "<br />");
console.log("userid & username" + index[i]);
}
if (index != '') {
$.ajax({
url: "yourphp_page_name",
method: "POST",
data: {
//sending array to php
data: index
},
success: function(data) {
//do something
},
error: function(error) {
//do something
}
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<input type='checkbox' value='" . $id_user."," . $name_user . "' name='autor'>" . $name_user . <br/>
<input type='checkbox' value='" . $id_user."," . $name_user . "' name='autor'>" . $name_user . <br/>
<button type="submit">Insert</button> <br/><br/> Selected data :
<p id="selecionados"></p>
Then in your php side ,you need to get that array i.e : data using $_POST['data'] and then explode your array and use it as per your requirement.
this code displays the name as i type, as i type it gives suggestion of names and when clicked on it it displays the result in the textbox.but i want to display the id related to that name from database when i clicked on that name from the dropdown option. please help
<input type="text" name="st_id" id="st_id" ><div id="txtHint" style="position: absolute; width:390px ;"></div>
ajax code:
$(document).ready(function () {
$("#st_id").keyup(function () {
var search = $(this).val();
if (search != '') {
$.ajax({
type: "POST",
url: "ajaxcode.php",
data: {search: search},
success: function (data) {
$("#txtHint").fadeIn();
$("#txtHint").html(data);
}
});
}
});
});
php code
<?php
if (isset($_POST["search"])) {
$display = '';
$q = $_POST["search"];
$stmt = $DBconnect->prepare("SELECT * FROM table1 WHERE First_name LIKE :sh ");
$stmt->bindValue(':sh', '' . $q . '%', PDO::PARAM_STR);
$stmt->execute();
$display = '<ul class="list-unstyled">';
foreach ($stmt as $row) {
if ($row) {
$display .= '<li>' . $row["First_name"] . ' ' . $row["Middle_name"] . ' ' . $row["Last_name"] . '</li>';
} else {
$display .= '<li>name not found</li>';
}
}
$display .= '</ul>';
echo $display;
}
?>
Most naive way I can come up with is adding an id to the top ul
<ul id="name_suggestion" class="list-unstyled">
and the id to the <li> tag with a data- attr
$display .= '<li data-user-id = '. $row["id"] . '>'.$row["First_name"].' '.$row["Middle_name"].' '.$row["Last_name"].'</li>';
Then add an a click listener to the li:
$('#name_suggestion li').on('click', function(e){
let val = $(this).attr('data-user-id');
$('#st_id').val(val);
});
I am creating a basic auction site and got quite far with help from this community. I am near finishing this now but having a slight issue with server side validation.
Auctions are listed on a PHP page with html and PHP, PHP runs a MySQL query and then lists the results. Example here:
$result = mysqli_query($con,"SELECT * From auction WHERE category = 'Bathroom' ORDER BY ID DESC");
while($row = mysqli_fetch_array($result))
{
echo "<form name='auction' id='auction" . $row['ID'] . "'>
<input type='hidden' name='id' value='" . $row['ID'] . "' />
<div class='auction-thumb'>
<div class='auction-name'>" . $row['Item'] . "</div>";
echo "<img class='auction' src='" . $row['ImagePath'] . "' />";
echo "<div class='auction-bid'>Current Bid: £<div class='nospace' id='" . $row['ID'] . "'>" . $row['CurrentBid'] . "</div></div>";
echo "<div class='auction-bid'>Your Name: <input type='text' class='bidder' name='bidname' autocomplete='off'/></div>";
echo "<div class='auction-bid'>Your Bid: <input type='text' class='auction-text' name='bid' autocomplete='off'/></div>";
echo "<div class='auction-bid'><input type='submit' name='submit' value='Place Bid!' /></div>";
echo "<div class='bid-success' id='bid" . $row['ID'] . "'>Bid placed!</div>";
echo "</div></form>";
}
echo "</table>";
mysqli_close($con);
Once the user clicks the submit button, the following jQuery is executed:
$(document).ready(function(){
$('form[name="auction"]').submit(function(){
var id = $(this).find('input[name="id"]').val();
var bidname = $(this).find('input[name="bidname"]').val();
var bid = $(this).find('input[name="bid"]').val();
var currentbid = $('#'+id).text();
var itemdesc = $(this).find('.auction-name').text();
bid = parseFloat(parseFloat(bid).toFixed(2));
currentbid = parseFloat(parseFloat(currentbid).toFixed(2));
if (bidname == '')
{
alert("No name!")
return false;
}
/* if (bid > currentbid)
{
alert("Bid is greater than current bid");
}
else
{
alert("Bid is too low!");
return false;
}*/
$.ajax({
type: "POST",
url: "auction-handler.php",
dataType: "json",
data: {bidname: bidname, bid: bid, id: id, itemdesc: itemdesc},
success: function(data){
$('#bid'+id).fadeIn('slow', function () {
$(this).delay(1500).fadeOut('slow');
});
//$('#auction' + id).find('.nospace').html(currentbid);
},
error: function() {
alert("bid too low");
}
});
return false;
});
});
If the code POSTS, the following PHP code is run on the handler page:
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$bidname = $_POST['bidname'];
$bid = $_POST['bid'];
$id = $_POST['id'];
$itemdesc = $_POST['itemdesc'];
$highestbid = mysqli_fetch_row(mysqli_query($con,"SELECT CurrentBid from Auction WHERE ID = '$id'"));
if ($bid <= $highestbid)
{
$_SESSION['errors']['bid'] = 'Sorry, but the bid is too low';
echo json_encode($_SESSION['errors']);
exit;
}
else
{
$query = "UPDATE auction SET CurrentBid = '$bid', Bidder = '$bidname' WHERE ID = '$id'";
$query2 = "INSERT INTO auction_log (Item, Bid, Bidder) VALUES ('$itemdesc','$bid','$bidname')";
mysqli_query($con, $query) or die(mysqli_error());
mysqli_query($con, $query2) or die(mysqli_error());
mysqli_close($con);
I added some server side validation to make sure that the bid posted is higher than what is currently in the MySQL table.
The problem I am having is that I get the "Sorry, but the bid is too low" error no matter what bid I put in.
If I put a bid higher than the current bid, I get the error, if I put a bid in lower, I get the error.
Both ways I go about it also trigger the success section of the AJAX.
I feel like I'm missing something very simple, so if anyone could help that would be great.
I am not sure why it's being downvoted, I am just looking for some help.
Thanks
The way that you're handling AJAX error is not very good because it only alerts you that you have an error, but you don't know what goes wrong.
In the AJAX object, replace the current error callback with one that logs the actual error to the console:
replace
error: function() {
alert("bid too low");
}
with
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
and you'll know for sure what is the error
This is the first time i am working on php and JavaScripts ... need your help in fixing something.
my site have a searchbox at the header, when a search term is submitted it goes to the search.php which holds a filter menu and search result. The filter menu is based on few selectlist. As soon as any optionis clicked in the filter menu it updates the search result.
For this i am using a javascript that calls data from another php file "SearchResult.php" to update a div with ID #Result.
PROBLEM:
it works perfectly fine at localhost however when online it causes a delay in updating the Search Result.
HELP:
Is there any way to show loading of some kind to let the viewer understand or is there anyway to make it fast.
here are my codes:
Java Script Function
function get()
{
$('#Search_Results').hide();
$.post('SearchResults.php', { Search: form.Search.value, cat: form.category.value, brand: form.brand.value },
function(output)
{
$('#Search_Results').html(output).show();
}
)
}
SEARCH FILTER FORM
enter code hereif(!empty($_REQUEST['Search'])){
$SearchTerm = $_REQUEST['Search'];
} else {
$SearchTerm = '';
}
// Search term submited
echo '<input name="Search" type="hidden" value="'.$SearchTerm.'" />';
$sql = mysql_query ("SELECT * FROM categories");
echo '<h4>Filter Categories</h4><select name="cat" onChange="get();" size="15">';
echo '<option value="" class="Select_Options">All Categories</option>';
while ($row = mysql_fetch_array($sql))
{
echo '<option class="Select_Options" value="' . $row["CategoryID"] . '">' . $row["CategoryName"] . '</option>';
}
echo '</select>';
//Few more such filters
SEARCH RESULT PAGE
if(!empty($_REQUEST['Search'])){
$SearchTerm = $_REQUEST['Search'];
}
else {
echo 'Please enter search keyword(s)';
exit();
}
if(!empty($_REQUEST['cat'])){
$cat = $_REQUEST['cat'];
$SearchQuery .= " AND categories.CategoryID = '$cat'";
}
if(!empty($_REQUEST['brand'])){
$brand = $_REQUEST['brand'];
$SearchQuery .= " AND brands.BrandID = '$brand'";
}
$sql = "SELECT DISTINCT products.ProductID, ProductKeywords, products.SectionID, products.ProductThumb, products.ProductPrice, products.CategoryID, products.SubCategoryID, products.BrandID, brands.BrandLogo, ProductTitle AS title FROM products
INNER JOIN brands ON products.BrandID = brands.BrandID
INNER JOIN sections ON products.SectionID = sections.SectionID
INNER JOIN categories ON products.CategoryID = categories.CategoryID
INNER JOIN subcategory ON products.SubCategoryID = subcategory.SubCatID $ColorJoin
WHERE MATCH (ProductKeywords) AGAINST ('$SearchTerm*' in boolean mode)$SearchQuery";
$query = mysql_query($sql);
echo '<div id="Product_Search_Container"><ul>';
while ($row = mysql_fetch_array($query))
{
$ProductID = $row["ProductID"];
$sql2 = mysql_query ("SELECT COUNT(ProColorID) AS ProductCount FROM productcolors WHERE ProductID = '$ProductID'");
while ($row5 = mysql_fetch_array($sql2))
{
$BrandID = $row["BrandID"];
$sql3 = mysql_query ("SELECT * FROM brands WHERE BrandID = '$BrandID'");
while ($row6 = mysql_fetch_array($sql3))
{
$ProductThumb = $row["ProductThumb"];
if ($ProductThumb == NULL) { $ProductThumb = "No_Image.jpg"; }
echo '<li><img src="images/Products/Thumbs/' . $ProductThumb . '" width="210px" height="275px" />
<div class="zoomer"><span class="zoom';
if ($ProductThumb != "No_Image.jpg") {
echo ' cursonstyle" style="position: relative; overflow: hidden;"><img src="images/Products/Thumbs/zoom/' . $ProductThumb . '" alt="' . $row["title"] . '" />
'; } else { echo '">'; }
echo '</span><span class="Pro_Title">' . $row["title"] . '</span>
<span class="BrandLogo"><img src="images/Brands/' . $row6["BrandLogo"] . '" /></span>
<span class="ProColors">' . $row5["ProductCount"] . ' Colors</span>
<span class="ProPrice">$' . $row["ProductPrice"] . '</span>
</a></li>';
}
}
}
echo '</ul></div>';
You could show a loading message as simple as showing it when you start the post request and hiding it in the callback.
function get()
{
$('#Search_Results').hide();
$('#loading').show().html('Please wait while loading..'); // <-- show message on function call
$.post('SearchResults.php', { Search: form.Search.value, cat: form.category.value, brand: form.brand.value },
function(output)
{
$('#loading').hide(); // <-- hide in callback function
$('#Search_Results').html(output).show();
}
)
}
You should also handle errors in your ajax request and look into prepared statements or at least use mysql_real_escape_string() for all user inputs.
If i click on my search field and submit it without entering any text all the data in my database is returned. How is this stopped so nothing happens?
Check out the site:
weezy.co.uk/newresults.php
Thanks!
James
<?php
$conn = mysql_connect("cust-mysql-123-02", "uwee_641290_0001", "La0%-Mr4");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
{
$search = "%" . $_POST["search"] . "%";
$searchterm = "%" . $_POST["searchterm"] . "%";
}
if (!mysql_select_db("weezycouk_641290_db1")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT name,lastname,email
FROM test_mysql
WHERE name LIKE '%".$search."%' AND lastname LIKE '%".$searchterm."%'";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo '<br>';
echo '<br>';
echo '<div class="data1">';
echo $row["name"];
echo '</div>';
echo '<br>';
echo '<div class="data2">';
echo $row["lastname"];
echo '</div>';
echo '<br>';
echo '<div class="data3">';
echo $row["email"];
echo '</div>';
}
mysql_free_result($result);
?>
you should check if it's empty before making a query:
if(empty($_POST['searchterm'])){
//don't search and show an error message
}else{
//proceed as normal, do the query
}
otherwise you might end up making a query like:
WHERE name LIKE('%%')
which is really expensive and returns all your database rows
Best way to do this (imo) is to have a simple javascript checking if the input is blank or not.
It is always wise to do some front end using javascript/Jquery. form validation where you are prompting users to input something.
Once you are done you may also check on the back end using the following:
if(isset($_POST['searchterm'])){
// search for the results.
}else{
// do nothing or show proper message
}
I think the best way would be to disable the submit button on the client side whenever your search box is empty.
You could do something like:
$(document).ready(function()
{
$('#searchBox').keyup(function()
{
if($(this).val() == '')
{
$('#searchButton').attr('disabled', true);
}
else
{
$('#searchButton').removeAttr('disabled');
}
});
});
where your html is like:
<input type='text' id="searchBox" />
<input type='button' id='searchButton' value='search' disabled/>
Make sure to validate on the server side as Nicola has indicated.
I was facing some problems in the above code. So the following improved version of the above code works just fine:
<form action="searchengine.php" method="POST">
<input type="text" id = "searchbox" name="searchterm" placeholder="Search here">
<input type="submit" id = "searchbutton" value="Search" style="display:none;">
</center>
<script src="http://codeorigin.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#searchbox').keyup(function()
{
if($(this).val() == '')
{
$('#searchbutton').hide();
}
else
{
$('#searchbutton').show();
}
});
});
</script>