Multiple searchboxes via AJAX - php

I want to use several textboxes on the page which all have their own search query to fetch data from the database.
I have it working on 1 textbox but I can't get it to work for 2 or more textboxes.
This is my code:
php
$opts = (isset($_POST['filterOpts']) ? $_POST['filterOpts'] : FALSE);
$val = (isset($_POST['text']) ? $_POST['text'] : FALSE);
$val2 = (isset($_POST['text']) ? $_POST['text'] : FALSE);
if ($val != null){
$where = " WHERE boekingsnummer LIKE '".$val."%'";
}
if ($val2 != null){
$where = " WHERE huiscode LIKE '".$val2."%'";
}
$sql = $select . $from . $where;
$statement = $pdo->prepare($sql);
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);
ajax
$('#boekingsnummer_1').keyup(function(){
updateEmployeesText($(this).val());
});
$('#huiscode_1').keyup(function(){
updateEmployeesText($(this).val());
});
function updateEmployeesText(val){
$.ajax({
type: "POST",
url: "submit.php",
dataType : 'json',
cache: false,
data: {text: val},
success: function(records){
$('#employees tbody').html(makeTable(records));
}
});
}

generate a string and pass it through url.
$('#huiscode_1').keyup(function(){
var text = '?val1='+$(this).val()+'&val2='$('#boekingsnummer_1').val();
updateEmployeesText($(this).val(text));
});
function updateEmployeesText(val){
$.ajax({
type: "POST",
url: "submit.php"+val,
cache: false,
success: function(records){
$('#employees tbody').html(makeTable(records));
}
});
}
like this. generate the string for every input fields u want and do the necessary checks before generating.GET the values on php script & process.hope this will work.

Related

Ajax post not passing data to php?

So I'm having trouble with passing data using ajax post to php
Here is my jquery :
$('#kodeobat').on('change',function(){
var kodeobat = $(this).val();
if (kodeobat = ""){
$("#hargaobat").val("");
} else {
$.ajax({
type: "POST",
data: { 'kodeobat': kodeobat },
dataType: "json",
url: "getdata.php",
success: function(json) {
$("#hargaobat").val(json["hargaobat"]);
}
});
}
});
and here is the php file:
$kodeobat = $_POST['kodeobat'];
$stmt = $db_con->prepare("SELECT kodeobat, hargaobat FROM Obat WHERE kodeobat='".$kodeobat."'");
$stmt->execute();
while($row=$stmt->fetchAll(PDO::FETCH_ASSOC))
{
if($kodeobat == $row['kodeobat']){
echo json_encode($row);
}
}
and it results : Notice: Undefined index: kodeobat in .../getdata.php on line 4 which is this line $kodeobat = $_POST['kodeobat'];
Is there something wrong with the code? Thank youuu :)
$('#kodeobat').on('change',function(){
var kodeobat = $(this).val();
if (kodeobat == ""){
$("#hargaobat").val("");
} else {
$.ajax({
type: "POST",
data: { 'kodeobat': kodeobat },
dataType: "json",
url: "getdata.php",
success: function(json) {
$("#hargaobat").val(json["hargaobat"]);
}
});
}
});
Notice if (kodeobat == "")
Try sending your JSON as JSON by using PHP's header() function:
header("Content-Type: application/json", true);
look at this
If you are unaware of what type of value you would get in response here is a try..
$kodeobat = $_POST['kodeobat'];
if(empty($kodeobat)) {
echo("Value is empty");
} else if(is_array($kodeobat)) {
$i = count($kodeobat); //If the value is array iterate it
for($j = 0; $j < $i; $j++) {
echo($kodeobat[$i] . " ");
}
} else if(is_object($kodeobat)){
$json = json_decode($_POST,true); //if it is a json value decode it
$kodeobat_new = $json['kodeobat'];
}

How get AJAX to Post JSON data into div

