Can jQuery UI Autocomplete use values from multiple input fields - javascript

I've been struggling with this code for a while and honestly I'm stuck.
This is how my auto-complete script looks like:
jQ19(function(){
// minLength:1 - how many characters user enters in order to start search
jQ19('#location_name').autocomplete({
source:'adress.php',
minLength:2,
select: function(event, ui){
// just in case you want to see the ID
var accountVal = ui.item.value;
console.log(accountVal);
// now set the label in the textbox
var accountText = ui.item.label;
jQ19('#location_name').val(accountText);
return false;
},
focus: function( event, ui ) {
// this is to prevent showing an ID in the textbox instead of name
// when the user tries to select using the up/down arrow of his keyboard
jQ19( '#location_name' ).val( ui.item.label );
return false;
}
});
});
Some more js to get me the additional value:
<script type='text/javascript'>
$('#city').on( 'change', function () {
var x = document.getElementById('city').value;
$.ajax({
type: 'post',
url: 'http://localhost/profsonstage/account/_compettions/autocomplate/location_name.php',
data: {
value: x
},
success: function( data ) {
console.log( data );
}
});
});
</script>*/
And the php that fetches the data results:
try {
$con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}catch(PDOException $exception){ //to handle connection error
echo "Connection error: " . $exception->getMessage();
}
// get the search term
$city = $_GET['city'];
$b = explode(" ",$city); //get rid of the city code
$a =$b[0];
$search_term = isset($_REQUEST['term']) ? $_REQUEST['term'] : "";
//query to search for data
$query = "SELECT * from locations where adress like '%$search_term%' and city=='$a'
LIMIT 0 , 5";
The problem is when the user types a value in the input for the #City the query looks like this:
$query = "SELECT * from locations where adress like '%%' and
city=='SomeCity'
LIMIT 0 , 5";
and when we go to the next input that (is supposed to be autocomplete too and start typing) the query looks like
$query = "SELECT * from locations where adress like '%input to autocomplate%' and
city==''
LIMIT 0 , 5";
Basically I can't figure out a way to pass the values at the same time. Any help will be appreciated.

You can use following;
jQ19(function(){
// minLength:1 - how many characters user enters in order to start search
jQ19('#location_name').autocomplete({
minLength:2,
select: function(event, ui){
// just in case you want to see the ID
var accountVal = ui.item.value;
console.log(accountVal);
// now set the label in the textbox
var accountText = ui.item.label;
jQ19('#location_name').val(accountText);
return false;
},
source: function( request, response ) {
var term = request.term;
$.getJSON( "address.php?term=" + term + "&city=" + $("#city").val(), request, function( data, status, xhr ) {
response( data );
});
},
focus: function( event, ui ) {
// this is to prevent showing an ID in the textbox instead of name
// when the user tries to select using the up/down arrow of his keyboard
jQ19( '#location_name' ).val( ui.item.label );
return false;
}
});
});
And in your php file;
try {
$con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}catch(PDOException $exception){ //to handle connection error
echo "Connection error: " . $exception->getMessage();
}
// get the search term
$city = $_GET['city'];
$b = explode(" ",$city); //get rid of the city code
$a =$b[0];
$search_term = isset($_REQUEST['term']) ? $_REQUEST['term'] : "";
//query to search for data
$query = "SELECT * from locations where adress like '%$search_term%' and city=='$a'
LIMIT 0 , 5";
//Fetch your data and respond json

Related

I want to highlight words i enter in autocomplete search bar

