Select option table data search in laravel - javascript

I already show data from database in a table. Then made a condition if product stock=0 then show some html 'out of stock' and else show product quantity. Now I want to search by option In Stock And out stock. When click In stock then I want to see all in stock product in the table and same function use in Out of stock.
here is my controller
public function all_products(Request $request)
{
// $categories = Category::all();
$col_name = null;
$query = null;
$seller_id = null;
$sort_search = null;
$products = Product::orderBy('created_at', 'desc')->where('auction_product',0);
if ($request->has('user_id') && $request->user_id != null) {
$products = $products->where('user_id', $request->user_id);
$seller_id = $request->user_id;
}
if ($request->search != null){
$searchString = $request->search;
$products = $products
->where('name', 'like', '%'.$request->search.'%')
->orWhere('barcode', 'like', '%'.$request->search.'%')
->orWhereHas('stocks', function ($query) use ($searchString) {
$query->where('sku', 'like', $searchString.'%');
});
$sort_search = $request->search;
}
if ($request->type != null){
$var = explode(",", $request->type);
$col_name = $var[0];
$query = $var[1];
$products = $products->orderBy($col_name, $query);
$sort_type = $request->type;
}
$products = $products->paginate(50);
$type = 'All';
return view('backend.product.products.index', compact('products','type', 'col_name', 'query', 'seller_id', 'sort_search'));
}
and here is my blade page
<div class="col-md-2 ml-auto">
<select class="form-control form-control-sm aiz-selectpicker mb-2 mb-md-0" name="type" id="type" onchange="sort_products()">
<option value="">{{ translate('Sort By') }}</option>
<option value="num_of_sale,desc"#isset($col_name , $query) #if($col_name == 'num_of_sale' && $query == 'desc') selected #endif #endisset>{{translate('In Stock')}}</option>
<option value="status,asc"#isset($col_name , $query) #if($col_name == 'status' && $query == 'asc') selected #endif #endisset>{{translate('Out Of Stock')}}</option>
</select>
</div>

Related

How can I print "not found" when the code output is empty?

I mixed an "ajax select" and "while scrolling load data" script, and this is working, but I don't know how to print "not found data" in div.status when the output variable (on animals.php) is empty.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Animals</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
<div class="search">
<div class="filter category">
<select name="category" id="category">
<option value="">All</option>
<option value="free">Free</option>
<option value="lost">Lost</option>
<option value="found">Found</option>
</select>
</div>
<div class="filter chipnumber">
<input type="text" name="chipnumber" id="chipnumber"></div>
</div>
<div class="send">
<button type="submit" id="submit">Search</button>
</div>
</div>
<script>
$(document).ready(function() {
var animal_limit = 6;
var animal_start = 0;
var animal_action = 'inactive';
function load_animal_data() {
var category = $('#category').val();
var chipnumber = $('#chipnumber').val();
$.ajax({
url: "animals.php",
method: "POST",
data: {animal_limit:animal_limit, animal_start:animal_start, animal_action:animal_action, category:category, chipnumber:chipnumber},
success:function(data) {
$('div.animals').append(data);
if (data == '') {
animal_action = 'active';
} else {
animal_action = 'inactive';
}
}
});
}
load_animal_data();
function search() {
var category = $('#category').val();
var chipnumber = $('#chipnumber').val();
animal_start = 0;
load_animal_data();
}
$('#search').on('click', function() {
search();
});
$(window).scroll(function () {
if ($(window).scrollTop() + $(window).height() > $('div.animals').height() && animal_action == 'inactive') {
animal_action = 'active';
animal_start = animal_start + animal_limit;
setTimeout(function() {
load_animal_data();
}, 1000);
}
});
});
</script>
<div class="animals"></div>
<div class="status"></div>
</body>
</html>
animals.php
<?php
$connect = mysqli_connect("localhost", "root", "", "petsdata");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_set_charset($connect,"utf8");
$output = '';
$animal_start = $connect->real_escape_string($_POST["animal_start"]);
$animal_limit = $connect->real_escape_string($_POST["animal_limit"]);
$category = $connect->real_escape_string($_POST["category"]);
$chipnumber = $connect->real_escape_string($_POST["chipnumber"]);
if (isset($animal_start, $animal_limit, $category, $chipnumber)) {
if (!empty($category) && !empty($chipnumber)) {
$query = mysqli_query($connect, "SELECT * FROM animals WHERE chipnumber LIKE '%".$chipnumber."%' AND category = '".$category."' ORDER BY id LIMIT ".$animal_start.", ".$animal_limit."");
}
else if (!empty($category)) {
$query = mysqli_query($connect, "SELECT * FROM animals WHERE category = '".$category."' ORDER BY id LIMIT ".$animal_start.", ".$animal_limit."");
}
else if (!empty($chipnumber)) {
$query = mysqli_query($connect, "SELECT * FROM animals WHERE chipnumber LIKE '%".$chipnumber."%' AND status = '1' ORDER BY id DESC LIMIT ".$animal_start.", ".$animal_limit."");
}
else {
$query = mysqli_query($connect, "SELECT * FROM animals ORDER BY id DESC LIMIT ".$animal_start.", ".$animal_limit."");
}
while ($row = mysqli_fetch_array($query)) {
$output .= '<div class="animal">';
$output .= '<span>Category: ' . $row["category"] . '</span>';
$output .= '<span>Chipnumber: ' . $row["chipnumber"] . '</span>';
$output .= '</div>';
}
}
echo $output;
?>
if($query->num_rows > 0){
//Proceed as normally
}else{
$output = 'No data Found';
}