I'm new Jquery and AJAX and I've really been struggling with the syntax I've been trying to use other tutorials as reference but nothing seems to work. I feel I have the right idea but syntax is wrong somewhere please help.
Here is the Ajax side
var var_numdatacheck = <?php echo $datacheck; ?>;
var var_numcheck = parseInt(var_numdatacheck);
function activitycheck(){
$.ajax({
type: 'POST',
url: 'feedupdate.php',
data: {function: '3test', datacheck: var_numcheck},
dataType: "json",
success: function(data) {
var json = eval('(' + data + ')');
$('#datacheck').html(json['0']);
var var_numcheck = parseInt(msg);
//setTimeout('activitycheck()',1000)},
error:function(msg) {
console.log(msg);
}
});
}
$(document).ready(function() {
activitycheck();
});
Here is the php the AJAX calls
<?php
require "dbc.php";
$function = $_POST['function'];
$datacheck = $_POST['datacheck'];
$search="SELECT * FROM Feedtest ORDER BY id DESC";
$request = mysql_query($search);
$update= mysql_fetch_array($request);
$updateid = $update['id'];
$updatecheck = mysql_num_rows($request);
$data = array();
if ($function == $datacheck){
echo $updatecheck;
echo $datacheck;
}
if ($function == "3test" && $updatecheck > $datacheck ) {
$updatesearch="SELECT * FROM Feedtest WHERE id = '$updateid' ORDER BY id DESC";
$updatequery = mysql_query($updatesearch);
$data['id'] = $updateid;
while ($row = mysql_fetch_array($updatequery))
{
?>
<?php $data[]= $row['First Name']; ?>
<?php
}
echo json_encode($data);
}
?>
</div>
</ul>
first of all ,always use JSON.parse(data) instead of eval.It is considereda a good practice.
second thing is always try to debug your code by checking it in console or alerting.In your context,this is what is happening-:
$.ajax({
type: 'POST',
url: 'feedupdate.php',
data: {function: '3test', datacheck: var_numcheck},
dataType: "json",
success: function(data) {
var data = eval('(' + data + ')');
console.log("myData"+data)//debugging.check the pattern so that you can acces it the way you want!!!
for(var i=0;i< data.length;i++)
{
alldata += "<li>"+data[i][0]+"<li><hr>";
}
$('#datacheck').html(alldata);
});
}
For JSON.parse:
success: function(data) {
var data = JSON.parse(data);
console.log("myData"+data)//debugging.check the pattern so that you can acces it the way you want!!!
for(var i in data)
{
alldata += "<li>"+data[i].First Name+"<li><hr>";
}
$('#datacheck').html(alldata);
});

PHP Jquery JSON catching

Here's my php responding to my jQuery calls.
<?php
if ( isset( $_POST['icnumber']) && $_POST['icnumber'] != '' ) {
$custic = $_POST['icnumber'];
$response = array();
$response['status'] = 'false';
$sql ="SELECT * FROM ctrl_cust WHERE cust_ic='$custic'";
$raw = mysql_query($sql,$link) or die('Query 1 '.mysql_error());
if ( $data = mysql_fetch_assoc( $raw ) ) {
$response['status'] = 'true';
$response['custid'] = $data['cust_id'];
$response['custname'] = $data['cust_name'];
}
header("Content-Type: application/json", true);
echo json_encode($response);
}
?>
and here's the jQuery
$(function() {
$('#icnumber-form').submit(function() {
var icno = $('#icnumber').val();
$.ajax({
type : 'POST',
url : 'php/create_process.php',
data : icno,
dataType: 'json',
success : function(data){
console.log(data);
},
beforeSend:function(){
$('.cust-exist-view').fadeIn();
}
});
return false;
})
});
The thing is, console.log returns NULL, but when I submit the form without javascript enabled, it returns this :
{"status":"true","custid":"00001","custname":"John"}
I wonder what is the problem...I've been running around in circles for hours...Help me please?
icnumber is not getting post, change data: icno, to data: {icnumber: icno}, and try

Auto Complete with json and bootstrap

