Using jQuery autocomplete from PHP/MySQL - php

My database columns as shown below:
`matDes1` varchar(255) DEFAULT NULL,
`matCost1` int(255) DEFAULT NULL,
`matDes2` varchar(255) DEFAULT NULL,
`matCost2` int(255) DEFAULT NULL,
`matDes3` varchar(255) DEFAULT NULL,
`matCost3` int(255) DEFAULT NULL,
`matDes4` varchar(255) DEFAULT NULL,
`matCost4` int(255) DEFAULT NULL,
`matDes5` varchar(255) DEFAULT NULL,
`matCost5` int(255) DEFAULT NULL,
I have a dynamic table with add and remove rows inside my HTML file.
Inside this table I have textarea and input, whenever I start typing will show me suggestions, and if I select one, will automatically populate other fields.
Here below my textarea and input:
<textarea id='codeANCILLARY_1' class='codeANCILLARY' name="codeANCILLARY[]"></textarea>
<input type="text" id="mat50ANCILLARY_1" class="mat50ANCILLARY" name="mat50ANCILLARY[]" />
textarea Searching through matDes1 to matDes5. so no problem here.
the problem is when selecting to populate both field, only accepting matDes1 and matCost1 not the rest.
is there a way to use say something like if statement and say:
if (matDes1 selected) {
show matDes1 with matCost1
} else if (matDes2 selected){
show matDes2 with matCost2
}
and
so
on
i really dont know anymore what must i do. :(
The full jQuery and PHP files are:
$(document).on('keydown', '.codeANCILLARY', function () {
var id = this.id;
var splitid = id.split('_');
var count = splitid[1];
$('#' + id).autocomplete({
source: function (request, response) {
$.ajax({
url: "../../MY_PHP_PAGE",
type: 'post',
dataType: "json",
data: {
search: request.term,
request: 1
},
success: function (data) {
response(data);
}
});
},
select: function (event, ui) {
$(this).val(ui.item.label);
var id = ui.item.value;
// AJAX
$.ajax({
url: '../../MY_PHP_PAGE',
type: 'post',
data: {
id: id,
request: 2
},
dataType: 'json',
success: function (takesAnyVaribale) {
var len = takesAnyVaribale.length;
if (len > 0) {
var codeANCILLARY = takesAnyVaribale[0]['codeANCILLARY'];
var mat50ANCILLARY = takesAnyVaribale[0]['mat50ANCILLARY'];
var unitsANCILLARY = takesAnyVaribale[0]['unitsANCILLARY'];
$('#codeANCILLARY_' + count).val(codeANCILLARY);
$('#mat50ANCILLARY_' + count).val(mat50ANCILLARY);
$('#unitsANCILLARY_' + count).val(unitsANCILLARY);
}
}
});
return false;
}
});
});
"MY_PHP_PAGE"
include "config.php";
$request = $_POST['request'];
if ($request == 1) {
$search = $_POST['search'];
$query1 = "SELECT * FROM MY_COMPONENTLIST WHERE matDes1 like'%".$search."%'";
$query2 = "SELECT * FROM MY_COMPONENTLIST WHERE matDes2 like'%".$search."%'";
$query3 = "SELECT * FROM MY_COMPONENTLIST WHERE matDes3 like'%".$search."%'";
$query4 = "SELECT * FROM MY_COMPONENTLIST WHERE matDes4 like'%".$search."%'";
$query5 = "SELECT * FROM MY_COMPONENTLIST WHERE matDes5 like'%".$search."%'";
$result1 = mysqli_query($con, $query1);
$result2 = mysqli_query($con, $query2);
$result3 = mysqli_query($con, $query3);
$result4 = mysqli_query($con, $query4);
$result5 = mysqli_query($con, $query5);
if ($result1 || $result2 || $result3 || $result4 || $result5) {
while ($row = mysqli_fetch_array($result1)) {
$response[] = array("value"=>$row['id'],"label"=>$row['matDes1']);
}
while ($row = mysqli_fetch_array($result2)) {
$response[] = array("value"=>$row['id'],"label"=>$row['matDes2']);
}
while ($row = mysqli_fetch_array($result3)) {
$response[] = array("value"=>$row['id'],"label"=>$row['matDes3']);
}
while ($row = mysqli_fetch_array($result4)) {
$response[] = array("value"=>$row['id'],"label"=>$row['matDes4']);
}
while ($row = mysqli_fetch_array($result5)) {
$response[] = array("value"=>$row['id'],"label"=>$row['matDes5']);
}
}
echo json_encode($response);
exit;
}
if ($request == 2) {
$id = $_POST['id'];
$sql = "SELECT * FROM MY_COMPONENTLIST WHERE id=".$id;
$result = mysqli_query($con, $sql);
$AncillaryPricing_arr = array();
while ($row = mysqli_fetch_array($result)) {
$id = $row['id'];
$codeANCILLARY = $row['matDes1'];
$mat50ANCILLARY = $row['matCost1'];
//***************************
//***************************
$codeANCILLARY = $row['matDes2'];
$mat50ANCILLARY = $row['matCost2'];
.and
.so on
.until 5
//***************************
//***************************
$unitsANCILLARY = $row['units'];
$AncillaryPricing_arr[] = array(
"id" => $id,
"codeANCILLARY" => $codeANCILLARY,
"mat50ANCILLARY" => $mat50ANCILLARY,
"unitsANCILLARY" => $unitsANCILLARY
);
}
echo json_encode($AncillaryPricing_arr);
exit;
}

You really need a better database layout for exactly this reason. Split the matdes and matcost columns out into a separate table, linked by the component ID. You can have as many as you want, then, and it's much easier to search them. Instead of all your separate queries, you'd have something like
SELECT * FROM MY_COMPONENTLIST_MAT WHERE matDes like'%".$search."%' and component_id = " . $id
(except as a prepared statement) and it would find any of them. You can use a JOIN to get the rest of the information from the main component list.

Related

Datatable not refreshing on ajax inside each loop

Scenario :
I have a datatable which has checkbox on each row. When i try to select all checkbox and remove all selected data from datatable, it was not refreshing but the code works perfectly fine on the backend. But when i try to select all except 1 row (any of the row) it works fine...
phpaction :
$query = "
SELECT id ID, code Code, name Name, description Description FROM tablename WHERE active = 1 ORDER BY id ASC";
$res = mysqli_query($dbcon, $query);
if (mysqli_num_rows($res) > 0) {
$data = array();
$tbl = '';
while ($row = mysqli_fetch_assoc($res)) {
$data[] = $row;
}
echo json_encode($data);
} else {
echo json_encode('');
}
ajax:
$datatable.find('input[type="checkbox"]:checked').each(function() {
ID = $(this).attr("value").substr((($(this).attr("value")).length - 8) * -1);
remove(ID);
});
function remove(ID) {
requestAction = 'remove';
$.ajax({
url: 'phpaction.php',
method: 'post',
data: {
requestAction: requestAction,
ID: ID
},
success: function(data) {
list();
},
error: function(err) {
console.log(err);
}
});
}

Getting Ajax reponse as null in php

I have a form in that I am trying to do inline editing and adding using AJAX call.
Firstly I am displaying data in HTML table. And then if enter data into text boxes and click on add button record adding displaying data in HTML table. After I click edit button data showing in the textboxes fine.
But I am getting the ajax response as null.
I couldn't figure it out.
This is my AJAX code PHP file:
$(function() {
$(".scrollingTable tbody a").click(function() {
//debugger;
var link = $(this).attr('href');
var arr = link.split('=');
var id = arr[1];
//alert(id);
$.ajax({
url: "insertgr.php",
type: "POST",
data: {
cntid: id
},
success: function(datas) {
var data = $.parseJSON(datas);
$("#num").val(data.id);
$("#namegr").val(data.vndr_cntname);
$("#designation").val(data.designation);
$("#mobilegr").val(data.vndr_cntmobile);
$("#maildgr").val(data.vndr_cntmail);
}
});
});
});
$(function() {
$('.txtcbt a').click(function() {
debugger;
var cntname, designation, mobile, email, vndrid, id, cid;
cid = $("#num").val();
cntname = $("#namegr").val();
designation = $("#designation").val();
mobile = $("#mobilegr").val();
email = $("#maildgr").val();
vndrid = "<?php echo $selectid; ?>";
//alert(cid);
if (cntname == "" || designation == "" || mobile == "" || email == "") {
alert("fields should not be empty");
} else {
$.ajax({
url: "insertgr.php",
type: "POST",
data: {
id: cid,
name: cntname,
dgnation: designation,
mobileno: mobile,
emailid: email,
vid: vndrid
},
success: function(html) {
var dat = $.parseJSON(html);
alert(html);
alert("it came to success");
$("#num").val("");
$('#namegr').val("");
$('#designation').val("");
$('#mobilegr').val("");
$('#maildgr').val("");
}
});
}
});
});
This is file AJAX is calling:
<?php
require('Assests/connection/connection.php');
error_reporting(0);
$vcntlist = "";
if (!empty($_POST['cntid'])) {
$id = $_POST['cntid'];
$result = mysqli_query($conn, "SELECT `id`, `vndr_cntname`, `designation`, `vndr_cntmobile`, `vndr_cntmail`,`vndr_id` FROM `vndr_cntdtls`where id=$id");
$rowcount = mysqli_num_rows($result);
if ($rowcount > 0) {
$row = mysqli_fetch_array($result);
$vcntid = $row['id'];
$cntname = $row['vndr_cntname'];
$cntdesignation = $row['designation'];
$cntmobile = $row['vndr_cntmobile'];
$cntmail = $row['vndr_cntmail'];
}
}
if (!empty($_POST['name']) && !empty($_POST['dgnation']) &&
!empty($_POST['mobileno']) && !empty($_POST['emailid']) &&
!empty($_POST['vid'])) {
$id = $_POST['id'];
$name = $_POST['name'];
$degination = $_POST['dgnation'];
$mobile = $_POST['mobileno'];
$email = $_POST['emailid'];
$vndrid = $_POST['vid'];
if (empty($_POST['id'])) {
$query = mysqli_query($conn, "INSERT INTO `vndr_cntdtls`(`vndr_cntname`, `designation`, `vndr_cntmobile`, `vndr_cntmail`, `vndr_id`) VALUES ('$name','$degination','$mobile','$email',$vndrid)");
} else {
$update1 = mysqli_query($conn, "UPDATE `vndr_cntdtls` SET `vndr_cntname`='$name',`designation`='$degination',`vndr_cntmobile`='$mobile',`vndr_cntmail`='$email' WHERE id=$id") or die(mysqli_error($conn));
}
$result = mysqli_query($conn, "SELECT DISTINCT `id`, `vndr_cntname`, `designation`, `vndr_cntmobile`, `vndr_cntmail`,vc.vndr_id FROM `vndr_cntdtls` vc INNER JOIN vendors v ON vc.vndr_id=$vndrid") or die(mysqli_error($conn));
$rowcount = mysqli_num_rows($result);
if ($rowcount > 0) {
while ($row = mysqli_fetch_array($result)) {
$vcntid = $row['id'];
$cntname = $row['vndr_cntname'];
$cntdesignation = $row['designation'];
$cntmobile = $row['vndr_cntmobile'];
$cntmail = $row['vndr_cntmail'];
}
}
}
echo json_encode($row);
?>
There could be a lot of ways it is not working.
First:
You need to put a application/json in your php so it can be compatible with the browser you are using.
header('Content-Type: application/json');
echo json_encode($row);
Second:
Why are you doing a while loop and assigning it into an unused variable?
You can simplify it by doing:
$row = mysqli_fetch_array($result);
header('Content-Type: application/json');
echo json_encode($row);
Unless it is multiple rows then:
$rowcount = mysqli_num_rows($result);
$rows = array();
if ($rowcount > 0) {
while ($row = mysqli_fetch_array($result)) {
$rows[] = $row;
}
}
header('Content-Type: application/json');
echo json_encode($row);
Third
null values usually appears when a variable you are trying to use is not initialized. By having the error_reporting turned off it does not display the error.
error_reporting(true);
Fourth
Check also the logs for database error, I assume it has something to do with MySQL query not having to reach the $row initialization.
Fifth
I believe you need to have it fetched as associative array for it to be useful
$row = mysqli_fetch_assoc($result);

ajax run mysql query and check whether mysql query was true or false?

I am using the following ajax script to run my MySQL query and then only want the jquery to fade out my div and fade in another if the query returned true otherwise if the query returned false don't do anything.
Ajax:
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: "include/fade_to_do_list.php",
data: "theOption=" + $(this).attr("id"),
dataType: 'json',//specify data type
success: function(data3) {
if(data3.res.indexOf("success") >-1 ){
setTimeout(
function() {
$("#to_do_list").fadeOut();
}, 3500
);
setTimeout(
function() {
$("#compliance_list").fadeIn();
}, 500
);
}
}
});
});
</script>
PHP/MYSQL:
<?php
session_start();
include 'config.php';
$query = "SELECT * FROM supplier_stats WHERE complete_count = > 3 AND user_id = '{$_SESSION['id']}'";
$result = mysql_query($query);
if(mysql_num_rows($result)>0) {
$query2 = "UPDATE supplier_stats SET profile_complete = 'complete' WHERE user_id = '{$_SESSION['id']}'";
$result2 = mysql_query($query2);
if($result2) {
$return['res'] = 'success';
} else {
}
}
echo json_encode($return);
?>
Please can someone show me where I am going wrong? I currently get no error and my jquery just doesnt execute. Thanks
mysql_query() always return you something. You need to count number of affected row.
Also problem is with equal to greater then operator it is used as >=
$query = "SELECT * FROM supplier_stats WHERE complete_count >= 3 AND user_id = '{$_SESSION['id']}'";
$result = mysql_query($query);
$query2 = "UPDATE supplier_stats SET profile_complete = 'complete' WHERE user_id = '{$_SESSION['id']}'";
$result2 = mysql_query($query2);
$total=mysql_affected_rows();
if($total >0) {
$return['res'] = 'success';
} else {
}