Next Line Javascript

What in my code is causing the code printed to be on the next line?
function GetSelected (selectTag) {
var selIndexes = "";
for (var i = 0; i < selectTag.options.length; i++) {
var optionTag = selectTag.options[i];
if (optionTag.selected) {
if (selIndexes.length > 0)
selIndexes += "";
selIndexes = optionTag.value;
}
}
var info = document.getElementById ("info");
if (selIndexes.length > 0) {
info.innerHTML = selIndexes;
}
else {
info.innerHTML = "There is no selected option";
}
}
Here's one of the option in the combobox:
<select option="single" name= "viocat" id="viocat" onchange="GetSelected (this);" class = "form-control">
<option>Choose category ...</option>
<option value="<?php
$con = mysqli_connect("///") or die (mysql_error());
$sql = mysqli_query ($con, "SELECT violationcategory, MAX(code) AS highest_id FROM tbl_violation where violationcategory = '\r\n DL'");
$sql = "SELECT violationcategory, MAX(code) AS highest_id FROM tbl_violation where violationcategory = '\r\n OR'";
$result = mysql_query ($sql,$con);
while($row = mysql_fetch_array($result)){
$i = $row['highest_id'];
$i++;
echo "OR - " .$i;
}
?> "> Driver's License Related</option>
</select>
Here's where to be displayed:
<label type= "text" id="info" name="viocode" class = "form-control">
I'm not quite sure exactly what you mean by next line but, from part of the question that you deleted, I think it is because you start your PHP block on a new line.
Instead of:
<option>Choose category ...</option>
<option value="
<?php
Try:
<option>Choose category ...</option>
<option value="<?php

Javascript/ajax not sending empty fields to php

