Ascending and Descending in Ionic - php

I have a problem in ionic.
so, when i choose the select list in "A-Z", it means ascending.
and when i click the button, it should go to another state that show my list.
if A-Z is choosen, the "goal futsal " should be number 1 right?.
how can i do that? what's wrong with my code. Please help.
thank you.
here is controller that i use in my code.
.controller('cariCtrl',function($scope,$http,$state,Cari){
$scope.cari = function(input){
Cari.setDaerah(input.daerah);
Cari.setNama(input.nama);
Cari.setUrut(input.urut);
$state.go('back.list');
}
})
.controller('listCtrl',function($scope,$http,$state,$ionicHistory,Cari){
$scope.user = [];
$scope.lapangan = [];
$scope.goBack = function(){
$state.go('menu.cari', {}, {
reload: true
});
}
$http({
method: 'POST',
data:{
daerah: Cari.getDaerah(),
nama: Cari.getNama(),
urut: Cari.getUrut()
},
url: "http://localhost/TA2/admin/app/getSearchLapangan.php"
}).success(function(data){
$scope.lapangan = data;
}).error(function(data, status,headers,config) {
alert(status);
alert(headers);
});
})
in app.js, i add this :
.factory('Cari', function(){
var data = {
daerah: '',
nama: '',
urut: ''
};
return {
getDaerah: function(){
return data.daerah;
},
setDaerah: function(pdaerah){
data.daerah = pdaerah;
},
getNama: function(){
return data.nama;
},
setNama: function(pnama){
data.nama = pnama;
},
getUrut: function(){
return data.nama;
},
setUrut: function(purut){
data.urut = purut;
}
};
})
The sql query is like this:
$daerah = $objData->daerah;
$nama = $objData->nama;
$urut = $objData->urut;
$SQL = "";
if ($urut == 0) {
$SQL = "SELECT L.*, (SELECT path FROM gambar G WHERE G.id_lapangan = L.id_lapangan LIMIT 1) as path from lapangan L WHERE daerah LIKE '" . $daerah . "%' AND nama LIKE '" . $nama . "%' ORDER BY nama ASC;";
} else {
$SQL = "SELECT L.*, (SELECT path FROM gambar G WHERE G.id_lapangan = L.id_lapangan LIMIT 1) as path from lapangan L WHERE daerah LIKE '" . $daerah . "%' AND nama LIKE '" . $nama . "%' ORDER BY nama DESC;";
}
$result = mysql_query($SQL, $link);
$array = array();
$counter = 0;
while ($row = mysql_fetch_array($result)) {
$array[$counter] = $row;
$counter++;
}
echo json_encode($array);
Here is my view :
<label class="item item-select">
<select style="right: auto;" ng-model="input.urut">
<option value="">Silahkan Pilih Urutan</option>
<option value="0">A-Z</option>
<option value="1">Z-A</option>
</select>
</label>
<button class="button button-block button-positive" ng-click="cari(input)">Cari</button>
by the way, i use php. Please help me.

You can set Ascending and Descending order list in Ionic
<label class="item item-select">
<select ng-model="input.urut" ng-change="onChange(input.urut)">
<option value="">Silahkan Pilih Urutan</option>
<option value="0">A-Z</option>
<option value="1">Z-A</option>
</select>
</label>
<div class="list">
<a ng-repeat="item in items | orderBy : 'album' : flag" href="#" class="item item-thumbnail-left">
<h2>{{ item.album }}</h2>
<h4>{{ item.artist }}</h4>
</a>
</div>
and add in your controller
$scope.flag = false;
$scope.onChange = function(urut){
if(urut == 0){
$scope.flag = false;
}else{
$scope.flag = true;
}
}
Updated Example

Related

I have three selects on my form. Each depends on the values of the previous one

