I've got some JQuery which monitors a form. Basically, for every keyup it will call a php file to search the database.
$(document).ready(function() {
$("#faq_search_input").watermark("Begin Typing to Search");
$("#faq_search_input").keyup(function() {
var faq_search_input = $(this).val();
var dataString = 'keyword='+ faq_search_input;
if (faq_search_input.length > 2) {
$.ajax({
type: "GET",
url: "core/functions/searchdata.php",
data: dataString,
beforeSend: function() {
$('input#faq_search_input').addClass('loading');
},
success: function(server_response) {
$('#searchresultdata').empty();
$('#searchresultdata').append(server_response);
$('span#faq_category_title').html(faq_search_input);
}
});
}
return false;
});
});
This works fine, however it filters the results in #searchresultdata depending on the query. The only thing is, if nothing is in the form, I want it to load everything - the user should not have to click the form to do this, therefore a .blur would not work.
The PHP file is simply:
if(isset($_GET['keyword'])){}
you should handle a [*] search on your server
$query = "SELECT Image, Manufacturer, Model FROM Device_tbl WHERE Manufacturer LIKE '%$keyword%' OR Model LIKE '%$keyword%";
if ($keyword=='*') $query = "SELECT Image, Manufacturer, Model FROM Device_tbl";
$(document).ready(function() {
$("#faq_search_input").watermark("Begin Typing to Search");
$("#faq_search_input").keyup(function() {
var faq_search_input = $(this).val();
if (faq_search_input =='') faq_search_input ='*';
var dataString = 'keyword='+ faq_search_input;
if (faq_search_input.length > 2 || faq_search_input=='*') {
$.ajax({
type: "GET",
url: "core/functions/searchdata.php",
data: dataString,
beforeSend: function() {
$('input#faq_search_input').addClass('loading');
},
success: function(server_response) {
$('#searchresultdata').empty();
$('#searchresultdata').append(server_response);
$('span#faq_category_title').html(faq_search_input);
}
});
}
return false;
});
$("#faq_search_input").trigger('keyup');
});
If you're loading all results initially, then could you not just store this in a JavaScript array and filter the results with JavaScript? This would save you a HTTP request on every key press, which can only be good for speed and resource usage of your site.
EDIT: Sample.
<?php
$sql = "SELECT `title` FROM `your_table`";
$res = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($res)) {
$rows[] = $row['title'];
}
echo '<script>var data = ' . json_encode($rows) . ';</script>';
?>
<form method="post" action="">
<fieldset>
<input type="text" name="search" id="faq_search_input" />
</fieldset>
</form>
<script>
// I presume you're using jQuery
var searchInput = $('#faq_search_input');
var searchResults = $('#searchresultdata');
var tmpArray = data;
// add all results to results div
$.each(data, function(key, val) {
searchResults.append('<li>' + val + '</li>');
});
searchInput.attr('placeholder', 'Begin typing to search');
searchInput.keyup(function() {
// hide any <li> in your #searchresultdata that don't match input
});
</script>
I don't know what is in your serverresponse variable, so I can only guess what gets put into the searchresultdata <div>. You'll also need to modify the SQL query to match your table and column names.
Contents of searchdata.php
$query = "SELECT Image, Manufacturer, Model FROM Device_tbl WHERE Manufacturer LIKE '%$keyword%' OR Model LIKE '%$keyword%'";
if ($keyword=='*') $query = "SELECT Image, Manufacturer, Model FROM Device_tbl";
$result=mysql_query($query, $database_connection) or die(mysql_error());
if($result){
if(mysql_affected_rows($database_connection)!=0){
while($row = mysql_fetch_object($result)){
?>
<div class="hold-cont">
<div class="holder">
<div class="image-hold" >
<img class="image-icon" src="<? echo $deviceimg.($row->Image); ?>"/>
</div>
</div>
<div class="device-name devicename-txt"><? echo($row->Manufacturer. ' ' .$row->Model); ?></div>
</div>
<?
}
}else {
echo 'No Results for :"'.$_GET['keyword'].'"';
}
}
}else {
echo 'Parameter Missing';
}
Related
I have reviewed suggested solutions but did not find any matching my issue.
We have a SELECT list that is dynamically populated from the database.
Each time a staff wishes to create a task and allocate time to complete the task, s/he selects the member who would handle that task and then allocates time to complete the task. This works fine.
//JS
function populateMember() {
$.ajax({
type: 'GET', // define the type of HTTP verb we want to use (POST for our form)
url: 'php/getMember.php?mode=edited&rowId=' + $.urlParam('id'), // the url where we want to POST
dataType: 'html', // what type of data do we expect back from the server
encode: true
})
.done(function (data) {
var returnedData = JSON.parse(data);
var newRows = (returnedData.length - 3);
if (returnedData.length > 3){
var x = 0;
for (x=0; x < newRows; x++){
$( "#newMember" ).trigger( "click" );
}
}
var i=0;
for (i in returnedData){
$('#member' + i).val(returnedData[i][0]);
$('#task_time_alocatted' + i).val(returnedData[i][1]);
}
})
.error(function () {});
}
//PHP
<?php
//Connect to server
///Connection info goes here
}
//These are parameters from the POST request
$mode = $_GET[ 'mode' ];
$rowId = (int) $_GET[ 'rowId' ];
$sql = "SELECT member, task_time_allocated FROM TaskAllocations WHERE parent_task_id = $rowId;";
$stmt = sqlsrv_query( $conn, $sql );
if ( $stmt === false ) {
$theErrors = sqlsrv_errors();
array_push($messages, 0, $sql, $theErrors);
echo json_encode($messages);
die();
} else {
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_BOTH) ) {
array_push($messages, [$row['member'], $row['task_time_allocated']]);
}
echo json_encode($messages);
}
?>
However, if the member that a staff is trying to select from the SELECT list is not on that list, we would like two text boxes, one for the member and one for task to be allocated to that member.
How do we handle this?
We have created this on the HTML form:
//JS
<script type="text/javascript">
$(function () {
$("#btnstaff").click(function () {
if ($(this).val().toLowerCase() == "amend") {
$.each($('.dvstaff'), function(i, item){
$(this).show();
});
$(this).val("Cancel");
} else {
$.each($('.dvstaff'), function(i, item){
$(this).hide();
});
$(this).val("Amend");
}
});
});
</script>
//HTML
<input id="btnstaff" type="button" value="Amend" name="btnstaff" />
<tr>
<td></td>
<td><div class="dvstaff" style="display: none"><input id="amendmember" class="shortText" style="width:242px;" name="amendmember"></div></td>
<td>
<div class="dvstaff" style="display: none"><input id="amendtime" class="shortText" placeholder="0" name="amendtime"> %</div></td>
</tr>
You click Amend and it creates two blank textboxes, one for new member and the other for task_time_allocated.
We would prefer to handle this Amend bit on the JS that invokes the getMember method since the HTML is generated from the JS.
Is this possible?
I have some <td name="puja"> elements I want to update every 5 seconds deppending on their id so they contain the greatest bid(puja) for it's auction(subasta). For that, I'm trying to use AJAX and PHP.
Html looks like this (relevant code):
<?php
foreach ($subastas as $subasta) { ?>
<td name="puja" id="<?php echo $subasta["oid_s"] ?>"> </td>
As I have multiple elements to update, I tried getting all the elements and then running my AJAX function for every one of them.
AJAX:
$(document).ready(function()
{
var ids = document.getElementsByName("puja");
for (var i=0; i<ids.length;i++){
var id = ids[i].id;
$.ajax({
url : 'includes/getPuja.php',
data:{"oid_s":id},
success: function(data){
$(`#${id}`).html(data);
}
});
};
});
Finally, in my php file I just make a database connection, get the desired value , and echo it.
getPuja.php (relevant code):
$puja = 0;
if(isset($_POST["oid_s"])) {
$oid_s = $_POST["oid_s"];
$consultaPuja='SELECT pujado from (SELECT * from pujas WHERE OID_S = :oid_s ORDER BY pujado DESC) where rownum = 1';
try {
$stmtPuja = $conexion->prepare($consultaPuja);
$stmtPuja -> bindParam(':oid_s', $oid_s);
$stmtPuja -> execute();
foreach ($stmtPuja as $fila) {
$puja = $fila["PUJADO"] ;
}
echo $puja;
} catch(PDOException $e) {
$_SESSION["excepcion"] = $e -> GetMessage();
header("Location: excepcion.php");
}
}
When I run it, the HTML is not modified.
I fixed my problem with the following code, now the values get updated every second:
$(document).ready(function(){
setInterval(getPuja, 1000);
function getPuja() {
$( '[name=puja]' ).each(function() {
var id = $( this ).attr('id');
$.ajax({
url : 'includes/getPuja.php',
method:"POST",
data:{oid_s:id},
success: function(data){
$(`#${id}`).html(data);
}
});
});
}
});
I am new to JQUERY and I am trying to search for the something and based on the searched text I am doing an ajax call which will call php function and the PHP is returning me with JSON data.
I want to display the returned data in the Datatable form.
I have my PHP file table.php and JavaScript file jss.js and my main.php.
The PHP file is returning the JSON data and I able to use alert to display it.
I want to know how can I display it in datatable.
<div>
<input type="text" name="search_query" id="search_query" placeholder="Search Client" size="50" autocomplete="off"/>
<button id="search" name="submit">Search</button>
</div>
my ajax/jss.js file
$(document).ready(function(){
$('#search').click(function(){
var search_query = $('#search_query').val();
if(search_query !='')
{
$.ajax({
url:"table.php",
method:"POST",
data:{search_query:search_query},
success: function(data)
{
alert("HEKKI "+data);
}
});
}
else
{
alert("Please Search again");
}
});
});
my table.php file
<?php
$data=array();
$dbc = mysqli_connect('localhost','root','','acdc') OR die('Could not connect because: '.mysqli_connect_error());
if (isset($_REQUEST['search_query']))
{
$name = $_REQUEST['search_query'];
}
if($dbc)
{
if (!empty($name))
{
$sql = "select c.res1 res1,
cc.res2 res2,
cc.res3 res3,
cc.res4 res4,
cc.res5 res5
from table1 c
inner join table2 cc
on c.id = cc.id
where c.name like '".$name."%'
and cc.ENABLED = 1";
$res = mysqli_query($dbc,$sql);
if(!(mysqli_num_rows($res)==0))
{
while($row=mysqli_fetch_array($res))
{
$data['RES1'] = $row['res1'];
$data['RES2'] = $row['res2'];
$data['RES3'] = $row['res3'];
$data['RES4'] = $row['res4'];
$data['RES5'] = $row['res5'];
}
}
else
{
echo "<div style='display: block; color:red; text-align:center'><br/> Not Found,Please try again!!!</div>";
}
}
}
echo json_encode($data);
/*
*/
?>
Can you please guide me how to display the result in main page.
Setting utf8 as charset is probably a good idea. If you have different charset in your table you will get a JSON error :
mysqli_set_charset($dbc, 'utf8');
Then use mysqli_fetch_assoc instead of mysqli_fetch_array. You want field: value records turned into JSON :
$data = array();
while($row=mysqli_fetch_assoc($res)) {
$data[] = $row;
}
Output the JSON :
echo json_encode( array('data' => $data) );
Now you can use it directly along with dataTables :
<table id="example"></table>
$('#example').DataTable({
ajax: {
url: 'table.php'
},
columns: [
{ data: 'res1', title: 'res1'},
{ data: 'res2', title: 'res2'},
//etc..
]
})
one approach is to create the form fulfiled with data just in table.php file and with support of jQuery you will need to populate the <form id="form_id"> with ajax result $('#form_id').html(ajax_response);
other aproach:
to use jQuery json data to populate every field separately.
var jsonData = JSON.parse( ajax_response ); // decode json
than
$('#id_input_1').val(jsonData.RES1);
$('#id_input_2').val(jsonData.RES2);
$('#id_input_3').val(jsonData.RES3);
Place a placeholder in this case I used #results, and dynamically create a table and append it to the placeholder. I commented out your ajax for this example, but just call the function I created to process the results from within the success callback and pass the new function a javascript object.
$(document).ready(function() {
$('#search').click(function() {
var search_query = $('#search_query').val();
if (search_query != '') {
//$.ajax({
// url: "table.php",
// method: "POST",
// data: {
// search_query: search_query
// },
// success: function(data) {
// alert("HEKKI " + data);
// }
//});
processResults({RES1: "result1", RES2: "result2"});
} else {
alert("Please Search again");
}
});
});
function processResults(obj){
var $tbl = $("<table>");
var $row = $("<tr>");
var trow;
$.each(obj, function(idx, elem){
trow = $row.clone();
trow.append($("<td>" + obj[idx] + "</td>"));
$tbl.append(trow);
});
$("#results").append($tbl);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" name="search_query" id="search_query" placeholder="Search Client" size="50" autocomplete="off" />
<button id="search" name="submit">Search</button>
<div id='results'></div>
</div>
I want to make the third drop down populated based on selection on second drop down refer value from first and second drop down.
jQuery
<script type="text/javascript">
$(document).ready(function() {
$("#parent_cat").change(function() {
$.get('loadsubcat.php?parent_cat=' + $(this).val(), function(data) {
$("#sub_cat").html(data);
});
});
$("#sub_cat").change(function() {
$.get('loadsubelement.php?sub_cat=' + $(this).val() + $('#parent_cat').val(), function(data) {
$("#select_subelement").html(data);
});
});
});
</script>
loadsubelement.php
<?php
include('config.php');
$parent_cat = $_GET['parent_cat'];
$sub_cat = $_GET['sub_cat'];
$query = mysqli_query($connection, "SELECT * FROM maincategories WHERE categoryID = {$parent_cat}");
$query = mysqli_query($connection, "SELECT * FROM maincategories WHERE subcategoryID = {$sub_cat}");
echo '<option value="">Please select</option>';
while($row = mysqli_fetch_array($query)) {
echo '<option value="'.$row['subcategoryID'].'">' . $row['maincategory_name'] . "</option>";
}
?>
I think you have to change your query string like this:
$.get('loadsubelement.php?sub_cat=' + $(this).val() +
"&parent_cat" + $('#parent_cat').val()
You are missing this: "&parent_cat" in your second ajax call.
Or a better way of doing is to send the an object like this:
$("#sub_cat").change(function() {
var dataString = {
parent_cat : $('#parent_cat').val(),
sub_cat : $(this).val()
};
if($('#parent_cat').val() !== ""){ // check if value is selected or not i guessed default value as "".
alert("Please choose the parent value.");
$('#parent_cat').focus(); // apply focus on the element.
return false;
}else{
$.get('loadsubelement.php', dataString, function(data) {
$("#select_subelement").html(data);
});
}
});
jQuery(function($) {
jQuery("#office_id").change(function(){
var inputString=jQuery("#office_id").val();
$.post("?r=reports/summary/loademployees/", {office_id: ""+inputString+""}, function(data){
$('#employee_id').fadeIn();
$('#employee_id').html(data);
}
});
});
});
This is a program triggers when when u change a dropdown containing offices having id as office_id and load employees (another dropdown box having id employee_id) of that office.
I have this messaging system (aka wall). It works to add new messages and If I want to cancel the messages loaded from the database. But if I want to cancel the new messages which have just been appended (without reload the page) it doesn't.
$("#wallButton").on("click",function(){
var textdocument = document.getElementById('input_post_wall').value
var poster = '<?php echo escape($userLogged->data()->user_id);?>';
var date = '<?php echo $humanize->humanize()->naturalDay(time());?>';
var time = '<?php echo $humanize->humanize()->naturalTime(time());?>';
var timeNow = '<?php echo time();?>';
if(textdocument.length>0){
$.ajax({
url: '/post_process.php',
type: 'post',
dataType: 'json',
data: {'action': 'post', 'userid': userId, 'poster': poster, 'text':textdocument, 'time':timeNow},
success: function(data) {
var LastID = data["postID"];
var image = data["image"];
var sex = data["sex"];
var name = data["name"];
if(image){
image = "/userImages/"+poster+"/"+poster+".jpg";
}else{
if(sex == 'male'){
image = '/images/male_profile.png';
}if (sex == 'female'){
image = '/images/female_profile.png';
}
}
$('.postDiv').prepend('<div class="post" data-post-id= "'+LastID+'"><img src="'+image+'" class="postImg"><div class="formatted-text"><h4>'+name+'</h4><h5>'+textdocument+'</h5><h6>'+date+' - <span>'+time+'</span></h6><a style="font-size:10px;"class="cancelPost" data-cancel-id= "'+LastID+'">cancel</a></div></div>').hide().fadeIn('slow');
textdocument.val('');
},
}); // end ajax call
}else{
alert('no text');
}
});//end click function
//this cancel post from wall but it only works for the messages displayed when the page has been loaded. I will write the code to cancel the message from database when the jquery part works.
$('.cancelPost').each(function (e) {
var $this = $(this);
$this.on("click", function () {
value = $(this).data('cancel-id');
$('div[data-post-id="'+ value +'"]').fadeOut("slow", function(){ $(this).remove(); });
});
});
this is the php function that fetches all the message from the database when page is loaded.
public function presentPost($userId){
$query = $this->_db->prepare("SELECT * FROM wall WHERE user_ident = ? ORDER BY postId DESC");
if ($query->execute(array($userId))){
$result = $query->fetchAll(PDO::FETCH_OBJ);
foreach ($result as $row) {
$user = New User($row->posterId);
if($user->data()->image == 0){
if($user->data()->sex == 'male'){
$image = '/images/male_profile.png';
}else{
$image = '/images/female_profile.png';
}
}else{
$image = "/userImages/$row->posterId/$row->posterId.jpg";
}
echo'<div class="post" data-post-id= "'.$row->postId.'"><img src="'.$image.'" class="postImg"> <div class="formatted-text"><h4>'.$user->data()->name.' '.$user->data()->lastName.'</h4><h5>'.$row->textPost.'</h5><h6>'.$this->_humanize->naturalDay($row->time).' - <span>'.$this->_humanize->naturalTime($row->time).'</span></h5><a style="font-size:10px;"class="cancelPost" data-cancel-id= "'.$row->postId.'">cancel</a></div></div>';
}
}
}
you should use delegates for that
$(document).on("click",".cancelPost", function () {
value = $(this).data('cancel-id');
$('div[data-post-id="'+value+'"]').fadeOut("slow");
$('div[data-post-id="'+value+'"]').remove();
});