I am a beginner in programming and i have a java script function that sends the variables of a form to a php script.
In the form i have two tables that hold two dropdowns each.
I can click the plus button to clone the first table row and i can click delete to remove the clones.
The max amount that can be generated is limited to 3 for nativelang and to 6 for practlang.
I have set all the variables that can be generated in the php and the javascript already and if i generate the max amount then it all works fine.
But if i don't generate any or just a few then the ajax.send is not doing anything, actually the form button stops working.
I suspect it is because of the expected data from the already declared variables that are empty because i didn't generate the drop downs.
This is the code that might cause the problem:
ajax.send("u="+u+"&e="+e+"&p="+p1+"&c="+c+"&g="+g+"&ct="+ct+"&nl="+nl+"&nll="+nll+"&nl0="+nl0+"&nll0="+nll0+"&nl1="+nl1+"&nll1="+nll1+"&nl2="+nl2+"&nll2="+nll2+"&pl="+pl+"&pll="+pll+"&pl0="+pl0+"&pll0="+pll0+"&pl1="+pl1+"&pll1="+pll1+"&pl2="+pl2+"&pll2="+pll2+"&pl3="+pl3+"&pll3="+pll3+"&pl4="+pl4+"&pll4="+pll4);
and this error is returned:
Uncaught TypeError: Cannot read property 'value' of nullsignup.php:954 signupsignup.php:893 onclick
How can i make it send the field even if its empty? or is it the php code?
I assumed the php would just save the fields that hold data and if a variable has no data then it is just saved as empty into the database right?
So thats why i thought it must be the javascript.
Would be super great if someone could help me to make this work :)
Sign up script:
function signup(){
var u = _("username").value;
var e = _("email").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var c = _("country").value;
var g = _("gender").value;
var ct = _("city").value;
var nl = _("nativelang").value;
var nll = _("nlanglevel").value;
var nl0 = _("nativelang0").value;
var nll0 = _("nlanglevel0").value;
var nl1 = _("nativelang1").value;
var nll1 = _("nlanglevel1").value;
var nl2 = _("nativelang2").value;
var nll2 = _("nlanglevel2").value;
var pl = _("practlang").value;
var pll = _("planglevel").value;
var pl0 = _("practlang0").value;
var pll0 = _("planglevel0").value;
var pl1 = _("practlang1").value;
var pll1 = _("planglevel1").value;
var pl2 = _("practlang2").value;
var pll2 = _("planglevel2").value;
var pl3 = _("practlang3").value;
var pll3 = _("planglevel3").value;
var pl4 = _("practlang4").value;
var pll4 = _("planglevel4").value;
var status = _("status");
if(u == "" || e == "" || p1 == "" || p2 == "" || c == "" || g == "" || ct == "" || nl == "" || pl == ""){
status.innerHTML = "Fill out all of the form fields marked with a star";
} else if(p1 != p2){
status.innerHTML = "Your passwords do not match";
} else {
_("signupbtn").style.display = "none";
status.innerHTML = 'Email has been sent!';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText.trim()!= "signup_success"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "<div id=\"status\">OK "+u+", <h2>check your email</h2> inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully <h2>activate your account!</h2></div>";
}
}
}
ajax.send("u="+u+"&e="+e+"&p="+p1+"&c="+c+"&g="+g+"&ct="+ct+"&nl="+nl+"&nll="+nll+"&nl0="+nl0+"&nll0="+nll0+"&nl1="+nl1+"&nll1="+nll1+"&nl2="+nl2+"&nll2="+nll2+"&pl="+pl+"&pll="+pll+"&pl0="+pl0+"&pll0="+pll0+"&pl1="+pl1+"&pll1="+pll1+"&pl2="+pl2+"&pll2="+pll2+"&pl3="+pl3+"&pll3="+pll3+"&pl4="+pl4+"&pll4="+pll4);
}
}
Script for the buttons that add or delete rows in the table(table holds dropdowns):
var ncount = -1;
$(document).ready(function(){
$('#addBtnNative').on('click', function(e){
if($('.nativelangdrop').length < 4) {
ncount++;
var initialn_row = $('tr.initialn').first().clone();
var nativelang_name = initialn_row.find('td:eq(0) select').attr('name'); // first td select
var nlanglevel_name = initialn_row.find('td:eq(1) select').attr('name'); // second td select
initialn_row.find('td:eq(0) select').attr('name', nativelang_name + ncount);
initialn_row.find('td:eq(1) select').attr('name', nlanglevel_name + ncount);
var nativelang_id = initialn_row.find('td:eq(0) select').attr('id'); // first td select
var nlanglevel_id = initialn_row.find('td:eq(1) select').attr('id'); // second td select
initialn_row.find('td:eq(0) select').attr('id', nativelang_id + ncount);
initialn_row.find('td:eq(1) select').attr('id', nlanglevel_id + ncount);
$('table.nativelanguages').append(initialn_row);
}
});
});
$(document).ready(function(){
$('#remBtnNative').on('click', function(e){
if($('.nativelangdrop').length > 1) {
ncount--;
var initialn_row = $('tr.initialn').last().remove();
}
});
});
var pcount = -1;
$(document).ready(function(){
$('#addBtnPract').on('click', function(e){
if($('.practlangdrop').length < 6) {
pcount++;
var initialp_row = $('tr.initialp').first().clone();
var practlang_name = initialp_row.find('td:eq(0) select').attr('name'); // first td select
var planglevel_name = initialp_row.find('td:eq(1) select').attr('name'); // second td select
initialp_row.find('td:eq(0) select').attr('name', practlang_name + pcount);
initialp_row.find('td:eq(1) select').attr('name', planglevel_name + pcount);
var practlang_id = initialp_row.find('td:eq(0) select').attr('id'); // first td select
var planglevel_id = initialp_row.find('td:eq(1) select').attr('id'); // second td select
initialp_row.find('td:eq(0) select').attr('id', practlang_id + pcount);
initialp_row.find('td:eq(1) select').attr('id', planglevel_id + pcount);
$('table.practlanguages').append(initialp_row);
}
});
});
$(document).ready(function(){
$('#remBtnPract').on('click', function(e){
if($('.practlangdrop').length > 1) {
pcount--;
var initialp_row = $('tr.initialp').last().remove();
}
});
});
PHP:
if(isset($_POST["u"])){
include_once("php_includes/db_conx.php");
$u = preg_replace('#[^a-z0-9]#i', '', $_POST['u']);
$e = mysqli_real_escape_string($db_conx, $_POST['e']);
$p = $_POST['p'];
$g = preg_replace('#[^a-z]#', '', $_POST['g']);
$c = preg_replace('#[^a-z ]#i', '', $_POST['c']);
$ct = $_POST['ct'];
$nl = preg_replace('#[^a-z]#', '', $_POST['nl']);
$nll = preg_replace('#[^a-z]#', '', $_POST['nll']);
$nl0 = preg_replace('#[^a-z]#', '', $_POST['nl0']);
$nll0 = preg_replace('#[^a-z]#', '', $_POST['nll0']);
$nl1 = preg_replace('#[^a-z]#', '', $_POST['nl1']);
$nll1 = preg_replace('#[^a-z]#', '', $_POST['nll1']);
$nl2 = preg_replace('#[^a-z]#', '', $_POST['nl2']);
$nll2 = preg_replace('#[^a-z]#', '', $_POST['nll2']);
$pl = preg_replace('#[^a-z]#', '', $_POST['pl']);
$pll = preg_replace('#[^a-z]#', '', $_POST['pll']);
$pl0 = preg_replace('#[^a-z]#', '', $_POST['pl0']);
$pll0 = preg_replace('#[^a-z]#', '', $_POST['pll0']);
$pl1 = preg_replace('#[^a-z]#', '', $_POST['pl1']);
$pll1 = preg_replace('#[^a-z]#', '', $_POST['pll1']);
$pl2 = preg_replace('#[^a-z]#', '', $_POST['pl2']);
$pll2 = preg_replace('#[^a-z]#', '', $_POST['pll2']);
$pl3 = preg_replace('#[^a-z]#', '', $_POST['pl3']);
$pll3 = preg_replace('#[^a-z]#', '', $_POST['pll3']);
$pl4 = preg_replace('#[^a-z]#', '', $_POST['pl4']);
$pll4 = preg_replace('#[^a-z]#', '', $_POST['pll4']);
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
$sql = "SELECT id FROM users WHERE username='$u' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$u_check = mysqli_num_rows($query);
// -------------------------------------------
$sql = "SELECT id FROM users WHERE email='$e' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$e_check = mysqli_num_rows($query);
if($u == "" || $e == "" || $p == "" || $g == "" || $c == "" || $ct == "" || $nl == "" || $pl == ""){
echo "The form submission is missing values.";
exit();
} else if ($u_check > 0){
echo "The username you entered is alreay taken";
exit();
} else if ($e_check > 0){
echo "That email address is already in use in the system";
exit();
} else if (strlen($u) < 3 || strlen($u) > 25) {
echo "Username must be between 3 and 25 characters";
exit();
} else if (is_numeric($u[0])) {
echo 'Username cannot begin with a number';
exit();
} else {
$p_hash = md5($p);
$sql = "INSERT INTO users (username, email, password, gender, country, city, nativelang, nlanglevel, nativelang0, nlanglevel0, nativelang1, nlanglevel1, nativelang2, nlanglevel2, practlang, planglevel, practlang0, planglevel0, practlang1, planglevel1, practlang2, planglevel2, practlang3, planglevel3, practlang4, planglevel4, ip, signup, lastlogin, notescheck)
VALUES('$u','$e','$p_hash','$g','$c','$ct','$nl','$nll','$nl0','$nll0','$nl1','$nll1','$nl2','$nll2','$pl','$pll','$pl0','$pll0','$pl1','$pll1','$pl2','$pll2','$pl3','$pll3','$pl4','$pll4','$ip',now(),now(),now())";
$query = mysqli_query($db_conx, $sql);
$uid = mysqli_insert_id($db_conx);
$sql = "INSERT INTO useroptions (id, username, background) VALUES ('$uid','$u','original')";
$query = mysqli_query($db_conx, $sql);
if (!file_exists("user/$u")) {
mkdir("user/$u", 0755);
}
$to = "$e";
$from = "email#site.com";
$subject = 'blah | Account Activation';
$message = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title> Message</title></head><body style="margin:0px; font-family:Tahoma, Geneva, sans-serif;"><div style="padding:10px; background:#333; font-size:24px; color:#CCC;">Account Activation</div><div style="padding:24px; font-size:17px;">Hello '.$u.',<br /><br />Click the link below to activate your account when ready:<br /><br />Click here to activate your account now<br /><br />Login after successful activation using your:<br />* E-mail Address: <b>'.$e.'</b></div></body></html>';
$headers = "From: $from\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\n";
mail($to, $subject, $message, $headers);
echo "signup_success";
exit();
}
exit();
}
HTML:
<legend class="legend"><h3>Select your languages</h3></legend>
<ul class="list-unstyled">
<li>
<div class="lala">
<table class="nativelanguages">
<tr>
<td>Spoken language</td>
<td style="padding-left: 5px;">Level</td>
</tr>
<tr class="initialn">
<td>
<select class="nativelangdrop" id="nativelang" name="nativelang" required>
<option value="none" selected disabled>Select language</option>
<?php
if ($file = #fopen('txt/languages.txt', 'r')) {
while(($line = fgets($file)) !== false) {
echo "<option>{$line}</option>";
}
fclose($file);
}
?>
</select></td>
<td>
<select class="langleveldrop" id="nlanglevel" name="nlanglevel" required>
<option value="none" selected disabled>Select level</option>
<?php
if ($file = #fopen('txt/levels.txt', 'r')) {
while(($line = fgets($file)) !== false) {
echo "<option>{$line}</option>";
}
fclose($file);
}
?>
</select>
</td>
</tr>
</table>
<div class="pmbutton">
<button href="javascript:;" type="button" class="btn btn-default" id="addBtnNative">
<span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
</button>
<button href="javascript:;" type="button" class="btn btn-default" id="remBtnNative">
<span class="glyphicon glyphicon-minus-sign" aria-hidden="true"></span>
</button>
</div>
</div>
<div class="lala">
<table style="float:left; margin-top:20px;" id="plang" class="practlanguages">
<tr>
<td>Practicing language</td>
<td style="padding-left: 5px;">Level</td>
</tr>
<tr class="initialp">
<td>
<select class="practlangdrop" id="practlang" name="practlang" required>
<option value="none" selected disabled>Select language</option>
<?php
if ($file = #fopen('txt/languages.txt', 'r')) {
while(($line = fgets($file)) !== false) {
echo "<option>{$line}</option>";
}
fclose($file);
}
?>
</select>
</td>
<td><select class="langleveldrop" id="planglevel" name="planglevel" required>
<option value="none" selected disabled>Select level</option>
<?php
if ($file = #fopen('txt/levels.txt', 'r')) {
while(($line = fgets($file)) !== false) {
echo "<option>{$line}</option>";
}
fclose($file);
}
?>
</select>
</td>
</tr>
</table>
<div class="pmbutton">
<button href="javascript:;" type="button" class="btn btn-default" id="addBtnPract">
<span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
</button>
<button href="javascript:;" type="button" class="btn btn-default" id="remBtnPract">
<span class="glyphicon glyphicon-minus-sign" aria-hidden="true"></span>
</button>
</div>
</div>
</li>
</ul>
Where you get your element values, try changing them to like this:
var u = _("username").value ? _("username").value : '';
This uses a Ternary Operator to set the value of u.
The syntax is: condition ? result-if-True : result-if-False;
Basically, this says, if _("username").value returns a value, assign that value to u, if not, set the value of u to "" (an empty string)
Below is a contrived example using regular jQuery method $("#username").val() I imagine it will also work with _("username").value though Im not sure what the benefit of doing _("username").value is having never seen this before myself.
var u = $("#username").val() ? $("#username").val() : 'not found';
alert(u);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
I suggest to use chrome developer tools so you can see what jquery.ajax send
https://developer.chrome.com/devtools#improving-network-performance
in php, you can see what are incoming using
print_r($_POST)
and
print_r($_GET)