I have three selects on my form.
Each depends on the values of the previous one.
I mean there is drop-down list with categories, car brand and car model.
The list with car brand must show the brands of chosen category. Also car model have consist of models of chosen brand.
The form HTML, the server language is PHP, I want to use Ajax JQUERY to get the value of the select.
Help please how it should be?
You should do something like this:
jQuery(function($) {
var brands = {
'Trucks': ['Ford', 'Chevrolet'],
'Cars': ['Honda', 'Volkzwagen'],
}
var models = {
'Ford': ['Model1', 'Model2'],
'Chevrolet': ['Model3', 'Model4'],
'Honda': ['Model5', 'Model6'],
'Volkzwagen': ['Model7', 'Model8'],
}
var $brands = $('#brand');
var $models = $('#model');
$('#category').change(function () {
var category = $(this).val(), brnds = brands[category] || [];
var html = $.map(brnds, function(brnd){
return '<option value="' + brnd + '">' + brnd + '</option>'
}).join('');
$brands.html('<option>Select</option>'+html)
$models.html('');
});
$('#brand').change(function () {
var brand = $(this).val(), mdls = models[brand] || [];
var html = $.map(mdls, function(mdl){
return '<option value="' + mdl + '">' + mdl + '</option>'
}).join('');
$models.html(html)
});
});
Check this JSFiddle: http://jsfiddle.net/minijavi19/2pza5/1908/
Of course if you want to use Ajax you should set your variables with it.
Thanks to everybody who paid attention to my question!!! But I want share with you with my solution. There ara 3 files: index.php, ajax-queries.js, php-funcs.php.
//index.php
$categories = $mysqli->query("SELECT category_id, category_name FROM
categories") or die($mysqli->error);
<form action="../../php/admin_funcs.php" method="post">
<select id="cat_slc" class="lists" name="category" >
<option disabled selected>Выберите категорию</option>
<?php
while ($crow = $categories->fetch_assoc())
{
echo "<option
value='".$crow['category_id']."'>".$crow['category_name']."
</option>";
}
?>
</select>
<select id="marka_slc" class="lists marka-select" name="marka" >
<option disabled selected>Выберите марку</option>
</select>
<select id="model_slc" class="lists model-select" name="mode">
<option disabled selected>Выберите модель</option>
</select>
</form>
//ajax-queries.js
$('#cat_slc').change(function () {
var cat_id = $(this).val();
var url = '../../php/data_functions.php';
$('#marka_slc').load(url + '#mark-block', {cat_id: cat_id}, function () {
$('.marka-select').fadeIn('slow');
});
});
$('#marka_slc').change(function(){
var mark_id = $(this).val();
var url = '../../php/data_functions.php';
$('#model_slc').load(url + '#model-block', {mark_id: mark_id}, function (){
$('.model-select').fadeIn('slow');
});
});
//php-funcs.php
<?php
require_once "db_connect.php";
function GetMarkas(){
global $mysqli;
$category_id = $_POST['cat_id'];
$query = "SELECT marka_id, marka_name FROM marka WHERE category_id =
'".$category_id."'";
$result = $mysqli->query($query);
$data = '';
while ($row = $result->fetch_assoc()){
$data .= "<option value='".$row['marka_id']."'>".$row['marka_name']."
</option>";
}
return $data;
}
function GetModels(){
global $mysqli;
$mark_id = $_POST['mark_id'];
$query = "SELECT model_id, model_name FROM model WHERE marka_id=
'".$mark_id."'";
$result = $mysqli->query($query);
$data = '';
while ($row = $result->fetch_assoc()){
$data .= "<option value='".$row['model_id']."'>".$row['model_name']."
</option>";
}
return $data;
}
if(isset($_POST['mark_id'])){
echo"<div id='model-block'>" . GetModels() . "</div>";
}
else if(isset($_POST['cat_id'])){
echo"<div id='mark-block'>" . GetMarkas() . "</div>";
}

Livesearch using php and ajax not working

I have a Ajax PHP MySQL live search that basically pulls out manufacturing items from a MySQL database and presents them in a drop-down list, as users enter they search term, one item per line, just like searching in Google.
What I need is a way to allow users to click on a particular link item, and for that to display data on the same page, just below the item(link) clicked.
Any help would be appreciated.
1.HTML form
<form class="navbar-form navbar-left" action="javascript:">
<div class="input-group">
<input type="text" class="form-control" id="searchbox1" name="q" token="<?=$csrf->token()?>" action='search1' placeholder="Search for Templates" autocomplete="off">
<div class="input-group-btn">
<button class="btn btn-default " id="searchbtn1" type="submit">
<i class="fa fa-search"></i></button>
</div>
</div>
<div id="livesearch1"></div>
</form>
2. AJAX Call seperate .js file
$('#searchbox1').on('keyup focus', function(e) {
var b = $(this).attr();
delete b.class, delete b.placeholder, delete b.id, delete b.name, delete b.type, delete b.autocomplete;
b.q = $(this).val();
if (b.q != '' && b.q.length > 0) {
$.ajax({
type: "POST",
url: api,
data: b,
cache: false,
success: function(a) {
$("#livesearch1").html(a);
$("#livesearch1").fadeIn();
}
});
} else {
$("#livesearch1").fadeOut();
}
});
$('#searchbox1').on('blur', function(e) {
$('#livesearch1').fadeOut();
});
3. api call
case 'search':
if($app->isAdmin() || $app->isEditor() || $app->isUser())
{
$app->escape('q');
ob_start();
ajaxsearch($q);
echo $result = ob_get_clean();
// json('success','true','results',$result);
}
break;
4. .php file
function ajaxsearch1($q){
$db = MysqliDb::getInstance();
$csrf = new Csrf_Protect();
$q = removeWhiteSpace($q);
$q = htmlspecialchars_decode($q,ENT_QUOTES);
$q = preg_replace('/[^a-zA-Z0-9.-. .).(]/', '', $q);
if(strlen($q) >0 )
{
$term = $q;
$searchterm = explode(' ',$term);
$searchColumns = array("name","slug");
$searchCondition = '';
for($i = 0; $i < count($searchColumns); $i++)
{
$searchFieldName = $searchColumns[$i];
$searchCondition .= "($searchFieldName LIKE '%" . implode("%' AND $searchFieldName LIKE '%", $searchterm) . "%')";
if($i+1 < count($searchColumns)) $searchCondition .= " OR ";
}
$res = $db->rawQuery("SELECT * FROM tbl_templates WHERE ($searchCondition) AND (version='1') order by id desc Limit 10 ");
foreach($res as $sr)
{ ?><li><?=ucfirst($sr['name'])?></li><?php
}
}
}
?>
This was a parameter issue.
data was not in the $q it was in the $name code should be something like this.
case 'search':
if($app->isAdmin() || $app->isEditor() || $app->isUser())
{
$app->escape('name');
ob_start();
ajaxsearch($name);
echo $result = ob_get_clean();
}
break;

Sendidng dynamic id and recieving data

I'm beginner at JS, AJAx, and so on. I was searching over the internet and found one code, so I used it, changed it a little... but it seems that it doesn't work (it does nothing).
First the javascript and html:
function fetch_select(val)
{
$.ajax({
type: 'post',
url: 'fetch_data.php',
data: {
get_option:val
},
success: function (response) {
document.getElementById("new_select").innerHTML=response;
}
});
}
<select onchange="fetch_select(this.value);">
<option>Wybierz</option>';
$zapytanie = "
SELECT
scan_category.scat_id,
scan_category.long_name
FROM
scan_category
WHERE
scan_category.state = 1 OR scan_category.state = 4 and scan_category.hide = 0
ORDER BY
scan_category.long_name";
$wykonaj = mysql_query($zapytanie) or die(mysql_error());
while($row=mysql_fetch_array($wykonaj))
{
echo '<option>'.$row[1].'</option>';
}
echo'</select>
<div id="new_select">
</div>';
$manga = $_POST['get_option'];
$znajdz = "
SELECT users.nick, scan_category.long_name, scan_work.work_name, scan_roles.role_id, scan_roles.scat_id, scan_roles.uid, scan_roles.what_id
FROM scan_roles
INNER JOIN scan_work ON scan_roles.what_id = scan_work.work_id
INNER JOIN users ON scan_roles.uid = users.uid
INNER JOIN scan_category ON scan_category.scat_id = scan_roles.scat_id
WHERE
scan_roles.scat_id = '$manga'";
$wykonaj = mysql_query($znajdz or die(mysql_error());
while ($row = mysql_fetch_array($znajdz)) {
echo '<h2>'.$row[1].
'</h2><br />'.$row[2].
':
<form enctype="multipart/form-data" action="manage.php5?mode=edit_role&edit&role_id="'.$row[4].
' method="POST">
<input type="hidden" name="pass" value="'.$_POST['pass'].
'">';
echo('<select name="user_id" size="1">');
$zapytanie = '
SELECT
users.uid,
users.nick
FROM
users
WHERE
active > 0
ORDER BY
users.nick';
$wykonaj2 = mysql_query($zapytanie) or die(mysql_error());
while ($wiersz = mysql_fetch_array($wykonaj)) {
echo('<option value="'.$wiersz[0].
'"');
if ($wiersz[0] == $row[6]) echo ' selected="selected"';
echo('>'.$wiersz[1].
'</option>');
}
echo '</select>';
echo('<input type="submit" value="edit">
</form>');
Do you have any idea how to make it work (it doesn't seem to be even going to the file "fetch_data.php).
If I should add something else, tell me, I'm pretty much beginner!
When i put console.log(response) it does say ReferenceError: response is not defined, when i puted it like this - console.log("response") it gives me "response".

Ajax sort using two compounded dropdowns

Currently, I am using a nav menu to display the categories of items, using Ajax to sort/limit items shown to the chosen category, and using lazyload to display additional items on scroll.
I am wanting to change the nav menu to two button dropdowns – one for categories, and the other for locations. I would like the user to be able to sort by category OR store, independently, or by category AND store, in conjunction.
Scenario:
User chooses Category A
Category A items for ALL locations are shown
User then chooses Location A
Category A items for Location A are shown
User then chooses Location B
Category A items for Location B are shown
User then chooses Category B
– Category B items for Location B are shown
I am hoping that this can be usable in reverse order as well, i.e. if the user chooses location first, and then category.
I am knee-deep in code - aren't we all! ;) - and think I need another pair of eyes to slap me back straight! Where am I going wrong?!? TIA for the help.
FYI, currently when I select the category, it works fine. When I then select a location, it just shows that location's items within the last category, regardless of the category previously chosen, and then when I scroll, lazyload begins displaying items from all locations and all categories. If I choose the location first, it shows that location's items from the last category. Any help is much appreciated.
Here are the buttons: (include-menu)
<div class="btn-group">
<button class="btn btn-default btn-lg dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Choose Category <span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li'; if (!$_REQUEST || $_REQUEST['show']) { echo ' class="active"'; } echo '><a class="pawn-sort" href="?show=all">Show All</a></li>'."\n";
$result = $site->query("SELECT * FROM CATEGORIES ORDER BY NAME ASC");
while ($data = $result->fetch_array())
{
$category_id = $data['ID'];
$cats = $site->query("SELECT * FROM PRODUCTS WHERE CATEGORIES LIKE '%$category_id%'");
if ($cat = $cats->fetch_array())
{
echo '<li'; if ($category_id == $_REQUEST['category']) { echo ' class="active"'; } echo '>
' . ucwords($data['NAME']) . '
<!-- <a data-index="' . $category_id . '" name="cat" href="#">' . ucwords($data['NAME']) . '</a> -->
</li>'."\n";
}
}
echo '</ul>
</div>
<div class="btn-group">
<button class="btn btn-default btn-lg dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Choose Store <span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li>Show All</li>
<li class="divider"></li>
<li>location1</li>
<li>location2</li>
<li>location3</li>
<li>location4</li>
<li>location5</li>
<li>location6</li>
<li>location7</li>
</ul>
</div>
Here is where ajax gets the items and displays them: (ajax-get-items)
define('ITEMS_PER_PAGE',8);
$category = $_GET['category'] ? $_GET['category'] : null;
$kingdom = $_GET['kingdom'] ? $_GET['kingdom'] : null;
if ($kingdom)
{
$this_store = " AND STORE = '$kingdom'";
} else {
$this_store = '';
}
$page = $_GET['page'] ? ($_GET['page']) : 1;
if($page < 1)
{
$page = 1;
}
$first = $_GET['first'] ? ($_GET['first']) : 0;
$next = $page + 1;
$start = ($page - 1 ) * ITEMS_PER_PAGE;
$offset = ITEMS_PER_PAGE;
if ($category) {
$que = "SELECT * FROM PRODUCTS WHERE QUANTITY != '0' AND STATUS = '1' AND CATEGORIES LIKE '%$category%' $this_store ORDER BY DATE DESC LIMIT $start, $offset";
$queAll = "SELECT * FROM PRODUCTS WHERE QUANTITY != '0' AND STATUS = '1' AND CATEGORIES LIKE '%$category%' $this_store ORDER BY DATE DESC";
} else {
$que = "SELECT * FROM PRODUCTS WHERE QUANTITY != '0' AND STATUS = '1' $this_store ORDER BY DATE DESC LIMIT $start, $offset";
$queAll = "SELECT * FROM PRODUCTS WHERE QUANTITY != '0' AND STATUS = '1' $this_store ORDER BY DATE DESC";
}
// COUNT HOW MANY ITEMS AVAILABLE
$resultsAll = $site->query("$queAll");
$countAll = count($resultsAll->fetch_assoc());
// MAIN QUERY
$results = $site->query("$que");
$output = "";
$counter = 0;
while ($cupon = $results->fetch_array()) {
$name = $cupon['NAME'];
$price = $cupon['PRICE'];
$store = $cupon['STORE'];
$sku = $cupon['SKU'];
$upc = $cupon['UPC'];
$img_id = $cupon['IMAGE_ID'];
$notify = $cupon['NOTIFY'];
$store_sku = $cupon['STORE_SKU'];
$out = "&out=true";
$img = "img/l/{$img_id}_1.jpg";
$output .= '<div class="pin">
<div id="pin_' . $counter . '">
<div class="thumbnail" style="overflow: hidden;">
<ul class="img-list">
<li>
<a href="/buy.php?sku=' . $sku . '">
<img class="radius" src="/' . $img . '">
<span class="text-content"><span>View Product Info</span></span></a>
</li>
</ul>
<div class="caption pinkish" style="margin-top:-9px;">
<h4 class="pin-title">' . $name . '</h4>
<hr style="margin-bottom:5px;">' . "\n";
$kingdoms = $castle->query("SELECT NAME, CITY, STATE FROM KINGDOMS WHERE ID = '$store' LIMIT 1");
$kingdom = $kingdoms->fetch_array();
$output .= '#' . $store_sku . '
<span class="glyphicon glyphicon-map-marker"></span> ' . $kingdom['CITY'] . '
<hr style="margin-top:5px;margin-bottom:3px;">
<p class="pin-price">
<a href="/buy.php?sku=' . $sku . '" class="btn btn-info btn-sm pull-right btn-green" style="margin-top:3px;" role="button">
<span class="glyphicon glyphicon-search small"></span> More info
</a>
<span class="price">$' . number_format($price, 2) . '</span>
<div class="clearfix"></div>
</div>
</div>
</div>
</div>' . "\n";
$counter++;
}
$output.= '<script type="text/javascript">
var container = document.querySelector(\'#container\');
var msnry;
// initialize Masonry after all images have loaded
imagesLoaded( container, function() {
msnry = new Masonry( container, {
// options
itemSelector: \'.pin\'
});
});
</script>';
if($category)
{
if(((($page -1) * ITEMS_PER_PAGE + $counter)< $countAll) )
{
$output.= '<div id="page-nav"></div>';
} else {
$output.= "<script>$('#container').infinitescroll('unbind', {debug: true});</script>";
}
} else {
if(((($page -1) * ITEMS_PER_PAGE + $counter)< $countAll) )
{
$output.= '<div id="page-nav"></div>';
} else {
$output.= "<script>$('#container').infinitescroll('unbind', {debug: true});</script>";
}
}
echo $output;
Here is the jquery:
<script>
$('.filter').on('click',function(){
var filterValue = $(this).attr('data-filter');
$('#alist').isotope({filter: filterValue});
})
var $container = $('#container');
function customMasonry(newElements)
{
// hide new items while they are loading
var $newElems = $( newElements ).css({ opacity: 0 });
// ensure that images load before adding to masonry layout
$newElems.imagesLoaded(function(){
// show elems now they're ready
$newElems.animate({ opacity: 1 });
var msnry;
// initialize Masonry after all images have loaded
imagesLoaded( $container, function() {
msnry = new Masonry( container, {
// options
itemSelector: '.pin'
});
});
});
}
function customScroll()
{
$container.infinitescroll({
navSelector : '#page-nav', // selector for the paged navigation
debug: false,
animate : false,
errorCallback : function() {
$container.infinitescroll('destroy');
$.removeData(this);
},
nextSelector : '#page-nav:first a:first', // selector for the NEXT link (to page 2)
itemSelector : '.pin', // selector for all items you'll retrieve
loading: {
finishedMsg: '',
img: 'loading.gif',
msgText: ''
}
},
// trigger Masonry as a callback
function( newElements ) {
customMasonry(newElements)
}
);
}
$(function(){
var isMobile = window.matchMedia("only screen and (min-width: 760px)");
if (isMobile.matches) {
$("#categories").sticky({topSpacing: 70});
}
customScroll();
$('.pawn-sort').click(function(event){
$('#container').html('');
$('#container').infinitescroll('bind');
$('html, body').animate({
scrollTop: $("#container").offset().top -369
}, 0);
$url = $(this).attr('href');
var res = $url.split("&");
var cat = res[0].split("=");
var $category = cat[1];
var king = res[1].split("=");
var $kingdom = king[1];
if($category == 'all' )
{
$category = null;
}
if($kingdom == 'all' )
{
$kingdom = null;
}
$('#container').css({height:500});
$.ajax({
method: "GET",
url: "ajax-get-items.php",
data: { page: "1", category: $category, kingdom: $kingdom, first: true }
})
.done(function( msg ) {
$('#container').html("<div id='gif'><img src='loading.gif'/></div>");
setTimeout(
function()
{
$('#container').html(msg);
// Reset the plugin before intializing it again
$('#container').infinitescroll('destroy');
$('#container').data('infinitescroll', null);
// Initialize plugin
$('#container').infinitescroll(
{
state: {
isDestroyed: false,
isDone: false,
isDuringAjax : false
}
}
);
customScroll();
}, 500);
});
event.preventDefault();
})
});
</script>

Ajax concatenate select and total record query

I've a php page where there is a ajax concatenate select and a div with the total number of records in the table tb1
HTML
<p>
<select name="model" id="model">
<?php echo $myclass->selModel(); ?>
</select>
</p>
<br />
<p>
<select name="year" id="year">
<option value=""> </option>
</select>
</p>
<p>
<div id="total"><?php echo $myclass->recordNum();?></div>
</p>
JS
// VARS
var wait = '<option>Waiting</option>';
var select = '<option value="">Select</option>';
// CAT_1 //
$("select#model").change(function(){
var model = $("select#model option:selected").prop("value");
$("select#year").html(wait);
$.post("ajax-php/select-concat.php", {model:model}, function(data){
switch (data) {
case select:
$("select#year").html("");
return false;
default:
$("select#year").prop("disabled", false);
$("select#year").html(data);
return false;
}
});
});
PHP - select-concat.php
if(isset($_POST['model']))
{
echo $myclass->selYear();
die;
}
MY PHP CLASS
public function selYear() {
$result = $this->db->mysqli->query
("SELECT year FROM tb1 WHERE model='$_POST[model]");
$year = '<option value="">Select</option>';
while($row = $result->fetch_assoc()) {
$year .= '<option value="' . $row['year'] . '"';
$year .= '>' . $row['year'] . '</option>';
}
return $year;
}
private function recordNum(){
$result = $this->db->mysqli->query
("SELECT * FROM tb1 WHERE something ");
$numrec = $result->num_rows;
return $numrec;
}
My goal is to update the number of records with ajax every time I run a concatenate select. How could I do that? Thanks
You should use json_encode() on select-concat.php to return two results.
if(isset($_POST['model']))
{
$years = $myclass->selYear();
$total = $myclass->recordNum();
$arr = array('years' => $years, 'total' => $total);
echo json_encode($arr);
die;
}
You must add POST model value to recordNum() function (or pass it with an argument).
Then...
$("select#model").change(function(){
var model = $("select#model option:selected").prop("value");
$("select#year").html(wait);
$.post("ajax-php/select-concat.php", {model:model}, function(data){
var json_data = $.parseJSON(data);
switch (data) {
case select:
$("select#year").html("");
$("#total").html(0);
return false;
default:
$("select#year").prop("disabled", false);
$("select#year").html(json_data.years);
$("#total").html(json_data.total);
return false;
}
});
});

Categories