this is my code:
class_search.php
case 'users':
if(!empty($_REQUEST['user'])){
if(strlen($_REQUEST['user']) >= 3){
$_REQUEST['user'] = $this->sanitize($_REQUEST['user'], 'string');
$stmt = $this->sql->prepare('SELECT
id,
nome,
url
FROM
animes
WHERE
nome LIKE ?
LIMIT 10');
$stmt->execute(array('%'.$_REQUEST['user'].'%'));
$this->queries++;
$c = 0;
if($admin){
$result['users'] = array();
}
if($stmt->rowCount() > 0){
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
if($admin){
$result['users'][$c] = array('name'=>($prefix ? '[usr] ' : '').$row['nome'], 'id'=>$row['id']);
$c++;
}else{
$result[] = ($prefix ? '[usr] ' : '').$row['nome'];
}
}
}
}
}
break;
general.js
$('#top_search').typeahead({
source: function(typeahead, query) {
$.ajax({
url: baseurl + "/ajax_calls.php",
dataType: "json",
type: "POST",
data: {
call: 'top_search',
user: query
},
success: function(data) {
typeahead.process(data);
}
});
},
onselect: function(obj) {
location.href= baseurl + '/animes/'+obj;
}
})
ajax_calls.php
case 'top_search':
$status = $site->process_autosearch('users');
break
;
I am having problem with onselect, I need to select the row url in my MySQL and encode to json, because when I click in one result I am redirect to mysite.com/animes/name of anime/ (yes, with space) and I need to fix this.
Table animes in phpMyAdmin:
http://s18.postimage.org/3ulrcmss9/Animes_Table.jpg
Quickly video: http://www.screenr.com/plZ7
You would need to use urlencode().
In your class_search.php file, update this part:
if($admin){
$result['users'][$c] = array('name'=>($prefix ? '[usr] ' : '').urlencode($row['nome']), 'id'=>$row['id']);
$c++;
}else{
$result[] = ($prefix ? '[usr] ' : '').urlencode($row['nome']);
}
And to make the names looks good in the searche auto-complete as well, you need to modify your jQuery as well, wrapping the decodeURIComponent() function around the obj like so:
onselect: function(obj) {
location.href= baseurl + '/animes/' + decodeURIComponent(obj);
}

Return Values from PHP to JSON/AJAX

A friend of mine had given me this snippet for a js file that can be useful for me:
$.ajax({
type: "POST",
url: "../CheckPerson.php",
data: "{'lastName':'" + _lname + "','firstName':'" + _fname + "','middleName':'" + _mname + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var res = response.d;
if (res == true) {
jAlert('Patient Name already exists!', 'Error');
return;
}
else {
$.ajax({
type: "POST",
url: "../NewPerson.php",
data: "{'lastName':'" + _lname + "','firstName':'" + _fname + "','middleName':'" + _mname + "','gender':'" + _gender + "','birthDate':'" + _bday + "','ssn':'" + _ssn + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var _id = response.d;
if (_id.length != 0) {
$('#patientName').removeAttr('disabled');
$('#patientName').val(_lname + ", " + _fname + " " + _mname);
$('#patientId').val(_id[0].patientID);
$('#dateOfBirth').val(_bday);
$('#referringDoctor').removeAttr('disabled');
$('#referringDoctor').focus();
$('#patientAge').val(_id[1]);
$('#ptLastName').val('');
$('#ptFirstName').val('');
$('#ptMiddleName').val('');
$('#ptGender').val('');
// $('input[name="birthdate"]').val(); // $('#ptBirthDate').val();
$('#ptSSN').val('');
}
// if (_id == true) {
// }
insertCallback(_id);
// $('#diagnosis tbody>tr:last').attr('dinfo', '_IEDiagnosis|' + _id);
},
failure: function (msg) {
alert(msg);
}
});
}
}
});
I'm using PHP but I'm new to using JSON. Is there a way to return a true value for "response.d" in my PHP file:
success: function (response) {
var _id = response.d;
}
Here's my logic but don't know the code to use:
$lastname = isset($_REQUEST['lastName'])?$_REQUEST['lastName']:'';
$firstname = isset($_REQUEST['firstName'])?$_REQUEST['firstName']:'';
$middlename = isset($_REQUEST['middleName'])?$_REQUEST['middleName']:'';
$response = array();
mysql_connect ("localhost", "root") or die ('Error: ' . mysql_error());
mysql_select_db ("healthpal");
$query = "SELECT Lastname, Firstname, MiddleName FROM db_patients WHERE Lastname = '$lastname' || Firstname = '$firstname' || MiddleName = '$middlename'";
$qrytest = mysql_query($query);
if (isset($qrytest)) {
//"response.d" will be true if the query return not NULL
}
Try something like this:
header('Content-type: application/x-json');
echo json_encode( array( 'd' => true ) );
What you need is the php json_encode function:
json_encode(array('response'=>'true')));
You have to construct JSON string in your PHP file, some thing like this
{"result":"true"}
this constructed JSON string should return as PHP response. In Javascript parse the JSON as,
var obj = eval(response)
if(obj.result == 'true'){
//Do your code here
}

Categories