autocomplete search form with multiple input php mysql

Hi Guys I have this search from that takes a search term matches it with a table.field and in php it searches all matching data.
I want to add autocomplete to it, can anyone PLEASE assist?
Here is the HTML FORM
<form action="'.$_SERVER['REQUEST_URI'].'" method="post">
<input type="text" id="searchThis" name="searchThis" placeholder="search" value="" size="14" />
<select name="searchItems" id="searchItems">
<optgroup value="Vehicles" label="Vehicles">Vehicles
<option value="vehicles.Make">Make</option>
<option value="vehicles.model">Model</option>
<option value="vehicles.RegNumber">Registration Number</option>
<option value="vehicles.licenseExpireDate">License Expire Date</option>
</optgroup>
<optgroup value="Owners" label="Owners">Clients
<option value="owners.OwnerName" label="" >Name</option>
<option value="owners.mobile">Mobile Number</option>
</optgroup>
</select>
<input type="submit" id="doSearch" name="Search" value="Search" />
</form>
<ul id="result">
</ul>
There is the JS
<script src="js/jquery-1.8.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
var $j = jQuery.noConflict();
(function($j){
$j(document).ready(function (){
$j("#searchThis").keyup(function()
{
var searchThis = $j('#searchThis').val();
var searchItems = $j('#searchItems').val();
var dataString = {'searchThis': searchThis,'searchItems':searchItems};
if(searchThis!='')
{
$j.ajax({
type: "POST",
url: "doAutocomplete_search.php",
data: dataString,
dataType: "html",
cache: false,
success: function(data)
{
$j("#result").html(data).show();
}
});
}return false;
});
$j("#result").live("click",function(e){
var clicked = $j(e.target);
var name = clicked.find('.name').html();
var decoded = $j("<div/>").html(name).text();
$j('#searchThis').val(decoded);
});
$j(document).live("click", function(e) {
var clicked = $j(e.target);
if (! clicked.hasClass("search")){
$j("#result").fadeOut();
}
});
$j('#searchid').click(function(){
$j("#result").fadeIn();
});
});
})($j);
And the PHP
function implement($cxn,$searchThis, $field) {
$show = "";
//Item to be searched
$srchThis = strip_tags(trim($searchThis));
//[0]= table , [1]=field to search
$srchStack = explode('.',$field);
$gtData = "SELECT * FROM ".$srchStack[0]." WHERE ".$srchStack[1]." like '%|{$srchThis}|%'";
//or die(mysqli_error($cxn))
if($selectc = mysqli_query($cxn,"SELECT * FROM {$srchStack[0]} WHERE {$srchStack[1]} LIKE '{$srchThis}%' OR {$srchStack[1]} LIKE '%{$srchThis}%'")) {
$srchData = array();
$rows = mysqli_fetch_row($selectc);
echo $rows;
//if() {, MYSQL_ASSOC
//echo var_dump($srchData);
$show .= '
<table style="border:2px solid #0000">';
//foreach($srchData as $fields=>$data) {
for($s=0; $s < $rows && $srchData = mysqli_fetch_assoc($selectc);$s++) {
if($srchStack[0] == 'vehicles' && $fields == 'RegNumber') {
$dataItem = $data;
$editTbl = 'Vehicles';
$link = 'href="index.php?list=vehicles&&tbl='.$srchStack[0].'&&item='.$dataItem.'"';
} elseif($srchStack[0] == 'vehicles' && $fields == 'Make') {
$dataItem = $data;
$editTbl = 'vehicles';
$link = 'href="index.php?list=vehicles&&tbl='.$srchStack[0].'&&item='.$dataItem.'"';
}
$show .= '<tr><td><a '.$link.'>'.$data.'</a></td></tr>
';
}
$show .= '</table>';
return $show;
} else {
$show .= "There are no entries in the database...<br>".mysqli_error($cxn);
return $show;
}
//}
}
echo implement($cxn, $_POST['searchThis'], $_POST['searchItems']);
$cxn->close();
Hi Guys so i had to do some refactoring, realized it was more the PHP MySQL code.
Here is the refactored PHP code
//Item to be searched
$srchThis = strip_tags(trim($searchThis));
//[0]= table , [1]=field to search
$srchStack = explode('.',$field);
$gtData = "SELECT * FROM ".$srchStack[0]." WHERE ".$srchStack[1]." like '%|{$srchThis}|%'";
//or die(mysqli_error($cxn))
if($selectc = mysqli_query($cxn,"SELECT * FROM {$srchStack[0]} WHERE {$srchStack[1]} LIKE '{$srchThis}%' OR {$srchStack[1]} LIKE '%{$srchThis}%'")) {
//$srchData = array();
$rows = mysqli_num_rows(#$selectc) or die(mysqli_error($cxn).'<br>No Rows returned...');
if($rows > 0) {//, MYSQL_ASSOC
//$link = ''; $l_c = 0;
$show .= '<table style="border:2px solid #0000">';
for($c = NULL;$c != $rows && $srchData = mysqli_fetch_assoc($selectc); $c++) {
foreach($srchData as $fields=>$data) {
if($fields == $srchStack[1]) {
$dataItem = $data;
$editTbl = $srchStack[0];
$show .= '<tr><td>'.$dataItem.'</td></tr>';//$a_json_row($dataItem);
//$show .= $link[$c];$link[$c]
}
}
}
$show .= '</table>';
return $show;
} else {
$show .= "There are no entries in the database...<br>".mysqli_error($cxn);
return $show;
}
Of-course the JS code still needs some more work but this greatly improved the results...
Hope this help someone...

Show the price in a textbox after selecting the id from a selected menu

I have two selected menu the 1st one we chose the type so the next will filter the mysql database to show the depertments numbers, and i need to show the depertment price in a textfiled after i select the depertment number from the second selectedmenu.
1st selected menu
<select name="gender" id="gender" class="update">
<option value="">Select one</option>
<?php if (!empty($list)) { ?>
<?php foreach($list as $row) { ?>
<option value="<?php echo $row['id']; ?>"> <?php echo $row['name']; ?>
<?php } ?>
</option>
<?php } ?>
</select>
2nd selected menu
<select name="category"
disabled="disabled" class="update" id="category" onChange="precio()" onClick="show()" >
<option value="">----</option>
</select>
this is how i get the value for the 2nd selected value
update.php
<?php
if (!empty($_GET['id']) && !empty($_GET['value'])) {
$id = $_GET['id'];
$value = $_GET['value'];
try {
$objDb = new PDO('mysql:host=localhost;dbname=name', 'root', '1234');
$objDb->exec('SET CHARACTER SET utf8');
$sql = "SELECT *
FROM `depertamientos`
WHERE `master` = ?";
$statement = $objDb->prepare($sql);
$statement->execute(array($value));
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
if (!empty($list)) {
$out = array('<option value="">Select one</option>');
foreach($list as $row) {
if ($row['visible'] == 0) {
$out[] = '<option value="'.$row['name'].'" id="'.$row['precio'].'">'.$row['name'].'</option>';
}
}
echo json_encode(array('error' => false, 'list' => implode('', $out)));
} else {
echo json_encode(array('error' => true));
}
} catch(PDOException $e) {
echo json_encode(array('error' => true));
}
} else {
echo json_encode(array('error' => true));
}
core.js
var formObject = {
run : function(obj) {
if (obj.val() === '') {
obj.nextAll('.update').html('<option value="">----</option>').attr('disabled', true);
} else {
var id = obj.attr('id');
var v = obj.val();
jQuery.getJSON('mod/update.php', { id : id, value : v}, function(data) {
if (!data.error) {
obj.next('.update').html(data.list).removeAttr('disabled');
} else {
obj.nextAll('.update').html('<option value="">----</option>').attr('disabled', true);
}
});
}
}
};
$(function() {
$('.update').live('change', function() {
formObject.run($(this));
});
});
js function
> <script src="javascripts/jquery-1.6.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
function show() {
var select = document.getElementById('category');
var input = document.getElementById('ds');
var change = document.getElementById('dpto');
var deptprecio = document.getElementById('11');
select.onchange = function() {
input.value = select.value;
deptprecio.value = "I don't know what to do here ???? ";
change.value = select.value;
}
}
</script>
my data base :
id master name visible precio
-------------------------------------------------
1 0 Type a 0 0
2 0 type b 0 0
3 1 101 1 20000
4 1 201 1 10000
5 2 103 1 30000
why putting the price as the id of your options tag ? Why not putting it in the value propertie as in #WebDevRon example?
$out[] = '<option value="'.$row['name'].'">'.$row['name'].'</option>';
remove javascript event in your your HTML tag:
<select name="category"
disabled="disabled" class="update" id="category" >
<option value="">----</option>
</select>
and if i understand your request you could just replace your javascript function "show" by something like this:
$("#category").change(function () {
var price = $(this).val();
$('#price-input').val(price); // where "price-input" is the id of your input.
});
Edit:
use data-attibute to store the price:
$out[] = '<option value="'.$row['name'].'" data-price="'.$row['precio'].'">'.$row['name'].'</option>';
JS:
$(function() {
$('.update').live('change', function() {
formObject.run($(this));
});
$("#category").change(function () {
var dept_number = $(this).val();
var price = $(this).find(':selected').data('price');
$('#dept-input').val(dept_number);
$('#price-input').val(price);
});
});
FIDDLE DEMO
Here is your complete solution - Demo
var $select2 = $('#select2');
var $text = $('#price');
$("#select1").change(function () {
var id = $(this).val();
if ($select2.data('options') == undefined) {
$select2.data('options', $select2.find('option').clone());
}
var options = $select2.data('options').filter('[value=' + id + ']');
$select2.html(options);
$text.val(id);
});

Categories