I wrote a AJAX search function which grabs the keyword values on key up and fires off the script. My goal is to have it populate the content area every key reordering the results to be in ABC order.
Instead what's happening is the first key fires off and the top result is always this
*ENGRAVING
then the rest of the values under it are in no specific order that I can tell.
I think this has to do with escaping characters?
Any help would be appreciated. Please help me get this to function so as a user searches the content area reorders itself being in order based on the keyword being searched up to the value that has been entered at that time.
On page load 5 results are added to the page then on page scroll more results are added to the page like this,
var assetPath = "<?php echo $assetPath ?>";
var searchPath = "<?php echo $searchPath ?>";
function displayRecords(lim, off) {
jQuery.ajax({
type: "GET",
async: false,
url: assetPath,
data: "limit=" + lim + "&offset=" + off,
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
success: function(html) {
$("#productResults").append(html);
$('#loader_image').hide();
if (html === "") {
$("#loader_message").html('<button data-atr="nodata" class="btn btn-default" type="button">No more records.</button>').show();
} else {
$("#loader_message").html('Loading... Please wait <img src="http://www.example.com/monstroid/wp-content/uploads/2016/02/LoaderIcon.gif" alt="Loading">').show();
}
window.busy = false;
}
});
}
Then when a user wants to search they use this form,
<div class="form-group pull-right">
<input type="text" name="itemID" id="itemID" class="search form-control" placeholder="Search product number">
</div>
Then this ajax function fires off on keyup
$("#itemID").keyup(function (){
var itemID = $(this).val();
var url = searchPath;
$.ajax({
type : "GET",
async : false,
url : url,
data : "itemID=" + encodeURIComponent(itemID),
cache : false,
success: function(html) {
$('#loader_image').hide();
$( "#productResults" ).replaceWith( html );
if (html === "") {
$("#loader_message").html('<p>There were no results that match your search criteria</p>').show();
} else {
$("#loader_message").html('Searching... Please wait <img src="http://www.example.com/monstroid/wp-content/uploads/2016/02/LoaderIcon.gif" alt="Loading">').show();
}
window.busy = false;
}
});
});
which runs this script at searchPath as the path variable
require_once ('Dbconfig.php');
$sql=" SELECT * FROM wuno_inventory WHERE wuno_product like '%".$itemID."%' OR wuno_alternates like '%".$itemID."%' ORDER BY wuno_product ";
try {
$stmt = $DB_con->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $res) {
echo '<tr class="invent">';
echo '<td>' . $res['wuno_product'] . '</td>';
echo '<td>' . $res['wuno_alternates'] . '</td>';
echo '<td>' . $res['wuno_description'] . '</td>';
echo '<td>' . $res['wuno_onhand'] . '</td>';
echo '<td>' . $res['wuno_condition'] . '</td>';
echo '</tr>';
}
}
The initial data populates perfectly in order from what is in the database. So I do not see why there would be problems for this function if it is a escaping situation.
Also the initial data is paginated. Would this cause a problem with the second query? I was thinking maybe since there is so much data it's all being appended to the content instead of replacing it. Maybe the jquery is conflicting?
Try introducing the timeout for your AJAX call. Move your AJAX JS into a separate function first:
function get_search_results(event) {
var itemID = $(event.target).val();
var url = searchPath;
$.ajax({
type : "GET",
async : false,
url : url,
data : "itemID=" + encodeURIComponent(itemID),
cache : false,
success: function(html) {
$('#loader_image').hide();
$( "#productResults" ).replaceWith( html );
if (html === "") {
$("#loader_message").html('<p>There were no results that match your search criteria</p>').show();
} else {
$("#loader_message").html('Searching... Please wait <img src="http://www.example.com/monstroid/wp-content/uploads/2016/02/LoaderIcon.gif" alt="Loading">').show();
}
window.busy = false;
}
});
}
Then add it to your keyup handler:
$("#itemID").keyup(function (){
setTimeout(get_search_results, 200);
});
Related
I'm trying this:
- Onclick on button get this.data-id as id in a DB select
- These data will be dynamically shown in a modal
What I dont know is how to work with ajax, can anyone help?
HTML
<a data-toggle="modal" data-id="'.$method['id'].'" title="Visualizar" class="itemview btn btn-info btn-mini" href="#MethodView">Visualizar</a>
.php
if(!empty($_POST)){
if (isset($_POST['id']) && $_POST['id'] > 0){
$id=$_POST['id'];
GetPaymentMethodView();
}
}
function GetPaymentMethodView() {
global $db;
try{
$query = $db->query("SELECT * FROM payment_methods WHERE id=$id");
$row=$query->fetch(PDO::FETCH_ASSOC);
$result['success'] = true;
$result['result'] = $row;
echo json_encode($result);
return true;
} catch (PDOException $pe) {
return false;
}
}
.js
$('.itemview').click(function (e) {
e.preventDefault();
var uid = $(this).data('id');
$.ajax({
type: "POST",
url: "resources/controllers/get.php",
data: 'id='+uid,
dataType: "json",
success: function (data) {
if (data.success) {
console.log(data.result);
console.log(data.result.id);
} else {
alert("error");
}
}
});
});
In page where you want to display result put something like this
<div class="result"></div>
In try small modification
try{
$query = $db->query("SELECT id, name, bank_info FROM payment_methods WHERE id=$id");
$row=$query->fetch(PDO::FETCH_ASSOC);
$result['success'] = true;
$result['result'] = $row;
echo json_encode($result);
exit;
return true;
}
In js small editing
success: function (data) {
if (data.success) {
//How to show rows in php?
console.log(data.result);
console.log(data.result.id);
var result = data.result;
//prepare markup
var resultHtml = '';
resultHtml += '<p>Id = ' + result.id +'</p>';
resultHtml += '<p>Name = ' + result.name +'</p>';
resultHtml += '<p>Bankinfo = ' + result.bank_info +'</p>';
//Put markup in div
$(".result").html(resultHtml)
} else {
alert("error");
}
}
And see in browser console to understand.
As both code is in same page you can perform this without js/jQuery too, for that just add value of $method['id'] directly to <input>.
See below to understand
Remove value of $method['id'] from <a> tag
<a data-toggle="modal" data-id="" title="Visualizar" class="itemview btn btn-info btn-mini" href="#MethodView">Visualizar</a>
Add value directly to <input> tag
<input type="text" name="methodid" id="methodid" value = "<?php echo $method['id']; ?>" />
And problem solved without js. :) So remove js stuff.
I have an AJAX function that calls a php function to search a mysql database. The script fires off on keyup and the problem is on the first key press the html content is updated but it will not update after the initial keyup event
How do I make the page continuously update the html content with the new data that is coming in after every keyup.
My AJAX function,
var searchPath = "<?php echo $searchPath ?>";
$("#itemID").keyup(function (){
var itemID = $(this).val();
var url = searchPath;
$.ajax({
type : "GET",
async : false,
url : url,
data : "itemID=" + encodeURIComponent(itemID),
cache : false,
success: function(html) {
$('#loader_image').hide();
$( "#productResults" ).replaceWith( html );
if (html === "") {
$("#loader_message").html('<p>There were no results that match your search criteria</p>').show();
} else {
$("#loader_message").html('Searching... Please wait <img src="http://www.example.com/monstroid/wp-content/uploads/2016/02/LoaderIcon.gif" alt="Loading">').show();
}
window.busy = false;
}
});
});
And this is the php behind it all,
<?php
require_once ('Dbconfig.php');
$sql=" SELECT * FROM wuno_inventory WHERE wuno_product like '%".$itemID."%' OR wuno_alternates like '%".$itemID."%' ORDER BY wuno_product ";
try {
$stmt = $DB_con->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $res) {
echo '<tr class="invent">';
echo '<td>' . $res['wuno_product'] . '</td>';
echo '<td>' . $res['wuno_alternates'] . '</td>';
echo '<td>' . $res['wuno_description'] . '</td>';
echo '<td>' . $res['wuno_onhand'] . '</td>';
echo '<td>' . $res['wuno_condition'] . '</td>';
echo '</tr>';
}
}
?>
I am loading data from a mysql table into a html table. I am using AJAX php Jquery to accomplish this. I need to make sure that the way I built this will work regardless of how much data is in the table.
Right now I am working with a table that is 5000 rows long but there will eventually be 88000 rows in this table.
I know if I load all the data on page load this could end up bogging down the server and the load time of the page.
My question is the way my logic is now will it load all the results into the $results and only query the needed amount of rows because it is paginated. Or even though it is paginated is my webpage taking every row in the whole database for load time.
if the whole table is being loaded how can I change the query to only load the data when needed. It loads on page scroll.
Also I need to write a search function. Since the data is paginated would I search the data in $results or query the table with separate search functions? Which way would provide less load times which would cause a bad experience for my user?
The AjAX
<script type="text/javascript">
jQuery(document).ready(function($) {
var busy = true;
var limit = 5;
var offset = 0;
var assetPath = "<?php echo $assetPath ?>"
function displayRecords(lim, off) {
jQuery.ajax({
type: "GET",
async: false,
url: assetPath,
data: "limit=" + lim + "&offset=" + off,
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
success: function(html) {
$("#productResults").append(html);
$('#loader_image').hide();
if (html == "") {
$("#loader_message").html('<button data-atr="nodata" class="btn btn-default" type="button">No more records.</button>').show()
} else {
$("#loader_message").html('Loading... Please wait <img src="http://www.wuno.com/monstroid/wp-content/uploads/2016/02/LoaderIcon.gif" alt="Loading">').show();
}
window.busy = false;
}
});
}
(function($) {
$(document).ready(function() {
if (busy == true) {
displayRecords(limit, offset);
busy = false;
}
});
})( jQuery );
(function($) {
$(document).ready(function() {
$(window).scroll(function() {
// make sure u give the container id of the data to be loaded in.
if ($(window).scrollTop() + $(window).height() > $("#productResults").height() && !busy) {
offset = limit + offset;
displayRecords(limit, offset);
}
});
});
})( jQuery );
});
</script>
This is how I am querying the database
$limit = (intval($_GET['limit']) != 0 ) ? $_GET['limit'] : 5;
$offset = (intval($_GET['offset']) != 0 ) ? $_GET['offset'] : 0;
$sql = "SELECT * FROM wuno_inventory WHERE 1 ORDER BY id ASC LIMIT $limit OFFSET $offset";
try {
$stmt = $DB_con->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $res) {
echo '<tr class="invent">';
echo '<td>' . $res['wuno_product'] . '</td>';
echo '<td>' . $res['wuno_alternates'] . '</td>';
echo '<td>' . $res['wuno_description'] . '</td>';
echo '<td>' . $res['wuno_onhand'] . '</td>';
echo '<td>' . $res['wuno_condition'] . '</td>';
echo '</tr>';
}
}
By transferring a JSON object from the server the limit, offset and html (and maybe others lime status_messsage, etc.) values could be transferred to the client at the same time.
On the client side I meant something like this:
var limit = 5;
var offset = 0;
var assetPath = "<?php echo $assetPath ?>"
function displayRecords(lim, off) {
jQuery.ajax({
type: "GET",
async: false,
url: assetPath,
dataType: "json", // We expect to receive a json object
data: "limit=" + lim + "&offset=" + off,
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
success: function(json) {
limit = json.lim; // corr to $output['lim']
offset = json.offs; // corr to $output['offs']
$("#productResults").append(json.html); // corr to $output['html']
$('#loader_image').hide();
if (json.html == "") {
$("#loader_message").html('<button data-atr="nodata" class="btn btn-default" type="button">No more records.</button>').show()
} else {
$("#loader_message").html('Loading... Please wait <img src="http://www.wuno.com/monstroid/wp-content/uploads/2016/02/LoaderIcon.gif" alt="Loading">').show();
}
window.busy = false;
}
});
}
...and on the server side:
$limit = (intval($_REQUEST['limit']) != 0 ) ? $_REQUEST['limit'] : 5;
$offset = (intval($_REQUEST['offset']) != 0 ) ? $_REQUEST['offset'] : 0;
$sql = "SELECT * FROM wuno_inventory WHERE 1 ORDER BY id ASC LIMIT $limit OFFSET $offset";
// Make sure to handle invalid offset values properly,
// as they are not validated from the last request.
// Prepare the $output structure (will become a json object string)
$output = array(
'lim'=>$limit,
'offs'=>$offset+$limit,
'html'=>''
);
try {
$stmt = $DB_con->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
$output['html'] .= $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $res) {
$output['html'] .= '<tr class="invent">';
$output['html'] .= '<td>' . $res['wuno_product'] . '</td>';
$output['html'] .= '<td>' . $res['wuno_alternates'] . '</td>';
$output['html'] .= '<td>' . $res['wuno_description'] . '</td>';
$output['html'] .= '<td>' . $res['wuno_onhand'] . '</td>';
$output['html'] .= '<td>' . $res['wuno_condition'] . '</td>';
$output['html'] .= '</tr>';
}
}
// Now encode $output as a json object (string) and send it to the client
header('Content-type: application/json; charset=utf-8');
echo json_encode($output, JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_FORCE_OBJECT);
I do this exact thing you want on my site http://www.flixnetforme.com/ where as you can see as you scroll to the bottom of the page the next set of records is loaded. I have over 150,000 records but it only loads 36 at a time when the user scrolls to the bottom of the page.
The way you want to do this is is by loading your first initial records through ajax and not hardcode them into the page.
index.php
$(document).ready(function(){
var last_id;
if (last_id === undefined) {
genres = $("#genres").val();
$.ajax({
type: "POST",
url: "includes/getmorefirst.php?",
data: "genres="+ genres,
success: function(data) {
$( ".append" ).append(data);
}
});
};
};
<html><div class="append"></div></html>
In this example when the user gets to the page and is loaded it calls getmorefirst.php and return the first records.
getmorefirst.php is a file that will load the first set amount of records you want to show when the user gets to the page. In my case I load 36 records at a time when a user scrolls to the bottom of my page.
getmorefirst.php
$sql = "SELECT * FROM table ORDER BY ID ASC LIMIT 36"
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
$last_id = $row['ID'];
echo '<div>'.$row['column'].'</div>';
echo '<div style="display:none" class="last_id" id="'.$last_id.'"';
}
The last_id div is important so that ajax will know the last record sent and which one to pick up after when it loads the next set of 36 records.
.append is the div where I am appending the data from ajax when the user its the bottom.
.last_id is your key to knowing how to load the next set of records. In whatever order you send the records back its important that ajax knows the last ID of the record loaded so it knows where to start loading the next time ajax calls for more records. In my case when the users scrolls to the bottom of the page.
when user scrolls to bottom of index.php
if($(window).scrollTop() === $(document).height() - $(window).height()) {
last_id = $(".last_id:last").attr("id");
$.ajax({
type: "POST",
url: "includes/getmore.php?",
data: "last_id="+ last_id,
success: function(data) {
$( ".append" ).append(data);
}
});
return false;
};
};
last_id = $(".last_id:last").attr("id"); will get the last ID sent.
data: "last_id="+ last_id, will send the last id to getmore.php so it knows the last id of the record sent.
getmore.php
$sql = "SELECT * FROM table WHERE ID > '$last_id' ORDER BY ID ASC LIMIT 36"
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
$last_id = $row['ID'];
echo '<div>'.$row['column'].'</div>';
echo '<div style="display:none" class="last_id" id="'.$last_id.'"';
}
As you can see getmore.php will return the next 36 records but AFTER the last_id sent.
Hope this make sense and gives you a start.
Here is a reduced example of the JSON / AJAX mechanism that I have tested:
HTML (file test.html)
<html>
<head>
<!-- THE NEXT LINE MUST BE MODIFIED -->
<script src="../jquery-1.4.3.min.js" type="text/javascript"></script>
<script type="text/javascript">
var limit = 5;
var offset = 0;
// THE NEXT LINE MUST BE MODIFIED
var assetPath = "http://www.example.com/stackoverflow/test.php"
function displayRecords(lim, off) {
jQuery.ajax({
type: "GET",
url: assetPath,
dataType: "json", // We expect to receive a json object
data: "limit=" + lim + "&offset=" + off,
async: true,
cache: false,
beforeSend: function() {
$("#content").html("");
},
success: function(json) {
limit = json.lim; // corr to $output['lim']
offset = json.offs; // corr to $output['offs']
$("#content").html(json.html);
window.busy = false;
}
});
}
</script>
</head>
<body>
<div id="content"></div>
<div onclick="displayRecords(limit,offset); return false;" style="cursor:pointer">Click to Call</div>
</body>
</html>
PHP (file test.php)
<?php
$limit = (intval($_REQUEST['limit']) != 0 ) ? $_REQUEST['limit'] : 5;
$offset = (intval($_REQUEST['offset']) != 0 ) ? $_REQUEST['offset'] : 0;
// Prepare the $output structure (will become a json object string)
$output = array(
'lim'=>$limit,
'offs'=>$offset+$limit,
'html'=>''
);
$output['html'] .= '<span style="color:red;">limit='.$output['lim'].', offset='.$output['offs'].'</span>';
// Now encode $output as a json object (string) and send it to the client
header('Content-type: application/json; charset=utf-8');
echo json_encode($output, JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_FORCE_OBJECT);
Result
1st time
2nd time
nth time
I want to load more than 10 rows from my table with jQuery, but it's not working.
My php code: (...chat.php?load=archive)
} else if (isset($_GET["load"]) && $_GET["load"] == "archive") {
echo "<script type='text/javascript' src='includes/js/chatArchive.js'></script>";
$limit = (int)$_POST["limit"];
$result = mysql_query("SELECT * FROM `chat` ORDER BY `date` DESC LIMIT ".$limit.", 2");
if (mysql_num_rows($result)) {
while($db = mysql_fetch_array($result)) {
echo "..."; // My datas...
}
echo "<div style='text-align: center; margin: 10px 0 10px 0;'>\n";
echo "<input type='submit' value='Load more rows' class='loadMore'>\n";
echo "</div>\n";
}
}
My JS file: (chatArchive.js)
var limit = 50;
$(document).ready(function() {
$(".loadMore").click(function() {
limit += 10;
$.ajax({
url: "../../../system/functions/chat.php?load=archive",
type: "POST",
data: { "limit" : limit },
success: function() {
alert("Success...");
console.log(limit); // This displayed my console!!!
}
});
});
});
Can anyone point out the problem?
Function which is defined as a callback for success property has an argument, usually called data, which is the returned value from your script. So, you should change your success function as follows:
success: function(data) { // see data here
alert("Success...");
console.log(limit); // This displayed my console!!!
console.log( data ); // check what data contains
}
Also it's a good practice to add error callback, which will indicate that something bad happens:
$.ajax({
url: "../../../system/functions/chat.php?load=archive",
....
error: function() {
alert("Bad thing happenned!");
}
)};
your ajax method is POST but in your php script you check GET request
if (isset($_GET["load"]) && $_GET["load"] == "archive")
Change Your ajax method to GET
I have a table in which the details are fetched from the DB.
if(mysql_num_rows($sql) > 0)
{
$row_count_n=1;
while($rows=mysql_fetch_assoc($sql))
{
extract($rows);
$options1 = select_data_as_options("project_resources", "name", $resource_allocated);
$options2 = select_data_as_options("project_roles", "name", $role);
echo "<tr>";
echo "<td><select name='ra_$row_count_n'><option value=''>-- Select --$options1</option></select></td>";
echo "<td><select name='role_$row_count_n'><option value=''>-- Select --$options2</option></select></td>";
echo "<td><input type='text' name='start_date_tentative_$row_count_n' class='date_one' value=$tentatively_starts_on /></td>";
echo "</tr>";
$row_count_n++;
}
}
I wanted to update the table when required, am doing this using Ajax by collecting data from the form using Jquery and saving it on button click.
$("#save_changes_id").click(function()
{
// To retrieve the current TAB and assign it to a variable ...
var curTab = $('.ui-tabs-active'); // in NEWER jQueryUI, this is now ui-tabs-active
var curTabPanelId = curTab.find("a").attr("href");
if(curTabPanelId == "#tab_dia")
{
var curTab = $('#sub_tabs .ui-tabs-active');
var curTabPanelId = curTab.find("a").attr("href");
}
responseData = doAjaxCall($(curTabPanelId + " form"));
if(responseData == 1)
showMessage('status_msg', 'Project details updated successfully', 'green');
else
showMessage('status_msg', 'Error: Please check all the fields', 'red');
});
function doAjaxCall(objForm)
{
var values = objForm.serialize();
$.ajax({
url: ajaxURL,
type: "post",
data: values,
async: false,
success: function(data)
{
responseData = data;
},
error:function()
{
alert('Connection error. Please contact administrator. Thanks.');
}
});
return responseData;
}
Ajax code is as below:
case "allocate_ba_details":
for($i=1; $i<=$row_count; $i++)
{
$resource = $_REQUEST["ra_$i"];
$role = $_REQUEST["role_$i"];
$start_date_tentative = $_REQUEST["start_date_tentative_$i"];
$already_available_check = mysql_num_rows(mysql_query("select * from project_allocate_ba where project_id = $pdid"));
if($already_available_check > 0)
{
$sql = ("UPDATE project_allocate_ba SET resource_allocated='$resource', role='$role', tentatively_starts_on='$start_date_tentative' WHERE project_id=$pdid");
}
}
echo $sql;
break;
As I am new to this am not sure how to pass the row name in order to update a particular row.
Please suggest a solution. Thanks in advance.
firstly use PDO or some php framework that has nice API to work with mysql. Second don't use success/error callback in jquery is too deprecated. Instanted use done/fail.always.
I understand that you want update row in html table data from the server ?
In success callback simply update the table using jquery text method for jquery object. You don't paste all code so i write example:
in server.php
<?php
[...]
$already_available_check = mysql_num_rows(mysql_query("select * from project_allocate_ba where project_id =" . intval($pdid)));
[...]
echo $already_available_check;
?>
This code return the integer, so in doAjaxCall:
function doAjaxCall(objForm)
{
var values = objForm.serialize();
$.ajax({
url: ajaxURL,
type: "post",
data: values,
async: false,
success: function(data)
{
if(typeof data !== 'undefined' && $.isNumeric(data)) {//check that server send correct anserw
$('whereIsData').text(data);
}
},
error:function()
{
alert('Connection error. Please contact administrator. Thanks.');
}
});
}
Now in success method you populate some DOM element using text method. You cannot simply return data from ajaxCall method because $.ajax is asynchronized method and responseData has value only when ajax request ends, so always return undefined in you example. You must present responseData to the user in success callback method.
For one thing...
$sql = ("UPDATE project_allocate_ba SET resource_allocated='$resource', role='$role', tentatively_starts_on='$start_date_tentative' WHERE project_id=$pdid")
needs single quotes around $pdid
Also don't echo the $sql. Instead do your inspection and form a response.
$response = array();
if(EVERYTHING_IS_GOOD){
$response['status'] = 'good to go';
}else{
$response['status'] = 'it went horribly wrong';
}
echo json_encode($response);