How to get the last 5-10 message from a database?

I am gtting data from database, but it's printed again and again. There is get coding of index page.
var lastmsgid = 0;
function getChat() {
$.ajax({
type: "POST",
url: "view_msg.php",
data: "sid=<?php echo $id; ?>&lastmsgid="+lastmsgid,
async: false,
datatype: "json",
success: function(rows) {
for (var i in rows) {
var row = rows[i];
var uname=row['uname'];
var msg=row['msg'];
$('#chatbox').append("<b>"+uname+"</b> : </b>"+msg).append("<hr />");
lastmsgid=row['id'];
}
}
});
}
Here is my view_msg.php page:
<?php
header('Content-type: application/json');
require_once('include/util.php');
$sid = $_POST['sid'];
$lastmsgid = $_POST['lastmsgid'];
$sql = "SELECT m.`id`, m.`msg`, u.`uname` FROM `message` as m JOIN `userdata` as u ON (m.`senderid`=u.`id`) WHERE m.`rcvrid` = ".$_SESSION['id']." OR m.`rcvrid` =$sid AND `senderid` = $sid OR `senderid` =".$_SESSION['id']." AND m.`id` > $lastmsgid order by m.`id` DESC limit 0,2" ;
$result = mysql_query($sql);
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
if (!empty($data)) {
echo json_encode($data);
}
exit;
?>
You should check your SQL query.. You need to use brackets in where condition because you are using OR.. I don't know the conditions for your desired result but it may be like below:
$sql="SELECT m.`id`,m.`msg`,u.`uname` FROM `message` as m JOIN `userdata` as u ON (m.`senderid`=u.`id`) WHERE ((m.`rcvrid` = ".$_SESSION['id']." OR m.`rcvrid` =$sid) AND (`senderid` = $sid OR `senderid` =".$_SESSION['id']." ) ) AND m.`id` > $lastmsgid order by m.`id` DESC limit 0,2" ;

