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;
Related
I have a timetable on my website. The user can select multiple times. The selected time is inserted into the database and the button turns from green to red, so the user know it's disabled.
I want to do this with only a reload of div.
It does work but it work only once, when pushing the button for the second time the div doesn't refresh / reload.
Update database / refresh;
$('.updateTime').click(function(){
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = window.location.search.substring(1),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
}
}
};
var uniqueId = $(this).attr('id');
var sdate = getUrlParameter('date');
$.ajax({
url: './ajax/reservation_insert_times.php',
type: 'POST',
data: {
uniqueId :uniqueId, sdate :sdate
},
success: function(mydiv){
$("#result").load(location.href+ ' #mydiv');
}
});
});
The code for generating the times
<div class="row" id="result">
<?
$result = array();
$query = $db->query("SELECT * FROM reservation_times WHERE datum = '" . db_escape($_GET['date']) . "' ");
while($row = mysqli_fetch_array($query)) {
$result[] = $row['time'];
}
?>
<?
$timestamp = strtotime(date("Y-m-d")." 12:00");
for ($i=0;$i<=32;$i++) {
$time = date('H:i', $timestamp);
$time .= ' UUR';
if (in_array($time, $result)) {
$color = "background-color:red !important";
}
else $color = "";
$timestamp += 15 * 60;
if (isset($checked) && $checked !='') { $color = 'background-color: red;';}?>
<div class="col-xs-4 col-md-3 col-lg-2" id="mydiv">
<button type="button" id="<?=$time;?>" class="btn btn-block btn-success btn-sm text-center" style="padding:10px; margin-bottom:10px; <?=$color;?>" onclick="" <? if (isset($checked) && $checked !='') { echo 'disabled';}?>>
<?=$time;?>
</button>
</div>
<? } ?>
</div>
The code for the reservation_availablity.php call:
$query = $db->query("SELECT * FROM reservation_times WHERE time = '".$uniqueId."'");
if(mysqli_num_rows($query) == 1) {
$remove = $db->query("DELETE FROM reservation_times WHERE time = '".$uniqueId."'");
} else {
if (isset($uniqueId) && $uniqueId !='') :
$sql = $db->query("INSERT INTO reservation_times (time, datum)
VALUES ('".$uniqueId."', '".$newDate."')");
endif;
}
Change you success method of your ajax:
$.ajax({
url: './ajax/reservation_insert_times.php',
type: 'POST',
data: {
uniqueId :uniqueId, sdate :sdate
},
success: function(mydiv){
$("#result").html(mydiv);
}
});
You are sending an ajax to get new content but then in success method instead of loading new content received as ajax response you are again loading the content of the same div. That's why it is working for the first time but will remain unchanged next time onwards.
//Wrong
$("#result").load(location.href+ ' #mydiv');
// Correct
$("#result").html(mydiv);
So, now whenever this ajax send to the server, it will update the content of div#result. And to allow user to manually refresh the content of this div as and when desired then you will have to call this ajax upon click of a button labled as Refresh Timetable.
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".
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
I have see the example about search box using JQuery and mysql, But the view more function no work. how to improve the program. When i click the view more i can see the next 10 record. Thanks
<script type="text/javascript">
$(document).ready(function()
{
$("#keywords").keyup(function()
{
var kw = $("#keywords").val();
if(kw != '')
{
$.ajax
({
type: "POST",
url: "search.php",
data: "kw="+ kw,
success: function(option)
{
$("#results").html(option);
}
});
}
else
{
$("#results").html("");
}
return false;
});
$(".overlay").click(function()
{
$(".overlay").css('display','none');
$("#results").css('display','none');
});
$("#keywords").focus(function()
{
$(".overlay").css('display','block');
$("#results").css('display','block');
});
});
</script>
<div id="inputbox">
<input type="text" id="keywords" name="keywords" value="" placeholder="Type Your Query..."/>
</div>
</div>
<div id="results"></div>
<div class="overlay"></div>
we extract the value of that key and send it to the search.php
<?php
include('db.php');
//file which contains the database details.
?>
<?php
if(isset($_POST['kw']) && $_POST['kw'] != '')
{
$kws = $_POST['kw'];
$kws = mysql_real_escape_string($kws);
$query = "select * from wp_posts where post_name like '%".$kws."%' and (post_type='post' and post_status='publish') limit 10" ;
$res = mysql_query($query);
$count = mysql_num_rows($res);
$i = 0;
if($count > 0)
{
echo "<ul>";
while($row = mysql_fetch_array($res))
{
echo "<a href='$row[guid]'><li>";
echo "<div id='rest'>";
echo $row['post_name'];
echo "<br />";
echo "<div id='auth_dat'>".$row['post_date']."</div>";
echo "</div>";
echo "<div style='clear:both;'></div></li></a>";
$i++;
if($i == 5) break;
}
echo "</ul>";
if($count > 5)
{
echo "<div id='view_more'><a href='#'>View more results</a></div>";
}
}
else
{
echo "<div id='no_result'>No result found !</div>";
}
}
?>
press the view more result will not show more result.
If I'm not mistaken, you want to bring next 10 with ajax ?
This situation behaves as a pagination,
You have to store the current click count in javascript . WÄ°thout clicking more button, the variable of clickCount is 0, when you click more ,then your variable clickCount=1 ,
while sending ajax , send clickCount to the php.
$.ajax
({
type: "POST",
url: "search.php",
data: "kw="+ kw+"&clickCount="+clickCount,
success: function(option)
{
$("#results").html(option);
}
});
You can query with limit&offset (clickCount )*10, itemCountForEachMoreClick = limit 0,10
when click more
limit 10,10
when click one more
limit 20,10. Do not forget to reset clickCount on keyPress !
php Side
$count = isset($_REQUEST["clickCount"])? $_REQUEST["clickCount"]:0;
$limitAndOffset = $count*10.",10";
$query = "select * from wp_posts where post_name like '%".$kws."%'
and (post_type='post' and post_status='publish') limit ".$limitAndOffset ;
I have an issue with JQuery and Ajax. Sometimes my code works just fine, sometimes it just will not. Other times I need to press a down arrow once in order to make the up arrows work, which is strange enough...
In IE or in Firefox, the lack of response happens more rarely than it does in Chrome.
The website in question is here:
http://www.dungeoncrawler.com/kickstarter_2013/calculator/
If you need to login, try:
ID: webmaster#geoste.ca
Pass: 123456789
Here is an example of my code:
Javascript JQuery function : first either chnQuantUp or chnQuantDn is called, and then the data gets passed to doCrtUpd which does the actual JQuery call.
function doCrtUpd(crtID,itmAmt,itmStrID)
{
// Call AJAX to update cart quantities
if (crtID)
{
$.ajax({
type: 'POST',
url: 'inc-kspldgman.php',
data: {cartordrnum: crtID,itmamt: itmAmt,storeitmkey: itmStrID, doaction: "UPDITM"},
async: true,
success: function (d)
{
reLoadDivs();
},
error: function (d)
{
alert(d);
}
});
}
}
function chnQuantUp(frmEle,frmEleID,crtID,itmStrID)
{
tmpvar2 = frmEle + frmEleID;
tmpvar1 = eval("document.frmStrItms."+ tmpvar2 +".value");
if (isNaN(tmpvar1))
{
tmpvar1 = 1;
}
else
{
tmpvar1 = parseInt(tmpvar1);
tmpvar1++;
}
eval("document.frmStrItms."+ tmpvar2 +".value = " + tmpvar1);
doCrtUpd(crtID,tmpvar1,itmStrID);
}
function chnQuantDn(frmEle,frmEleID,crtID,itmStrID)
{
tmpvar2 = frmEle + frmEleID;
tmpvar1 = eval("document.frmStrItms."+ tmpvar2 +".value");
if (isNaN(tmpvar1))
{
tmpvar1 = 0;
}
else
{
tmpvar1 = parseInt(tmpvar1);
}
tmpvar1--;
if (tmpvar1 < 0)
{
tmpvar1 = 0;
}
eval("document.frmStrItms."+ tmpvar2 +".value = " + tmpvar1);
doCrtUpd(crtID,tmpvar1,itmStrID);
}
Example of my HTML, one of the store items:
<div name="frmEle14" id="frmEle14" class="item" style=" background-image: url(./gallery/calc_ID_84.png);">
<div class="item_name">GREENKNEE, PPM</div>
<div class="item_count_5">
<div align="center">
<img src="images/calc_arrow_up_lw.jpg" border="0" class="arrow_btn1" /><br />
<input type="text" name="frmeleamt14" id="frmeleamt14" class="count_box" value="0" size="3" maxlength="3" onkeyup="javascript:doManChng('0',document.frmStrItms.frmeleamt14.value,'38','frmeleamt14');" /><br />
<input type="hidden" name="frmelesku14" id="frmelesku14" value="GVN-DCM-0005-CHAMP-PPM" />
<input type="hidden" name="frmelesalecode14" id="frmelesalecode14" value="NONE" />
<input type="hidden" name="frmeleitmkey14" id="frmeleitmkey14" value="38" />
<input type="hidden" name="frmgvnlinekey14" id="frmgvnlinekey14" value="0" />
<img src="images/calc_arrow_down_lw.jpg" border="0" class="arrow_btn2" />
<input type="hidden" name="frmelepicnme14" id="frmelepicnme14" value="calc_ID_84.png" />
</div>
</div>
<div class="item_price">$3.00</div>
</div>
And the PHP code that handles the actual addition to the database:
if ($cartordrnum)
{
// Start UPDATE
if ($doaction == "UPDITM")
{
$rspns = "";
// Get store item's data that we need, such as price per unit
$sql = "SELECT item_unitprice,salecode FROM store_items WHERE itemkey = ".$storeitmkey.";";
$getitmdata1 = mysqli_query($conn,$sql);
$getitmdata = mysqli_fetch_array($getitmdata1);
$itemunitprice = $getitmdata['item_unitprice'];
settype($itemunitprice,"float");
$salecode = $getitmdata['salecode'];
settype($salecode,"string");
$getitmdata = null;
$getitmdata1 = null;
// Do new item total if it has not already been calculated via salecode
if ($itmttl == 0)
{
$itmttl = ($itmamt * $itemunitprice);
}
$gvnlinekey = 0;
$dbitmamt = 0;
$sql = "SELECT lineitmkey, linequant FROM gvn_lineitems WHERE storeitmkey = ".$storeitmkey." AND code_note IS NULL ORDER BY lineitmkey DESC LIMIT 0,1;";
$chklineitm1 = mysqli_query($conn,$sql);
if (mysqli_num_rows($chklineitm1))
{
$chklineitm = mysqli_fetch_array($chklineitm1);
$gvnlinekey = $chklineitm['lineitmkey'];
settype($gvnlinekey,"integer");
$dbitmamt = $chklineitm['linequant'];
settype($dbitmamt,"integer");
}
$chklineitm = null;
if ($gvnlinekey)
{
if ($itmamt)
{
// Check if amounts have changed.
if ($dbitmamt != $itmamt)
{
// We have a change, so do an update.
// Do DB update
$sql = "UPDATE gvn_lineitems SET linequant = ".$itmamt.", linesubttl = ".$itmttl.", linettl = ".$itmttl." WHERE lineitmkey = ".$gvnlinekey.";";
if (mysqli_query($conn,$sql))
{
$rspns = "UPDATED";
}
}
}
else
{
// Delete the lineitem because it has a zero or negative amount
$sql = "DELETE FROM gvn_lineitems WHERE lineitmkey = ".$gvnlinekey." AND code_note IS NULL;";
if (!mysqli_query($conn,$sql))
{
$rspns = "DELETED1";
}
}
}
else
{
// Insert new line item
if ($itmamt > 0)
{
$sql = "INSERT INTO gvn_lineitems (ordrnumkey,storeitmkey,linequant,linesubttl,linettl) VALUES (".$cartordrnum.",".$storeitmkey.",".$itmamt.",".$itmttl.",".$itmttl.");";
if (mysqli_query($conn,$sql))
{
$rspns = "ADDED";
}
}
else
{
// Delete the lineitem because it has a zero or negative amount
$sql = "DELETE FROM gvn_lineitems WHERE storeitmkey = ".$storeitmkey." AND code_note IS NULL;";
if(mysqli_query($conn,$sql))
{
$rspns = "DELETED2";
}
}
}
$chklineitm1 = null;
//echo $rspns;
}