Working with range slider and query - javascript

I have a price range with min and max value, where I would like to
Compare its min and max value with an int name course_priceFinal
What happens it simple, after a user select a min and max price using price range then it gets post using ajax and then i compare it.
The HTML and JS side of things:
<text>$</text><input type="number" id="from" name="fromPrice" readonly>
<text>$</text><input type="number" id="to" name="toPrice" readonly></p>
<div id="slider-range"></div>
</li>
<script>
$(function() {
$( "#slider-range" ).slider({
range: true,
min: 0,
max: 5000,
values: [ 300, 3000 ],
slide: function( event, ui ) {
$( "#from" ).val(ui.values[ 0 ]);
$( "#to" ).val( ui.values[ 1 ]);
document.getElementById("results").innerHTML = "<div class='loading-indication'><img src='ajax-loader.gif' /> Please wait... Loading New Courses...</div>";
var datastring = $('#testform').serialize(); // this will create key/value pairs to send to the phph page like `duration5=5` with a `&` sepparating each key/value pair
$('#display-datastring').html(datastring); // this line is just so you can see the variable being created
$.ajax({
url: 'fetch_pages.php',
type: 'post',
data: datastring,
success: function(res){
$('#results').html(res);
}
});
}
});
});
</script>
The PHP side of things:
$fromPrice = isset($_POST['fromPrice']) ? $_POST['fromPrice']: null;
$toPrice = isset($_POST['toPrice']) ? $_POST['toPrice']: null;
then ...
$fromPriceArr = array();
if (!empty($fromPrice)) $fromPriceArr[] = $fromPrice;
if (count($fromPriceArr)>0) {
$get_crs_mysqli .= " AND (course_priceFinal <= ('".implode("','", $fromPriceArr)."')) ";
}
//To Price
$toPriceArr = array();
if (!empty($toPrice)) $toPriceArr[] = $toPrice;
if (count($toPriceArr)>0) {
$get_crs_mysqli .= " AND (cast(course_priceFinal = ('".implode("','", $toPriceArr)."')) ";
}
Problem is that I receive the following error:
5023000 SELECT * FROM courses WHERE course_date1 >= CURRENT_DATE() AND (course_title like '%html%') SELECT * FROM courses WHERE course_date1 >= CURRENT_DATE() AND (course_title like '%html%') AND (course_priceFinal <= ('502')) AND (cast(course_priceFinal = ('3000')) ORDER BY course_date1 ASC LIMIT 0, 10 AND (course_priceFinal >= ('502')) AND (course_priceFinal <= ('3000'))
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\test\fetch_pages.php
Show its initial value, where at its start no value is shown until you hit the slider
http://jsfiddle.net/b453V/52/

1: You're going to need to do some investigation on why that query is failing. Whatever you're returning from the query is returning an error, so do some simple debugging:
$res = mysqli_query($link, "SELECT * FROM `blah`");
if ( !$res ) {
printf("Errormessage: %s\n", mysqli_error($link));
exit;
}
2: That's super simple. Just add the values manually in the create event. (Slide is only called when the slider is being moved). A working sample can be found here.

Related

The ajax data is not sending on update jQuery sortable

There is this piece of javascript/jQuery code that uses the sortable feature of jQuery. I use it to sort an unknown amount of divs, although currently I'm trying to send the data to the database with ajax:
Javascript with jQuery.sortable & ajax
var lst, pre;
$(".sortlist").sortable({
start:function(event, ui){
pre = ui.item.index();
},
axis: 'y',
handle: '.handle',
update: function (event, ui) {
var data = $("#list1").sortable("toArray");
console.log($("#list1").serializeArray = data);
$.ajax({
data: data,
type: 'POST',
url: 'backend/components/reorder-cards.php'
});
},
stop: function(event, ui) {
lst = $(this).attr('id');
post = ui.item.index();
other = (lst == 'list1') ? 'list2' : 'list1';
//Use insertBefore if moving UP, or insertAfter if moving DOWN
if (post > pre) {
$('#'+other+ ' div:eq(' +pre+ ')').insertAfter('#'+other+ ' div:eq(' +post+ ')');
} else {
$('#'+other+ ' div:eq(' +pre+ ')').insertBefore('#'+other+ ' div:eq(' +post+ ')');
}
}
}).disableSelection();
Every update it should use the code to do an INSERT in the php file called reorder-cards.php:
include('../../config/connect.php');
$data = $_POST['include('../../config/connect.php');
$data = $_POST['data'];
$insertdata = $conn->prepare("INSERT INTO pageOrder (order) VALUES (:order)");
$insertdata->bindParam(':order', $data, PDO::PARAM_STR);
$insertdata->execute();'];
$insertdata = $conn->prepare("INSERT INTO pageOrder (order) VALUES (:order)");
$insertdata->bindParam(':order', $data, PDO::PARAM_STR);
$insertdata->execute();
However it's not sending anything to the database, I've never gotten an insert via ajax to work. Can somebody tell me what I'm doing wrong?
use the DevTools (for example in Chrome) to check if you send an correct Ajax request, so it's easier to locate your problem.

Setting up Pickadate 'onSet'

I'm trying to setup pickadate on two inputs.When a date is selected on the first input, i would like to set the selected date in the second input if the 2nd is empty.
First I tried to update the value after the first input is selected but something doesn't work correclty.
The configuration of both input is complexe so i would like to do it this way :
$( '#event-begin-date,#event-end-date' ).pickadate({
min: true,
max: undefined,
today: '<?php echo T_("Aujourd\'hui"); ?>',
clear: '<?php echo T_("Effacer"); ?>',
close: '<?php echo T_("Fermer"); ?>',
format: '<?php echo T_("dd/mm/yyyy"); ?>',
firstDay: <?php echo T_("1"); ?>,
formatSubmit: '<?php echo T_("dd/mm/yyyy"); ?>'
});
$('#event-begin-date').pickadate({
onSet: function(thingSet) {
var picker = $input.pickadate('picker');
picker.set('select', this.component.item.select.pick );
}
});
Amsul, the creator of this plugin has made a codepan example for this case: pickadate v3: “from” & “to” dates.
this is the code incase codepen is unavailable:
var from_$input = $('#input_from').pickadate(),
from_picker = from_$input.pickadate('picker')
var to_$input = $('#input_to').pickadate(),
to_picker = to_$input.pickadate('picker')
// Check if there’s a “from” or “to” date to start with.
if ( from_picker.get('value') ) {
to_picker.set('min', from_picker.get('select'))
}
if ( to_picker.get('value') ) {
from_picker.set('max', to_picker.get('select'))
}
// When something is selected, update the “from” and “to” limits.
from_picker.on('set', function(event) {
if ( event.select ) {
to_picker.set('min', from_picker.get('select'))
}
else if ( 'clear' in event ) {
to_picker.set('min', false)
}
})
to_picker.on('set', function(event) {
if ( event.select ) {
from_picker.set('max', to_picker.get('select'))
}
else if ( 'clear' in event ) {
from_picker.set('max', false)
}
})
For propose solution, pay attention of double declaration of .pickadate() :
var from_$input = $('#input_from').pickadate(),
from_picker = from_$input.pickadate('picker');
First line will redeclare without any customization which could lead to issue in your code.
A more consise way to proceed using event, and adding data-from or data-to in your input :
When you open the modal, event check if there is value in from/to and set on the fly the max/min value
var from = $(this).data('from'),
to = $(this).data('to');
$(this).attr('data-value', $(this).val()).pickadate({
min: true,
selectMonths: true,
selectYears: 3,
format: 'dd mmm yyyy',
formatSubmit: 'yyyy-mm-dd',
hiddenName: true,
onOpen: function() {
if(typeof from !== 'undefined' && $('#' + from)) {
var value = ($('#' + from).val() === '' ? true : $('#' + from).pickadate('picker').get('select'));
this.set('min', value);
} else if(typeof to !== 'undefined' && $('#' + to)) {
var value = ($('#' + to).val() === '' ? false : $('#' + to).pickadate('picker').get('select'));
this.set('max', value);
}
}
});

database won't refresh when I search for a different query. -ajax

ok let me try to explain this as detail as I can.
I have these different inputs. It has passenger names, ticket numbers and rloc.
I am trying to search the passengers let's say by ticket number.
I have this search button to search into the database for the ticket number.
I got the ticket number and I am trying to find the next ticket number by clicking the next button. It works up to this point. (these are done by using ajax)
What is making me stuck is. If I didn't refresh the page, the database would stay to the database used when I click next.
sample if I input 111 searched the record, pull it out and I click next it'll go for record 112 then 113 with another click but without refreshing the page, I input 111 and search which still works but if I click next again it'll show the record of 114 instead of 112.
I thought it might be something about the .on() event for binding purpose but still not getting it right. Can someone give me an extra eyes please? Thank you.
Here is my html which is really basic
<div class="container">
<div class="title">
<h1>Ticket search</h1>
</div>
<div class="update-info">
<h3>{{$num}} files have been convert and updated.</h3>
</div>
<div class="sub-container">
<div class="form-field">
<label>Ticket Number : </label>
<input class="ticket-field" type="text" name="ticketNumber" value="" placeholder="Please enter ticket number">
</div>
<div class="button-field">
<input type="submit" class="btn-search"value="Search">
<button class="btn-update">Update</button>
<button class="btn-prev" name="previous">PREV</button>
<button class="btn-next" name="next">NEXT</button>
</div>
<input type="hidden" name="ticketHolder" value="">
</div>
<div id="text-field">
</div>
</div>
my js search using jquery and ajax
$("div.container").on("click", ".btn-search", function(event) {
event.preventDefault();
var noError = true;
var ticketNumber = $.trim($("input[name='ticketNumber']").val());
if($.isNumeric(ticketNumber) || ticketNumber==""){
noError = true;
}else{
noError = false;
$("input[name='ticketNumber']").val('');
alert("please enter a number");
}
if(noError){
$("#text-field").empty();
$.ajax({
method: "post",
url: "/search",
dataType: "json",
data: {ticketNumber:ticketNumber},
success: function(data){
if(data.length>1){
$.each(data,function(index,item){
$("#text-field").append("<h3 class='block-hearder'><span>"+item['dateOfFile']+"</span><span>"+item['paxName']+"</span><span>"+item['airlineName']+"</span></h3><div class='text-block'>"+item['content']+"</div>");
});
$( "#text-field" ).accordion( "destroy" );
$( "#text-field" ).accordion({
collapsible: true
});
}else{
$.each(data,function(index,item){
$("#text-field").append("<div class='text-block-single'>"+item['content']+"</div>"+"<script>");
searchNext(item['systemName'],item['ticketNumber']);
if(item['content'].indexOf('S') != 0){
$('.btn-prev').button( "enable" );
$('.btn-next').button( "enable" );
}
});
}
$("input[name='ticketNumber']").val('');
}
});
}
}); //end btn-search
my searchNext() for js
function searchNext(systemName, ticketNumber){
var systemName = systemName;
var ticketNumber = Number(ticketNumber);
// Making sure this function doesn't get called twice
if( !this.wasRun ){
$(".btn-next").click(function(event) {
event.preventDefault();
$.ajax({
method: "post",
url: "/next",
dataType: "json",
data: {systemName: systemName, ticketNumber: ticketNumber},
success: function(data){
$("#text-field").empty();
$("#text-field").append("<div class='text-block-single'>"+data['content']+"</div>");
if(data['content'].indexOf('>') > 0){
if((ticketNumber + 1) == data['ticketNumber']){
ticketNumber++;
searchNext(ticketNumber, data['systemName']);
}
}else{
$('.btn-next').button( "disable" );
}
}
});
}); //end btn-next
}
this.wasRun = true;
} //end searchNext()
in my php, my search()
public function search(){
$data = array();
/* Check if ticket number entered is not null and is number */
if(($_POST['ticketNumber'] != null) && (is_numeric($_POST['ticketNumber']))){
$ticketNumber = trim($_POST['ticketNumber']);
}else{
$ticketNumber = "";
}
if(strlen($ticketNumber) == 10 ){
$model = Document::where('ticketNumber', '=', $ticketNumber)->get();
}else{
$data['content'] = 'entery valid ticket number (10 numbers)';
}
$index = 0;
if(sizeof($model)>0){
foreach ($model as $key => $value) {
$document = $value->getAttributes();
$data[$index]['content']=$document['fileContent'];
$data[$index]['dateOfFile']=$document['dateOfFile'];
$data[$index]['systemName']=$document['systemName'];
$data[$index]['ticketNumber']=$document['ticketNumber'];
$index++;
}
}else{
$data[$index]['content'] = "Sorry the document does not exist, or hasn't been update yet, please click update and try again.";
}
echo json_encode($data);
} //End search function
in my php next() which searches the next record
public function next(){
$data = array();
$systemName = $_POST['systemName'];
$nextTicketNumber = $_POST['ticketNumber'] + 1;
//used to get the nextTicketNumber if there is a sequential nextTicketNumber
$model = Document::where('systemName', '=', $systemName)
->where('ticketNumber', '=', ($nextTicketNumber))->get();
if(sizeof($model) == 0){
$data['content'] = 'Reached end of record';
return json_encode($data);
}
//Getting all the same system number and stores the tickets in an array to find the max ticketNumber
$getAllModel = Document::where('systemName', '=', $systemName)->get();
$allTicketNumber = [];
if(sizeof($getAllModel) > 0){
foreach($getAllModel as $key => $value){
$allTicketNumber[] = $value->ticketNumber;
}
}
$maxTicketNumber = max($allTicketNumber);
if($nextTicketNumber > $maxTicketNumber){
$data['content'] = 'Reached end of record';
}else{
$data['content'] = $model[0]->fileContent;
$data['ticketNumber'] = $model[0]->ticketNumber;
$data['systemName'] = $model[0]->systemName;
}
echo json_encode($data);
}

Prevent already selected option Jquery autocomplete with MYSQL

I am using Jquery Autocomplete to fetch a list of tags from a mysql table. When the user picks one tag from the list, it gets saved on the page. I am trying to prevent the already saved tag from being displayed again.
Here is my code:
HTML
<input type="text" id="tag">
<input type="text" id="tags" style="display:none;">
Jquery
$('#tag').autocomplete({
source : function(request, response) {
$.ajax({
url : 'tags.php',
dataType : "json",
method : 'post',
data : {
searchQuery : request.term,
selectedTags: $('#tags').val() //sends already selected terms
},
success : function(data) {
response($.map(data, function(item) {
var code = item.split("|");
return {
label : code[0],
value : code[0],
data : item
}
}));
},
error: function(jqxhr, status, error)
{
alert(error);
}
});
},
autoFocus : true,
minLength : 1,
select : function(event, ui) {
var names = ui.item.data.split("|");
tag_ids = [];
tag_names = [];
tags = $('#tags').val();
if(tags != '')tag_names = tags.split(',');
tag_ids.push(names[1]);
tag_names.push("'" + names[0] + "'");
$('#tags').show();
$('#tags').val( tag_names.join( "," ) );
$('#tag').val('');
}
PHP
$searchQuery = $_POST['searchQuery'];
$selectedTags = $_POST['selectedTags'];
if(!empty($selectedTags))
{ $query = $db->prepare("SELECT * FROM tags WHERE name LIKE ? AND name NOT IN ?");
$query->execute(array($searchQuery . "%", $selectedTags));
}
else
{
$query = $db->prepare("SELECT * FROM tags WHERE name LIKE ?");
$query->execute(array($searchQuery . "%"));
}
When I select the first suggestion, it gets saved in #tags but then no other suggestion is displayed. If there is any other suggestion to achieving this, that'd be great.
I figured it out. I was trying to pass an array to the prepared statement.
PDO doesn't work that way.
To solve this, I declared the number of parameters first and then put them in the prepared statement while using foreach to bindvalue to each parameter.
Here is the final solution:
//exploding the string to an array first
$selectedTags = explode(',', $selectedTags);
//creating another array with parameters equal to the size of the selectedTags
$bindValues = implode(',', array_fill(0, count($selectedTags), '?'));
//putting the parametes
$query = $db->prepare("SELECT * FROM tags WHERE name LIKE ? AND name NOT IN (" . $bindValues .")");
//binding values
$query->bindValue(1, $searchQuery . '%');
//Now, using foreach to bind selected tags values
foreach($selectedTags as $k => $selectedTag)
{
//using k+2 as index because index starts at 0 and first parameter is the search query
$query->bindValue($k+2, $selectedTag);
}
$query->execute();
And this solved the problem. I hope it helps others too.

Intercept and pre-process jQuery-ui autocomplete data

I have a Jquery UI autocomplete code that grabs data from an ajax request, as i grab the data the results are already put in the input box where the autocomplete is attached. my problem is i have a other data along the data that will be posted with the result of the autocomplete.
I had tried to grab all the i need and put it in a single string with delimeters so i can split() it on the client-side. I want to save the other data in a hidden text field
here is my code
<div id="01ac091c834d81b41f0ef4b6eb09cde90bb9aa1a" style="display:none" title="Add Member">
Type the name of the member
<br>
<br>
<div style="text-align:center">
<input type="text" id="txtUserFind" size="35">
</div>
<input type="hidden" id="hidtxtUserFind-nickname">
<input type="hidden" id="hidtxtUserFind-userhash">
<input type="hidden" id="hidtxtUserFind-picture">
<input type="hidden" id="hidtxtUserFind-sex">
</div>
<script type="text/javascript">
head(function() {
$(":button:contains('Select User')").attr("disabled","disabled").addClass("ui-state-disabled");
$("#txtUserFind").keydown(function(){
$(":button:contains('Select User')").attr("disabled","disabled").addClass("ui-state-disabled");
});
$("#txtUserFind").change(function(){
var userdetails = $("#txtUserFind").val().split(";");
alert($("#txtUserFind").val());
/*
0 profiles.nickname,
1 profiles.firstname,
2 profiles.surname,
3 users.user_hash,
4 profiles.sex,
5 profiles.picture
*/
$("input#hidtxtUserFind-nickname").val(userdetails[0]);
$("input#txtUserFind").val(userdetails[1] + " " + userdetails[2]);
$("input#hidtxtUserFind-userhash").val(userdetails[3].replace("u-",""));
$("input#hidtxtUserFind-sex").val(userdetails[4]);
if(userdetails.length > 5){
$("input#hidtxtUserFind-picture").val(userdetails[5]);
}
});
$("<?php echo $tagmemberbtn; ?>").click(function(){
$("#01ac091c834d81b41f0ef4b6eb09cde90bb9aa1a").dialog({
modal:true,
resizable: false,
height:250,
width:400,
hide:"fade",
open: function(event, ui){
searchdone = false;
$(":button:contains('Select User')").attr("disabled","disabled").addClass("ui-state-disabled");
},
beforeClose: function(event, ui){
$("#txtUserFind").val("");
},
buttons:{
"Select User":function(){
$(this).dialog("close");
},
"Close":function(){
searchdone = false;
$("#txtUserFind").val("");
$(this).dialog("close");
}
}
});
});
$(function() {
var cache = {},
lastXhr;
$("#txtUserFind").autocomplete({
source:function(request,response) {
var term = request.term;
if ( term in cache ) {
response(cache[term]);
return;
}
lastXhr = $.getJSON(cvars.userburl+"getusers", request, function(data,status,xhr) {
stopAllAjaxRequest();
cache[ term ] = data;
if ( xhr === lastXhr ) {
response( data );
}
});
},
minLength: 1,
select: function(event, ui) {
$(":button:contains('Select User')").removeAttr("disabled").removeClass("ui-state-disabled");
}
}).data("autocomplete")._renderItem = function(ul,item){
if(item.picture==null){
//know if girl or boy
if(item.sex<=0){
item.picture = cvars.cthemeimg + "noimagemale.jpg";
}
else{
item.picture = cvars.cthemeimg + "noimagefemale.jpg";
}
}
else{
item.picture = cvars.gresuser + "hash=" + item.user_hash.replace("u-","") +"&file="+item.picture.replace("f-","");
}
var inner_html = '<a><div class="autocomplete-users-list_item_container"><div class="autocomplete-users-image"><img src="' + item.picture + '" height="35" width="35"></div><div class="label">' + item.nickname + '</div><div class="autocomplete-users-description">' + item.firstname + " " + item.surname + '</div></div></a>';
return $("<li></li>")
.data("item.autocomplete",item)
.append(inner_html)
.appendTo(ul);
};
});
});
You idea is right, you must use a callback as the source parameter. I've put together an example here:
Demo on jsFiddle
If you read the documentation carefully it says:
The third variation, the callback, provides the most flexibility, and
can be used to connect any data source to Autocomplete. The callback
gets two arguments:
A request object, with a single property called "term", which refers
to the value currently in the text input. For example, when the user
entered "new yo" in a city field, the Autocomplete term will equal
"new yo".
A response callback, which expects a single argument to contain the
data to suggest to the user. This data should be filtered based on the
provided term, and can be in any of the formats described above for
simple local data (String-Array or Object-Array with label/value/both
properties). It's important when providing a custom source callback to
handle errors during the request. You must always call the response
callback even if you encounter an error. This ensures that the widget
always has the correct state.
So here is an example implementation I used in the demo:
$("#autocomplete").autocomplete({
source: function(request, response) {
$.ajax({
url: "/echo/html/", // path to your script
type: "POST", // change if your script looks at query string
data: { // change variables that your script expects
q: request.term
},
success: function(data) {
// this is where the "data" is processed
// for simplicity lets assume that data is a
// comma separated string where first value is
// the other value, rest is autocomplete data
// the data could also be JSON, XML, etc
var values = data.split(",");
$("<div/>").text("Other value: " + values.shift()).appendTo("body");
response(values);
},
error: function() {
response([]); // remember to call response() even if ajax failed
}
});
}
});
You can include a function on select. Within that function you can access the value and the label of the selected item and process as needed:
$('#input_id').autocomplete({
source:"www.example.com/somesuch",
select: function(event, ui){
var value = ui.item.value;
valueArray = value.split('whatever delimiter here');
//do what you will with the values
ui.item.value = ui.item.label; //This ensures only the label is displayed after processing.
}
});

Categories

Resources