php jquery iterate php array in success function

I have jquery pop form . It takes one input from the user ,mapping_key , Once the user enters the mapping key ,i make an ajax call to check if there is a user in the database with such a key.
This is my call .
Javascript:
$.ajax({
url : base_url+'ns/config/functions.php',
type: 'POST',
data : {"mapping_key":mapping_key} ,
success: function(response) {
alert(response)
}
});
PHP:
$sql = "select first_name,last_name,user_email,company_name from registered_users where mapping_key = '$mapping_key'";
$res = mysql_query($sql);
$num_rows = mysql_num_rows($res);
if($num_rows == 0)
{
echo $num_rows;
}
else{
while($result = mysql_fetch_assoc($res))
{
print_r($result);
}
}
Now i want to loop through the returned array and add those returned values for displaying in another popup form.
Would appreciate any advice or help.
In your php, echo a json_encoded array:
$result = array();
while($row = mysql_fetch_assoc($res)) {
$result[] = $row;
}
echo json_encode($result);
In your javascript, set the $.ajax dataType property to 'json', then you will be able to loop the returned array:
$.ajax({
url : base_url+'ns/config/functions.php',
type: 'POST',
data : {"mapping_key":mapping_key} ,
dataType : 'json',
success: function(response) {
var i;
for (i in response) {
alert(response[i].yourcolumn);
}
}
});
change
data : {"mapping_key":mapping_key} ,
to
data: "mapping_key=" + mapping_key,
You have to take the posted mapping_key:
$mapping_key = $_POST['mapping_key'];
$sql = "select first_name,last_name,user_email,company_name from registered_users
where mapping_key = '$mapping_key'";
or this:
$sql = "select first_name,last_name,user_email,company_name from registered_users
where mapping_key = $_POST['mapping_key']";

Categories