I want to achieve this in below mention code need
i want to highlight text in auto complete same like pic i added above
<?php
$query = isset($_GET['query']) ? $_GET['query'] : FALSE;
global $wpdb;
// escape values passed to db to avoid sql-injection
$depts = $wpdb->get_results( "SELECT * FROM wp_paklog_service WHERE service_name LIKE '".$query."%'" );
$suggestions = array();
$data = array();
foreach($depts as $row) {
$suggestions[] = $row->service_name;
$data[] = $row->id;
}
json_encode ($suggestions);
?>
//this is js code
var obj = <?php echo json_encode($suggestions); ?>;
jQuery(".search-services").autocomplete({
source: function( request, response ) {
var matcher = new RegExp( "^" + jQuery.ui.autocomplete.escapeRegex( request.term ), "i" );
response( jQuery.grep( obj, function( item ){
return matcher.test( item );
}) );
}

parsererrorDetails : SyntaxError: Unexpected end of input

I've been trying to do an ajax form for my web page.
Form sending informations into register.php for check process.
If its OK they are adding into database.
Problem is :
First record is always working properly. But if i try to add another record into database it gives parsererrorDetails : SyntaxError: Unexpected end of input error.
If the current information already exist in database i put the error message to the screen. But if i try to send another record it gives the same error.
I think i can't get the second data after submitting the first one is not coming back as a JSON.
Here is my code . Any help much appricated.
Server Side / register.php
I've got header('Content-type: application/json'); on the top.
try {
// local db connection
$conn = new PDO('mysql:host=localhost;dbname=db_trop#Dubai;charset=utf8','root','mysql');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (isset($_POST)) {
// CHECK IF PASSWORD ALREADY IN USE
$objP = clear(strtoupper($_POST['objPass'])); // Get Ajax Data
// $stmt = $conn->prepare('SELECT Id,PassNumber FROM tblRecords WHERE PassNumber = ?');
// $stmt->execute(array($objP));
$stmt = $conn->prepare('SELECT Id,PassNumber FROM tblRecords WHERE PassNumber = :passnum');
$stmt->bindParam(':passnum', $objP);
$stmt->execute();
$PassResult = $stmt->fetchAll();
// (PDO::FETCH_ASSOC)
if($PassResult) {
// IF THE PASSWORD FAILS
$response_array['status'] = 'fail';
$response_array['message'] = 'Parola Kullanılıyor';
echo json_encode($response_array);
die();
} else {
// ADD DATA TO DATABASE
$fTerms = intval($_POST['objTerms']);
$fNameSurname = clear(strtoupper($_POST['objNameSurname']));
$fMail = clear($_POST['objEmail']);
$fGsm = clear(intval($_POST['objGsm']));
$fAddress = clear(strtoupper($_POST['objAdres']));
$DateTime = date('d-m-Y h:i:s');
if($fTerms==1) {
// SQL
$SqlQuery = "INSERT INTO tblRecords(NameSurname, Email, Gsm, Address, PassNumber,DateAdded, IsChecked)
VALUES (:fNameSurname, :fMail, :fGsm, :fAddress,:objP, :DateTime,:fTerms)";
// RECORDS
$addRecords = $conn->prepare($SqlQuery);
$addRecords->bindParam(':fNameSurname', $fNameSurname, PDO::PARAM_STR);
$addRecords->bindParam(':fMail', $fMail, PDO::PARAM_STR);
$addRecords->bindParam(':fGsm', $fGsm, PDO::PARAM_INT);
$addRecords->bindParam(':objP', $objP, PDO::PARAM_STR);
$addRecords->bindParam(':fAddress', $fAddress, PDO::PARAM_STR);
$addRecords->bindParam(':DateTime', $DateTime, PDO::PARAM_STR);
$addRecords->bindParam(':fTerms', $fTerms, PDO::PARAM_STR);
$addRecords->execute();
// END OF RECORD PROCESS
if ($addRecords) {
$response_array['status'] = 'success';
$response_array['message'] = 'BRAVO';
$conn = null;
} else {
$response_array['status'] = 'fail';
$response_array['message'] = 'OLMADI';
$conn = null;
}
} else {
die();
}
}
}
and Client Side / main.js
$("#register").submit(function (event, request) {
var password = $(this).find('input[name="objPassword"]').val();
var namesurname = $(this).find('input[name="objNameSurname"]').val();
var email = $(this).find('input[name="objEmail"]').val();
var gsm = $(this).find('input[name="objGsm"]').val();
var adres = $(this).find('input[name="objAddress"]').val();
var termsOk = $(this).find('input[name="objAcceptTerms"]').val();
var formURL = $(this).attr("action");
var postMessage;
if (postMessage) {
postMessage.abort();
}
var postData = {"objPass": password, "objNameSurname": namesurname, "objEmail": email, "objGsm": parseInt(gsm), "objAdres": adres, "objTerms": termsOk };
postMessage = $.post(formURL, postData, function (data) {
$('#register').trigger("reset");
})
.done(function(data) {
var defaultText = '';
if(data.status == 'success'){
$( ".info-row span" ).html(data.message);
$("#register").find('input[name="objPassword"]').val('');
$("#register").find('input[name="objNameSurname"]').val('');
$("#register").find('input[name="objEmail"]').val('');
$("#register").find('input[name="objGsm"]').val('');
$("#register").find('input[name="objAddress"]').val('');
$("#register").find('input[name="objAcceptTerms"]').val('');
$('input:checkbox').removeAttr('checked');
$('input').removeClass("error");
$('input[type=text]').focus(function() {
defaultText = $(this).val();
$(this).val('');
$( ".info-row span" ).html("");
});
// $('#register').trigger("reset");
console.log(data);
} else if(data.status == 'fail'){
$( ".info-row span" ).html(data.message);
$("#register").find('input[name="objPassword"]').val('');
$("#register").find('input[name="objNameSurname"]').val('');
$("#register").find('input[name="objEmail"]').val('');
$("#register").find('input[name="objGsm"]').val('');
$("#register").find('input[name="objAddress"]').val('');
$("#register").find('input[name="objAcceptTerms"]').val('');
$('input:checkbox').removeAttr('checked');
$('input').removeClass("error");
$('input[type=text]').focus(function() {
defaultText = $(this).val();
$(this).val('');
$( ".info-row span" ).html("");
});
console.log(data);
// $('#register').trigger("reset");
}
}) .fail(function (jqXHR, textStatus, errorThrown) {
alert(JSON.stringify(textStatus));
// $( ".info-row span" ).html(textStatus);
console.error("Error: " + textStatus + "Details : " + errorThrown);
// console.error("Error: " + textStatus + "Details : " + errorThrown);
}) .always(function(data) {
$('#register').trigger("reset");
});
event.preventDefault();
});
What i want to do is that:
Users can enter their informations consecutively and after each form has submitted i want to put error message on the screen (which is working right now but not working after first submit.)
Thanks

ajax add and delete with same button

I am trying to create a button that when clicked will add a record to that database, and when clicked again, will delete this record from that database (it's a 'favourite' button).
I would like it to work as follows;
User clicks 'fav' button > button state changes to success > record added
User clicks 'fav' button again > state changes to default > record removed from db
So far my code is as follows (updated code thanks to #Peter);
books_model.php
class BooksModel
{
public function checkFav($bookid,$userid)
{
$book_id=$_REQUEST['book_id'];
$user_id=$_SESSION['user_id'];
$sql = "SELECT * FROM favourite WHERE user_id=? AND book_id=?";
$query = $this->db->prepare($sql);
$query->bind_param('ii', $userid,$bookid);
$query->execute();
$query->store_result();
$rows_found = $query->num_rows();
if(empty($rows_found)) {
$sql = "INSERT INTO favourite (user_id, book_id)
VALUES (?, ?)";
$query = $this->db->prepare($sql);
$query->bind_param('ii',$userid,$bookid);
$query->execute();
} else {
$sql = "DELETE FROM favourite WHERE user_id=? AND book_id =?";
$query = $this->db->prepare($sql);
$query->bind_param('ii',$userid,$bookid);
$query->execute();
}
}
}
books_controller.php
class Books extends Controller
{
function checkFav()
{
$checkFav_model = $this->loadModel('Books');
}
}
itemView.php
$(document).ready(function(){
$( "#fav" ).click(function(){
$( this ).toggleClass( "btn-success" );
book_id = $(fav).val(); // set the value of the button (book_id)
$.ajax({
type: 'POST',
url: '<?php echo URL; ?>books/checkFav', //location of query
data: {book_id:book_id}, //taken from value of button
success: function () {
$( "div.addtofavs" ).slideToggle( "slow" ); //show div below button
}//end success
});//end ajax
});
});
button html
<button id="fav" value="'.$book->id.'" type="button" class="btn btn-default"></button>
Currently when I click the button and look in the console I can see the post, however nothing is being sent to my db.
Any advice or direction is appreciated as I am quite new to MVC and JS.
public function checkFav($bookid,$userid)
{
$sql = "SELECT * FROM favourite WHERE user_id=:userid AND book_id=:bookid";
$query = $this->db->prepare($sql);
$query->bindParam(':userid', $userid);
$query->bindParam(':bookid', $bookid);
$query->execute();
$rows_found = $query->countRows();
if(empty($rows_found)) {
$sql = "INSERT INTO favourite (user_id, book_id) VALUES (:userid, :bookid)";
$query = $this->db->prepare($sql);
$query->bindParam(':userid', $userid);
$query->bindParam(':bookid', $bookid);
$query->execute();
} else {
$sql = "DELETE FROM favourite WHERE user_id=:userid AND book_id =:bookid";
$query = $this->db->prepare($sql);
$query->bindParam(':userid', $userid);
$query->bindParam(':bookid', $bookid);
$query->execute();
}
}
$book_id=$_REQUEST['book_id'];
$user_id=$_SESSION['user_id'];
checkFav($book_id,$user_id);
You can simply do a check:
SELECT * FROM favourite WHERE user_id = :user_id AND book_id = :book_id
if it returns something, execute the
DELETE FROM favourite WHERE user_id = :user_id AND book_id = :book_id
else do the insert.
If you want to show the book is already added as favourite to the user, then you have to execute another call on page load which gives the button an attribute, which tells you AND the user it's already a favourite or not.
In the last case you don't have to do the check anymore. Just execute the DELETE query if it contains the attribute, else do the INSERT
// try to get the attribute of the button
var attr = $(".favoriteButton").attr('data-favorite');
// check the button has the attribute
if (typeof attr !== typeof undefined && attr !== false) {
//delete query
$.ajax({
type: 'POST',
url: '<?php echo URL; ?>books/deleteFav', //location of query
data: {book_id:book_id}, //taken from value of button
success: function () {
$( "div.addtofavs" ).slideToggle( "slow" ); //show div below button
}//end success
});//end ajax
});
}
Something like that
Use generic vars: var IsDeleted; var IsAdded; then IsDeleted = 0; IsAdded =1; (your book is added). Change the values again when you delete book IsDeleted = 1; IsAdded =0; when you execute $( "#fav" ).click(function() check those values and do what action you want (add, delete).
<button class="fvrt" data-item-id="11" data-current-state="0"> Like <button> // 0 = normal, 1 = liked
$(document).on('click', '.fvrt', function(){
if($(this).attr('data-current-state') == 0){
like_item($(this).attr('data-item-id')); // send ajax request
$(this).attr('data-current-state', '1');
$(this).val('Liked');
}else{
dislike_item($(this).attr('data-item-id')); // send ajax request
$(this).attr('data-current-state', '0');
$(this).val('Like');
} // checking state
}); // on clicked

No response from jQuery .post even though PHP is returning correct data

Here is my jQuery:
function SelectSubCats(cat_num) {
console.log("Select SubCats..");
$.post("ajax.php", {
_populateSubCats : 1,
cat_num : cat_num
},
function(data){
console.log("Data: " + data );
});
}
I am not reaching the console.log statement is the problem.
in ajax.php:
else if(array_key_exists('_populateSubCats', $_POST)) { // {{{
$cat_num = $DB->escape($_POST['cat_num']);
print GetSubCats($cat_num);
} // }}}
function GetSubCats($cat_num) {
global $DB;
$returnHTML = '';
$query = "SELECT sc_i_num, sc_s_subcategory FROM subcat "
. "WHERE sc_i_c_num = {$cat_num} "
. "ORDER BY sc_s_subcategory";
$result = $DB->query($query);
$returnHTML .= "<option value=''></option>";
while($obj = $DB->next($result)) {
$returnHTML .= "<option value='{$obj->sc_i_num}'>{$obj->sc_s_subcategory}</option>";
}
return $returnHTML;
}
The return generates <option>s for a <select>. The idea is, there are categories and subcategories. The jQuery function above is called in the onchange of the category <select>. Eventually I'd like to replace that console.log with an append to add the new data to the sub-category select. But right now, I am just trying to get a response. I have logged the php side and am getting the exact response I need. What else is going on?
Specify the type of response you want by adding , 'html'.
i.e.:
function SelectSubCats(cat_num) {
console.log("Select SubCats..");
$.post("ajax.php", {
_populateSubCats : 1,
cat_num : cat_num
},
function(data){
console.log("Data: " + data );
}, 'html' );
}

.ajax() isn't posting to php database query

This has been an ongoing issue for me. You all have already helped so much. However, I am stuck again. I cannot get my .ajax() to run. For some reason the .click() won't even work without if(field != text) above my .ajax() call, but I digress.
My question is: Why is my ajax() not functioning properly and if this gets fixed will the table is have displayed update after the query is sent to the database without a page refresh?
Here is my script:
<script type="text/javascript">
$(document).ready(function()
{
$(".edit_td").click(function()
{
$(this).children(".text").hide();
$(this).children(".editbox").show();
}).children('.editbox').change(function()
{
var id=$(this).closest('tr').attr('id');
var field=$(this).data('field');
var text=$(this).val();
var dataString = 'id= '+ id +'&field= '+ field +'&text= '+ text;
alert("made variables");
if(field != text)
{
alert("in if");
$.ajax({
type: "POST",
url: "table_edit_ajax.php",
data: dataString,
cache: false,
success: function(html)
{
$("#first_"+ID).html(first);
$("#last_"+ID).html(last);
}
});
}
else
{
alert('Enter something.');
}
});
// Edit input box click action
$(".editbox").mouseup(function()
{
return false
});
// Outside click action
$(document).mouseup(function()
{
$(".editbox").hide();
$(".text").show();
});
});
</script>
Here is my table_edit_ajax.php
<?php
//connect to DB
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
echo 'in table_edit';
$id = mysqli_escape_String($_POST['id']);
$table = "owners";
$field = mysqli_escape_String($_POST['field']);
$text = mysqli_escape_String($_POST['text']);
$query = "UPDATE ".$table." SET ".$field."='".$text."' WHERE ".$table."_id = '".$id."'";
mysqli_query($query);
//close connection
mysqli_close($con);
?>
The first argument to all mysqli functions is the connection, statement, or result object.
$id = mysqli_escape_String($con, $_POST['id']);
$table = "owners";
$field = $_POST['field'];
$text = mysqli_escape_String($con, $_POST['text']);
$query = "UPDATE ".$table." SET ".$field."='".$text."' WHERE ".$table."_id = '".$id."'";
mysqli_query($con, $query);
$field shouldn't be escaped, since it's not a string value. Therefore, you need to validate it carefully, to prevent SQL injection. Perhaps instead of allowing the client to submit the field name to update, have them submit an integer, which you look up in an array to convert to a field name.
In your AJAX call, you may have a problem due to not encoding your parameters properly. Change the dataString assignment to:
var dataString = { id: id, field: field, text: text };
Then jQuery will encode it for you.
you are sending a data string
var dataString = 'id= '+ id +'&field= '+ field +'&text= '+ text;
and retrieving it through $_POST.
first check what is in $_POST
and use $_GET instead of $_POST
and change post in ajax to get
and what is first and last in success callback??

Categories

Resources