Load more data after scroll PHP AJAX Mysqli - javascript

Hello guys and first of all sorry for my bad english. I just need some help for one script how i can make this script to load more data after scroll when they coming they can see only 5-10 result and when they scroll down will get more.
I will share the code that is being asked and where I need to do it
user_list.php
<?php
$rank_ico = 0;
$sex_ico = 0;
function ico($r, $o){
if($o == 1){
if($r == 1 ){ return '<i class="u_ico fa fa-user" style="font-size:18px;"></i>'; }
else if($r == 2){ return '<i class="v_ico fa fa-heart" style="font-size:16px;"></i>'; }
else if($r == 3){ return '<img src="../images/police-badge.png" class="m_ico" title="Полицай" />'; }
else if($r == 4){ return '<i class="a_ico fa fa-star" style="font-size:17px;"></i>'; }
else if($r == 5){ return '<i class="sa_ico fa fa-star" style="font-size:17px;"></i>'; }
else { return ''; }
}
else {
return '';
}
}
function sex($s, $g){
if($g == 1){
if($s == 1){ return "<img src='/css/themes/Fancy_gold/icon/male-icon.png' width='20' height='20' class='boy' />"; }
else if ($s == 2){ return "<img src='/css/themes/Fancy_gold/icon/female-icon.png' width='20' height='20' class='girl' />"; }
else { return ''; }
}
else {
return '';
}
}
$load_data = 'setting.allow_avatar, setting.allow_private, setting.allow_theme, setting.default_theme, setting.language,
setting.timezone, setting.allow_ignore, setting.allow_friend, setting.ico, users.user_access, users.user_rank, users.user_roomid,
users.user_name, users.user_theme, users.guest';
require("config1.php");
if($data['ico'] == 1){
$rank_ico = 1;
$sex_ico = 1;
}
if($data["user_access"] >= 1 && $access == 'on'){
$data_list = $mysqli->query("SELECT user_name, user_color, user_rank, alt_name, user_tumb, user_status, user_access, user_sex FROM `users` WHERE `user_roomid` = {$data["user_roomid"]} AND `user_status` <= 2 AND `user_access` != 2 AND `user_access` != 0 ORDER BY `user_status` ASC, `user_rank` DESC, `user_name` ASC ");
if ($data_list->num_rows > 0)
{
echo "<div id=\"container_user\">";
echo "<ul>";
while ($list = $data_list->fetch_assoc())
{
if($list["alt_name"] == ""){
$alt = "$notsetyet";
}
else{
$alt = $list["alt_name"];
}
$uavatar = $list['user_tumb'];
if($uavatar == "default_avatar_tumb.png" || $list['user_rank'] < $data['allow_avatar']){
$avatar_path = "$icon_path";
$uavatar = "default_avatar_tumb.png";
}
else {
$avatar_path = "avatar";
}
$avatar = "<img class=\"avatar_userlist\" src=\"$avatar_path/$uavatar\"/>";
if($list['user_status'] == 1){
$away = $list['user_color'];
}
else {
$away = "away";
}
if($list['user_access'] == 1){
echo '<li class="users_option">
<div class="open_user hover_element sub_element">
' . $avatar . '<p title="' . $alt . '" class="' . $away . ' usertarget" id="' . $list[user_name] . '"><s>' .$list["user_name"] . '</s></p>
</div>
<div class="option_list">
<ul class="user_option_list" value="' . $list[user_name] . '">';
echo "<li class=\"user_option_separator get_info\" value=\"get_info\">$usinfo</li>";
if($list['user_name'] !== $data['user_name']){
if($data['user_rank'] >= 3){
echo "<li class=\"user_option_separator get_unmute\" value=\"get_unmute\">$usunmute</li>";
}
if($data['user_rank'] > 4){
echo "<li class=\"user_option_separator get_kill\" value=\"get_kill\">$usdelete</li>";
}
}
echo "</ul>
</div>
</li>";
}
else {
echo "<li class=\"users_option\">
<div class=\"open_user hover_element sub_element\">
$avatar<p title=\"$alt\" class=\"$away usertarget\" id=\"{$list["user_name"]}\">{$list["user_name"]} " . ico($list['user_rank'], $rank_ico) . sex($list['user_sex'], $sex_ico) . "</p>
</div>
<div class=\"option_list\">
<ul class=\"user_option_list\" value=\"{$list["user_name"]}\">";
echo "<li class=\"user_option_separator get_info\" value=\"get_info\">$usinfo</li>";
if($list['user_name'] !== $data['user_name']){
if($list['user_rank'] >= $data['allow_private'] && $data['user_rank'] >= $data['allow_private']){
echo "<li class=\"user_option_separator send_private\" value=\"{$list['user_name']}\">$usprivate</li>";
}
if( $list['user_rank'] < 3 && $data['guest'] != 1 && $data['user_rank'] >= $data['allow_ignore']){
echo "<li class=\"user_option_separator get_ignore\" value=\"get_ignore\">$usignore</li>";
}
if( $data['guest'] != 1 && $data['user_rank'] >= $data['allow_friend']){
echo "<li class=\"user_option_separator get_friends\" value=\"get_friends\">$usfriends</li>";
}
if($data['user_rank'] >= 3){
echo "<li class=\"user_option_separator get_mute\" value=\"get_mute\">$usmute</li>";
echo "<li class=\"user_option_separator get_kick\" value=\"get_kick\">$uskick</li>";
}
if($data['user_rank'] > 3){
echo "<li class=\"user_option_separator get_ban\" value=\"get_ban\">$usban</li>";
}
if($data['user_rank'] > 4){
echo "<li class=\"user_option_separator get_kill\" value=\"get_kill\">$usdelete</li>";
}
}
echo "</ul>
</div>
</li>";
}
}
echo "</ul><div class=\"clear\"></div></div>";
}
}
else {
echo "<ul>
<li>Room empty</li>
</ul>";
}
function.js
user_reload = function()
{
if(firstLoad == 1 && width > 1024){
$('#chat_panel').animate({right:"+="+optionSize},400);
dataControl = "1";
$.ajax({
url: "system/user_list.php",
cache: false,
success: function(html){
$("#chat_panel .panel_element").html(html);
},
});
firstLoad = "0";
}
else if (dataControl != 1){
return false;
}
else if ($('.option_list:visible').length){
return false;
}
$.ajax({
url: "system/user_list.php",
cache: false,
success: function(html){
$("#chat_panel .panel_element").html(html);
},
});
}

Related

If I click on Tab, it doesn't response. Why?

Problem is I cannot click the Tabs on the website and If i click on Tabs; it show
Uncaught Type Error: Cannot set properties of null (setting 'value').
Is there any way to fix this? Also, I am a beginner and I don't know how to fix this. Codes are written in PHP and Javascript.
<?php
// session_start();
require("checklogin.php");
$toolsname = "Matrix Setup";
$toolsnamepath = "index.php";
$userlogin = $loginname;
$usrgroup = $_SESSION["usrgrp"];
$str_tab = isset($_POST["str_tab"])? $_POST["str_tab"] : "";
$winwidth = isset($_POST["winwidth"])? $_POST["winwidth"] : "";
$ch = isset($_POST["ch"])? $_POST["ch"] : "";
$badgeno = isset($_SESSION["badgeno"])? $_SESSION["badgeno"] : "";
if($str_tab == ""){
$str_tab = isset($_GET["str_tab"])? $_GET["str_tab"] : "";
}
if($winwidth == ""){
$winwidth = isset($_GET["winwidth"])? $_GET["winwidth"] : "";
}
if($ch == ""){
$ch = isset($_GET["ch"])? $_GET["ch"] : "";
}
echo "<html>";
echo "<head><title>$toolsname</title>";
echo "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=5\">";
echo "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">";
echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"\web/css/lotmgt_edge.css\"/>";
echo "<script src=\"lotmgt.js\"></script>\n";
echo "<script src=\"setup/setup.js\"></script>\n";
echo "<script src=\"productmatrix/productmatrix.js\"></script>\n";
echo "<script src=\"simulator/simulator.js\"></script>\n";
echo "<script src=\"addmatrix/addmatrix.js\"></script>\n";
echo "<script src=\"addAVImatrix/addmatrix.js\"></script>\n";
echo "<script src=\"\web/js/eregister/pointer.js\" type=\"text/javascript\"></script>";
echo "</head>";
echo "<body onload=OnLoad('" . $ch . "','" . $badgeno . "')>";
//include($_SERVER['DOCUMENT_ROOT']."\library\common\apewsheader.php");
//include($_SERVER['DOCUMENT_ROOT']."\library\common\db_config.inc");
//include($_SERVER['DOCUMENT_ROOT']."\library\common\standard_defines.inc");
include("//sgewsnant21.amk.st.com/ewsweb/wwwroot/library/common7/apewsheader.php");
include("//sgewsnant21.amk.st.com/ewsweb/wwwroot/library/common7/db_config.inc");
include("//sgewsnant21.amk.st.com/ewsweb/wwwroot/library/common7/standard_defines.inc");
include("editme.php");
echo "<form name=\"lotmgt\" method=\"post\" target=\"_self\" onsubmit=\"return false;\">";
echo "<div style=\"position:relative; top:20px;\">";
echo "<table cellpadding=\"3\" cellspacing=\"0\" border=\"0\" width=\"99%\">";
echo "<tr>";
echo "<td>";
for($c=0;$c<count($ary_tab);$c++) {
$class_tab = (($ch=="ProductMatrix" && $ary_tab[$c]=="Product Matrix" && (!isset($str_tab) || $tr_tab=="")) || ($ch=="SocketSimulator" && $ary_tab[$c]=="Socket Simulator" && (!isset($str_tab) || $str_tab=="")) || ($ch=="AVIMatrixAdd" && $ary_tab[$c]=="AVI Matrix Add" && (!isset($str_tab) || $str_tab=="")) || ($ch=="SetupPostTest" && $ary_tab[$c]=="Setup PostTest" && (!isset($str_tab) || $str_tab=="")) || ($ch=="Setup" && $ary_tab[$c]=="Setup" && (!isset($str_tab) || $str_tab=="")) || (($c==0 && !isset($str_tab)) && $ch=="") || $ary_tab[$c] == $str_tab)? "link_tab_slct" : "link_tab";
echo "" . $ary_tab[$c] . "";
}
echo"</td>";
echo"</tr>";
echo"</table>";
echo "</div>";
//echo $str_tab;
if($str_tab != ""){
switch($str_tab){
case "Setup":
include("setup/setup.php");
break;
case "Setup PostTest":
include("setup/setup.php");
break;
case "Setup1":
include("setup1/setup.php");
break;
case "Product Matrix":
include("productmatrix/productmatrix.php");
break;
case "Socket Simulator":
// include("simulator/simulator.php");
include("simulator/Socket_simulator.php");
break;
// case "Matrix Add":
// include("addmatrix/addmatrix.php");
// break;
case "AVI Matrix Add":
include("addAVImatrix/addmatrix.php");
break;
}
}
else {
if ($ch=="ProductMatrix") {
include("productmatrix/productmatrix.php");
}
else if($ch=="SocketSimulator"){
// include("simulator/simulator.php");
include("simulator/Socket_simulator.php");
}
else if($ch=="AVIMatrixAdd"){
include("addAVImatrix/addmatrix.php");
}
else if($ch=="Setup"){
include("setup/setup.php");
}
else if($ch=="SetupPost6E"){
include("setup/setup.php");
}
else{
include("setup/setup.php");
}
}
//common
echo "<input type=\"hidden\" name=\"str_tab\" value=\"" . $str_tab . "\">";
echo "<input type=\"hidden\" name=\"winwidth\" value=\"" . $winwidth . "\">";
echo "<input type=\"hidden\" name=\"username\" value=\"" . $loginname . "\">";
echo "</form>";
flush();
mysqli_close($conn);
echo "</body>";
echo "</html>";
?>
Above codes are index.php codes.
var winplanproducttoentity = '';
var winupdateauto = '';
var winupdatebytester = '';
var winupdatebyproduct = '';
var winupdatestatus = '';
var wintestlot = '';
var winassignlot = '';
var winshowlot = ''
var winchecksicom = '';
var w;
var winwidth = window.screen.width;
var div = new Array('outputdiv','setupdiv');
//var div = new Array('outputdiv','setupdiv','availdiv');
var reqHttp = InitRequest();
var reqHttp1 = InitRequest();
var reqHttp2 = InitRequest();
var reqHttp3 = InitRequest();
function InitRequest() {
var request=null;
try {
request=new XMLHttpRequest();
}
catch (e) {
try {
request=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e){
request=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return request;
}
function AsynReqData(request,url,fn) {
request.open("GET", url + '&sid=' + Date() + Math.random(), true);
request.onreadystatechange = eval(fn);
request.send(null);
}
function SynReqData(request,url) {
request.open("GET", url + '&sid=' + Date() + Math.random(), false);
request.send(null);
return request.responseText;
}
function DisplayTab(tabname,tabid) {
document.getElementById(tabid).value = tabname; // this is the $str_tab
document.lotmgt.submit();
}
function OnLoad(ch,badgeno){
var tab = document.lotmgt.str_tab.value; // this is the $str_tab from DisplayTab function
w = (winwidth < 1280)? 1280 : winwidth;
if((tab=='' & ch=='') || tab=='Setup' || (ch=='Setup' & tab=='')) {
var p_1 = "checked";
var T_0 = "checked";
var zmiss = "checked";
for(var i=0; i<div.length; i++) {
document.getElementById(div[i]).className = 'hide';
}
// var wd = (128*5) - 10;
var wd = (128*7.5) - 50;
var lf = 0;
document.getElementById('filterdiv').style.width = wd + 'px';
document.getElementById('filterdiv').style.left = lf + 'px';
wd = (128*5.5) - 80;
lf = (128*5) - 10; // lf = (128*7) - 20;
document.getElementById('waferdiv').style.width = wd + 'px';
document.getElementById('waferdiv').style.left = lf + 'px';
// AsynReqData(reqHttp,'setup/content_wafer.php?site=','UpdateWafer');
AsynReqData(reqHttp1,'setup/content_filter.php?site=' + '' + '&badgeno=' + badgeno + '&p_1=' + p_1 + '&T_0=' + T_0 + '&zmiss=' + zmiss,'UpdateFilter');
}
else if (tab=='Product Matrix' || (ch=='ProductMatrix' & tab=='')){
AsynReqData(reqHttp,'productmatrix/content_filter.php?area=','UpdatePMFilter');
}
// else if (tab=='Matrix Simulator' || (ch=='MatrixSimulator' & tab=='')){
// // AsynReqData(reqHttp,'simulator/content_filter.php?area=','UpdateSIMFilter');
// }
else if (tab=='Setup PostTest' || (ch=='SetupPostTest' & tab=='')){
var p_1 = "checked";
var T_0 = "checked";
var wd = (128*9) - 50;
var lf = 0;
document.getElementById('filterdiv').style.width = wd + 'px';
document.getElementById('filterdiv').style.left = lf + 'px';
AsynReqData(reqHttp1,'setup/content_filter1.php?site=' + '' + '&badgeno=' + badgeno + '&p_1=' + p_1 + '&T_0=' + T_0,'UpdateFilter');
}
}
//shared functions
function ManagePopup(except){
var mywin = new Array('winplanproducttoentity','winupdateauto','winupdatebytester','winupdatebyproduct','winupdatestatus','wintestlot','winassignlot','winshowlot','winchecksicom');
for(var i=0; i<mywin.length; i++) {
var win = window[mywin[i]];
if (mywin[i] == except){
if(!win.closed && win.location) win.focus();
}
else{
if(!win.closed && win.location) win.close();
}
}
}
function PlanProductToEntity(product,type){
var w = 300;
var h = 600;
var winl = (screen.width - w) / 2;
var wint = (screen.height - h) / 2;
var winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,copyhistory=no';
ManagePopup('winplanproducttoentity');
winplanproducttoentity = this.open('../lotmgt/wip/pop_assignproduct.php?product=' + product + '&type=' + type, 'winplanproducttoentity', winprops);
}
Above codes are Javascript codes. Error says in Javascript and How to fix that?
The error occurs in the JS code and is due to the HTML generated in PHP which is missing an id attribute.
You seem to get the error here: document.getElementById(tabid).value = tabname; because document.getElementById(tabid) is null.
When it looks for the element with id str_tab it doesn't find it. The only element in the HTML which could be the desired one has the attribute name="str_tab" and it's your hidden field. You have to add the missing id="str_tab" attribute to this hidden field.

Text message won't clear even after sending the text in chat

I'm working on a chat box and it's working fine but when we enter the text message and sent it after the message is sent it won't clear automatically. It will remain there even after posting the text, we need to clear it manually.
I have tried to change some code but couldn't solve the issue.
Code which I'm using in this.
<div class="row">
<div class="pull-left">
<h3><?php echo sprintf($this->lang->line("conv_with"), $user["username"]); ?></h3>
</div>
</div>
<div class="row">
<div class="main_container clearfix">
<div class="ibox-content-no-bg">
<div class="chat-discussion">
<?php
$last_conv = $last_conv->result_array();
$last_conv = array_reverse($last_conv);
foreach($last_conv as $message):
$activity_thumb = $message["thumb_url"];
if($message["thumb_url"] == "" || $message["photostatus"] == 0) {
$activity_thumb = base_url() . "images/avatar.png";
}
?>
<?php
if($message["user_id"] == $this->session->userdata("user_id"))
$align_message = "left";
else
$align_message = "right";
?>
<div class="chat-message clearfix <?php echo $align_message; ?>" data-id="<?php echo $message["id"]; ?>">
<?php
if($message["gender"] == 0) {
$gender_user_color = "male_color";
} else {
$gender_user_color = "female_color";
}
?>
<a class="nailthumb-msg-container" href="<?php echo base_url("user/profile/".$message["user_id"]) ?>"><img width="62" alt="" src="<?php echo $activity_thumb; ?>" class="message-avatar"></a>
<div class="message">
<a class="message-author <?php echo $gender_user_color; ?>" href="<?php echo base_url("user/profile/".$message["user_id"]) ?>"><?php echo $message["username"] ?></a>
<span class="message-date text-muted pm-date" title="<?php echo $message["date"]; ?>Z"></span>
<span class="message-content">
<?php echo $message["content"]; ?>
</span>
<span class="message-date-mob text-muted pm-date" title="<?php echo $message["date"]; ?>Z"></span>
</div>
</div>
<?php
endforeach;
?>
</div>
<div class="chat-message-form">
<div class="form-group">
<p class="lead emoji-picker-container">
<textarea id="pm-write" class="form-control message-input pm-write-answer-textarea" placeholder="<?php echo $this->lang->line("enter_message_here_placeholder"); ?>" name="message" data-emojiable="true"></textarea>
</p>
</div>
<div class="btn-reply-placeholder">
<a class="btn btn-primary btn-send-reply" href="#" data-user-id="<?php echo $user["uid"]; ?>" data-conv-id="<?php echo $current_conv->id; ?>"><?php echo $this->lang->line("send_reply_btn"); ?></a>
</div>
</div>
</div>
</div>
</div>
AJAX
$(document).ready(function() {
$('.nailthumb-msg-container').nailthumb();
$(".pm-date").timeago();
$(".message").emoticonize();
$(".chat-discussion").scrollTop(100000);
window.setInterval(function(){
var last_message_id = $(".chat-message:last").attr("data-id");
// Live refresh
$.ajax({
url: base_url + "pm/refresh_conv",
type: 'POST',
data: {conv_id : conv_id, last_message_id: last_message_id},
success: function(data) {
$.each(data.last_messages, function(i, item) {
var message = item;
var avatar = "";
if(message.thumb_url == null || message.photostatus == 0) {
avatar = base_url + "images/avatar.png";
} else {
avatar = base_url + message.thumb_url;
}
if(message.gender == 0) {
var gender_user_color = "male_color";
} else {
var gender_user_color = "female_color";
}
if(message.user_id == user_id) {
var msg_dir = "left";
} else {
var msg_dir = "right";
}
var block_msg = '<div class="chat-message ' + msg_dir + '" data-id="' + message.mid + '">';
block_msg += '<a class="nailthumb-msg-container" href="' + base_url + 'user/profile/' + message.user_id + '"><img width="62" alt="" src="' + avatar + '" class="message-avatar" /></a>';
block_msg += '<div class="message">';
block_msg += '<a class="message-author ' + gender_user_color + '" href="' + base_url + 'user/profile/' + message.user_id + '">' + message.username + '</a>';
block_msg += '<span class="message-date text-muted pm-date" title="' + message.date + 'Z"></span>';
block_msg += '<span class="message-content">';
block_msg += message.content;
block_msg += '</span>';
block_msg += '</div>';
block_msg += '</div>';
$(".chat-message").last().after(block_msg);
$('.nailthumb-msg-container').nailthumb();
$(".pm-date").timeago();
$(".message").emoticonize();
$(".chat-discussion").scrollTop(100000);
});
}
});
}, 2000);
$(".btn-send-reply").click(function(e) {
e.preventDefault();
$(':input[name="pmwrite"]').val(null);
var conv_id = $(this).attr("data-conv-id");
var user_id = $(this).attr("data-user-id");
var content = $(".emoji-wysiwyg-editor").html();
$(this).html('<i class="fa fa-circle-o-notch fa-spin"></i>');
$(this).addClass("disabled");
var that = $(this);
$.ajax({
url: base_url + "pm/send_reply",
type: 'POST',
data: {conv_id : conv_id, content: content, user_id : user_id},
success: function(data) {
var res = data.result;
if(res == 999) {
alert(not_logged_in_str);
that.html(send_reply_str);
that.removeClass("disabled");
} else if(res == 998) {
alert(write_something_str);
that.html(send_reply_str);
that.removeClass("disabled");
} else if(res == 500) {
alert(cant_demo_mode_str);
that.html(send_reply_str);
that.removeClass("disabled");
} else if(res == 997) {
alert(conv_not_exist_str);
that.html(send_reply_str);
that.removeClass("disabled");
} else if(res == 996) {
alert(user_blocked_you_str);
that.html(send_reply_str);
that.removeClass("disabled");
} else {
var avatar = "";
if(data.user.thumb_url == null || data.user.photostatus == 0) {
avatar = base_url + "images/avatar.png";
} else {
avatar = base_url + data.user.thumb_url;
}
$(".pm-write-answer-textarea").val("");
if(data.user["gender"] == 0) {
var gender_user_color = "male_color";
} else {
var gender_user_color = "female_color";
}
$('.nailthumb-msg-container').nailthumb();
$(".pm-date").timeago();
that.html(send_reply_str);
that.removeClass("disabled");
$(".chat-discussion").scrollTop(100000);
}
}
});
});
String.prototype.replaceArray = function(find, replace) {
var replaceString = this;
for (var i = 0; i < find.length; i++) {
replaceString = replaceString.replace(find[i], replace[i]);
}
return replaceString;
};
});
I expect the textarea to be cleared after someone send t the message but actual is the text will remain in textarea even after the message is sent.
I assume that this $(".emoji-wysiwyg-editor") is your element for your content. since this is the one you called in
var content = $(".emoji-wysiwyg-editor").html();
Try clearing this element after success by using this code since you're using a jquery here.
$(".emoji-wysiwyg-editor").html('');
Just add this line at the start of your AJAX success() function
$('#pm-write').empty();
Using pure Javascript
document.getElementById('pm-write').innerHTML = "";
It would look like this
$.ajax({
url: base_url + "pm/send_reply",
type: 'POST',
data: {conv_id : conv_id, content: content, user_id : user_id},
success: function(data) {
var res = data.result;
$('#pm-write').empty(); //Clean the textarea
//Other code
}
});
Using javascript, you can easily achieve this by setting an event listener on the text-area like this
document.addEventListener("DOMContentLoaded", function() {
var submitBtn = document.getElementsByClassName("btn-send-reply")[0];
submitBtn.addEventListener("click", function(){
document.getElementsByName("message")[0].value = "";
});
});
or in jQuery
$(document).ready(function(){
$('.btn-send-reply').click(function(){
$( "input[name*='message']" ).val("");
})
})

JavaScript to change a multi level <select> into accordion

in my item post page, their is an for selecting main category and than after selecting it shows relevant sub category.
i want to change this in to a accordion. please help me how to change this. so when a user come to my website and try to post ad he should be shown accordion for selecting the main category and sub category. please help me to achieve this by modify the code or using java-script to achieve this.
the code `
$categoryID = Params::getParam('catId');
if( osc_item_category_id() != null ) {
$categoryID = osc_item_category_id();
}
if( Session::newInstance()->_getForm('catId') != '' ) {
$categoryID = Session::newInstance()->_getForm('catId');
}
$subcategoryID = '';
if( !Category::newInstance()->isRoot($categoryID) ) {
$subcategoryID = $categoryID;
$category = Category::newInstance()->findRootCategory($categoryID);
$categoryID = $category['pk_i_id'];
}
if($categories == null) {
if(View::newInstance()->_exists('categories')) {
$categories = View::newInstance()->_get('categories');
} else {
$categories = osc_get_categories();
}
}
if ($item == null) { $item = osc_item(); }
$subcategory = array();
?>
<select id="parentCategory" name="parentCatId">
<option value=""><?php _e('Select a category', 'modern'); ?></option>
<?php foreach($categories as $_category) {
$selected = ( (isset($item["fk_i_category_id"]) && $item["fk_i_category_id"] == $_category['pk_i_id']) || (isset($categoryID) && $categoryID == $_category['pk_i_id']) );
if($selected) { $subcategory = $_category; };
echo '<option value="'.$_category['pk_i_id'].'" '.($selected ? 'selected="selected"' : '' ).'>'.$_category['s_name'].'</option>';
} ?>
</select>
<select id="catId" name="catId">
<?php
if(!empty($subcategory)) {
if( count($subcategory['categories']) > 0 ) {
echo '<option value="">'.__('Select Subcategory', 'modern').'</option>';
foreach($subcategory['categories'] as $c) {
$selected = ( (isset($item["fk_i_category_id"]) && $item["fk_i_category_id"] == $c['pk_i_id']) || (isset($subcategoryID) && $subcategoryID == $c['pk_i_id']) );
echo '<option value="'.$c['pk_i_id'].'" '.($selected ? 'selected="selected"' : '' ).'>'.$c['s_name'].'</option>';
}
} else {
echo '<option value="'.$categoryID.'" >'._e('No Subcategory', 'modern').'</option>';
}
} else {
echo '<option value="">'._e('Select Subcategory', 'modern').'</option>';
}
?>
</select>
<script type="text/javascript" charset="utf-8">
<?php
foreach($categories as $c) {
if( count($c['categories']) > 0 ) {
$subcategory = array();
for($i = 0; $i < count($c['categories']); $i ) {
$subcategory[] = array($c['categories'][$i]['pk_i_id'], $c['categories'][$i]['s_name']);
}
printf('var categories_%1$s = %2$s;', $c['pk_i_id'], json_encode($subcategory));
echo PHP_EOL;
}
}
?>
$(document).ready(function(){
$("#parentCategory").bind('change', function(){
var categoryID = $(this).val();
if( categoryID == 0 ) {
var options = '<option value="' categoryID '" selected=""><?php _e('No Subcategory', 'modern'); ?></option>';
}
categories = window['categories_' categoryID];
if( categories==null || !$.isArray(categories) ) {
var options = '<option value="' categoryID '" selected=""><?php _e('No Subcategory', 'modern'); ?></option>';
} else {
var options = '<option value="' categoryID '" selected=""><?php _e('Select Subcategory', 'modern'); ?>...</option>';
$.each(categories, function(index, value){
options = '<option value="' value[0] '">' value[1] '</option>';
});
};
$('#catId').html(options);
$("#catId").next("a").find(".select-box-label").text('Select a Sub Category...');
$("#catId").change();
$("div#uniform-catId.selector").css('visibility', 'visible');
});
// In case of error and Category already chosen, let's show the Subcategory selector
if($("div#uniform-parentCategory.selector select").val()) {
$("div#uniform-catId.selector").css('visibility', 'visible');
}
});
</script>
<?php
}
?>`
If this is related to osclass, in item-post.php from bender (for example), use
<?php ItemForm::category_select(null, null, __('Select a category', 'bender')); ?>
instead of
<?php ItemForm::category_multiple_selects(); ?>
PS. This is not a js solution.

Ajax request to php working on localhost but not on live server

I am new with AJAX and was just testing a simple chat application between two user roles in a core php based application. My application works fine on WAMP but the same application is not working on my live server. On live server I am not receiving any errors in console. I know the following might not be the best practice but this is just to test the ajax functionality and i can not figure out where the problem is. Thanks in advance for reading the long code.
Update : i forgot to add that sending messages is working and i can see the same in my db but the refresh function is not working
Below is my js
$('#msgsend').click(function() {
var x;
var x=document.getElementById("texty").value;
var sendDATA = new Array();
sendDATA[0] = 'sendMessage';
sendDATA[1] = '<?php echo $_GET['token']; ?>';
sendDATA[2] = x;
<?php if(isset($_SESSION['tid'])) { ?>
sendDATA[3]='tid';
<?php } else { ?>
sendDATA[3]='uid';
<?php } ?>
sendDATA[4] = '<?php echo isset($_SESSION['tid'])?$_SESSION['tid']:$_SESSION['id'];?>';
$.ajax({
type: "POST",
url: "helpers/chathelper.tpl.php",
data: {'sendDATA': sendDATA},
success: function(res){
document.getElementById("texty").value = "";
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
});
window.setInterval(function(){
/// call your function here
var chatDATA = new Array();
chatDATA[0] = 'refreshChat';
chatDATA[1] = '<?php echo $_GET['token']; ?>';
chatDATA[2] = '<?php echo isset($_SESSION['tid'])?$_SESSION['tid']:$_SESSION['id'];?>';
<?php if(isset($_SESSION['tid'])) { ?>
chatDATA[3]='tid';
<?php } else { ?>
chatDATA[3]='uid';
<?php } ?>
$.ajax({ url: 'helpers/chathelper.tpl.php',
data: {'chatDATA' : chatDATA },
type: 'post',
dataType:'html',
success: function(data){
if(data !== '')
{console.log(data);
$('#chat-main').append(data);
$('#chat-main').animate({scrollTop: $('#chat-main').prop("scrollHeight")}, 500);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("Status: " + textStatus); console.log("Error: " + errorThrown);
}
});
}, 2000);
});
and below is my php
$chatDATA=$_POST['chatDATA'];
$sendDATA=$_POST['sendDATA'];
$uid;$tid;$mes;$token;$action;$type;
if(isset($chatDATA))
{
$action=$chatDATA[0];
$token=$chatDATA[1];
if(!strcmp($chatDATA[3],'uid'))
$uid=$chatDATA[2];
else if(!strcmp($chatDATA[3],'tid'))
$tid=$chatDATA[2];
$type=$chatDATA[3];
}
else if(isset($sendDATA))
{
$action=$sendDATA[0];
$token=$sendDATA[1];
$mes=$sendDATA[2];
$type=$sendDATA[3];
if(!strcmp($chatDATA[3],'uid'))
$uid=$chatDATA[4];
else if(!strcmp($chatDATA[3],'tid'))
$tid=$chatDATA[4];
}
switch($action){
case "sendMessage" :
sendmessage($uid,$tid,$mes,$token,$con);
break;
case "refreshChat" :
refresh($uid,$tid,$token,$type,$con);
break;
}
function sendmessage($uid,$tid,$mes,$token,$con){
$mes=mysqli_real_escape_string($con,$mes);
$data = mysqli_query($con,"SELECT * FROM `chat` WHERE `token` = '".$token."'");
$key=mysqli_fetch_array($data,MYSQLI_BOTH);
if($tid!=null && ($key[2]==$tid))
{
$trav= getTraveler($tid,$con);
$mes=$trav[3].' : '.$mes;
$res2 = mysqli_query($con,"INSERT INTO `chat` (`uid`, `tid`, `jid`, `message`, `sender`, `unread`, `token`) VALUES('".$key[1]."','".$key[2]."','".$key[3]."','".$mes."','tid','0','".$token."')");
}
else if($uid!=null && ($key[1]==$uid))
{
$user=getUser($uid,$con);
$mes=$user[3].' : '.$mes;
$res2 = mysqli_query($con,"INSERT INTO `chat` (`uid`, `tid`, `jid`, `message`, `sender`, `unread`, `token`) VALUES('".$key[1]."','".$key[2]."','".$key[3]."','".$mes."','uid','0','".$token."')");
}
else
return false;
}
function refresh($uid,$tid,$token,$type,$con)
{
if(isset($uid))
$chat_read = mysqli_query($con,"select * from `chat_read` where `token`='" . $token . "' AND `uid`='".$uid."'");
else if (isset($tid))
$chat_read = mysqli_query($con,"select * from `chat_read` where `token`='" . $token . "' AND `tid`='".$tid."'");
$get_read = mysqli_fetch_row($chat_read);
if (isset($get_read) && isset($type) && isset($uid)) {
$read_sql = "SELECT * FROM `chat` WHERE `token`='" . $token . "' AND `id`>'" . $get_read[2] . "' ";
$unread = mysqli_query($con,$read_sql);
$html_output = "";
$all_results = array();
$last_id_updated;
while ($message = mysqli_fetch_array($unread,MYSQLI_BOTH)) {
$all_results[] = $message;
}
$size_arr=mysqli_num_rows($unread);
for ($i=0; $i < $size_arr; $i++) {
if ($all_results[$i]['sender'] == "uid")
$html_output .= '<li class="left clearfix"> <div class="chat-body1 clearfix"><p>'.$all_results[$i][message].'</p> <div class="chat_time pull-right">'.$all_results[$i][time].'</div> </div> </li>';
else if ($all_results[$i]['sender'] == "tid")
$html_output .= '<li class="left clearfix admin_chat"> <div class="chat-body1 clearfix"> <p>'.$all_results[$i][message].'</p> <div class="chat_time pull-left">'.$all_results[$i][time].'</div> </div> </li>';
$last_id_updated=$all_results[$i]['id'];
}
if($size_arr) {
if(isset($uid))
$read_update="UPDATE `chat_read` SET `last_id_uid`= '".$last_id_updated."',`uid`='".$uid."' WHERE token='".$token."'";
elseif (isset($tid))
$read_update="UPDATE `chat_read` SET `last_id_tid`= '".$last_id_updated."',`tid`='".$tid."' WHERE token='".$token."'";
$res=mysqli_query($con,$read_update);}
echo $html_output;
}
if (isset($get_read) && isset($type) && isset($tid)) {
$read_sql = "SELECT * FROM `chat` WHERE `token`='" . $token . "' AND `id`>'" . $get_read[3] . "' ";
$unread = mysqli_query($con,$read_sql);
$html_output = "";
$all_results = array();
$last_id_updated;
while ($message = mysqli_fetch_array($unread,MYSQLI_BOTH)) {
$all_results[] = $message;
}
$size_arr=mysqli_num_rows($unread);
for ($i=0; $i < $size_arr; $i++) {
if ($all_results[$i]['sender'] == "uid")
$html_output .= '<li class="left clearfix"> <div class="chat-body1 clearfix"><p>'.$all_results[$i][message].'</p> <div class="chat_time pull-right">'.$all_results[$i][time].'</div> </div> </li>';
else if ($all_results[$i]['sender'] == "tid")
$html_output .= '<li class="left clearfix admin_chat"> <div class="chat-body1 clearfix"> <p>'.$all_results[$i][message].'</p> <div class="chat_time pull-left">'.$all_results[$i][time].'</div> </div> </li>';
$last_id_updated=$all_results[$i]['id'];
}
if($size_arr) {
if(isset($uid))
$read_update="UPDATE `chat_read` SET `last_id_uid`= '".$last_id_updated."',`uid`='".$uid."' WHERE token='".$token."'";
elseif (isset($tid))
$read_update="UPDATE `chat_read` SET `last_id_tid`= '".$last_id_updated."',`tid`='".$tid."' WHERE token='".$token."'";
$res=mysqli_query($con,$read_update);}
echo $html_output;
}
}
I was making some mistakes in DB query getting null response so i wrote the whole script again and took care of all the e and was getting null response Below is the Working Script.
My JS
$('#msgsend').click(function() {
var x;
var x=document.getElementById("texty").value;
var sendDATA = new Array();
sendDATA[0] = 'sendMessage';
sendDATA[1] = '<?php echo $_GET['token']; ?>';
sendDATA[2] = x;
<?php if(isset($_SESSION['tid'])) { ?>
sendDATA[3]='tid';
<?php } else { ?>
sendDATA[3]='uid';
<?php } ?>
sendDATA[4] = '<?php echo isset($_SESSION['tid'])?$_SESSION['tid']:$_SESSION['id'];?>';
$.ajax({
type: "POST",
url: "helpers/chathelper.tpl.php",
data: {'sendDATA': sendDATA},
success: function(res){
document.getElementById("texty").value = "";
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
});
window.setInterval(function(){
/// call your function here
var chatDATA = new Array();
chatDATA[0] = 'refreshChat';
chatDATA[1] = '<?php echo $_GET['token']; ?>';
chatDATA[2] = '<?php echo isset($_SESSION['tid'])?$_SESSION['tid']:$_SESSION['id'];?>';
<?php if(isset($_SESSION['tid'])) { ?>
chatDATA[3]='tid';
<?php } else { ?>
chatDATA[3]='uid';
<?php } ?>
$.ajax({ url: 'helpers/chathelper.tpl.php',
data: {'chatDATA' : chatDATA },
type: 'post',
dataType:'html',
success: function(data){
if(data !== '')
{console.log(data);
$('#chat-main').append(data);
$('#chat-main').animate({scrollTop: $('#chat-main').prop("scrollHeight")}, 500);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("Status: " + textStatus); console.log("Error: " + errorThrown);
}
});
}, 2000);
});
and Below is the PHP
session_start();
require_once('../includes/config.php');
require_once('../includes/db_connect.php');
require_once('../sources/functions.php');
require_once('dbhelper.php');
$chatDATA=$_POST['chatDATA'];
$sendDATA=$_POST['sendDATA'];
$uid;$tid;$id;$mes;$token;$action;$type;
if(isset($chatDATA))
{
$action=$chatDATA[0];
$token=$chatDATA[1];
$id=$chatDATA[2];
$type=$chatDATA[3];
}
else if(isset($sendDATA))
{
$action=$sendDATA[0];
$token=$sendDATA[1];
$mes=$sendDATA[2];
$type=$sendDATA[3];
if(!strcmp($sendDATA[3],'uid'))
$uid=$sendDATA[4];
else if(!strcmp($sendDATA[3],'tid'))
$tid=$sendDATA[4];
}
switch($action){
case "sendMessage" :
sendmessage($uid,$tid,$mes,$token,$con);
break;
case "refreshChat" :
refresh($id,$token,$type,$con);
break;
}
function sendmessage($uid,$tid,$mes,$token,$con){
$mes=mysqli_real_escape_string($con,$mes);
$data = mysqli_query($con,"SELECT * FROM `chat` WHERE `token` = '".$token."'");
$key=mysqli_fetch_array($data,MYSQLI_BOTH);
if($tid!=null && ($key[2]==$tid))
{
$trav= getTraveler($tid,$con);
$mes=$trav[3].' : '.$mes;
$res2 = mysqli_query($con,"INSERT INTO `chat` (`uid`, `tid`, `jid`, `message`, `sender`, `unread`, `token`) VALUES('".$key[1]."','".$key[2]."','".$key[3]."','".$mes."','tid','0','".$token."')");
echo $mes;
}
else if($uid!=null && ($key[1]==$uid))
{
$user=getUser($uid,$con);
$mes=$user[3].' : '.$mes;
$res2 = mysqli_query($con,"INSERT INTO `chat` (`uid`, `tid`, `jid`, `message`, `sender`, `unread`, `token`) VALUES('".$key[1]."','".$key[2]."','".$key[3]."','".$mes."','uid','0','".$token."')");
echo $mes;
}
else
return false;
}
function refresh($id,$token,$type,$con)
{
if(isset($id)&&isset($token)&&isset($type)&&isset($con))
{
$chat_sql="select * from `chat_read` where `token`='" . $token . "'";
$chat_read = mysqli_query($con,$chat_sql);
$get_read = mysqli_fetch_row($chat_read);
if (isset($get_read) && isset($type) && isset($id)) {
if(isset($_SESSION['id']))
$read_sql = "SELECT * FROM `chat` WHERE `token`='" . $token . "' AND `id`>'" . $get_read[5] . "' ";
else if(isset($_SESSION['tid']))
$read_sql = "SELECT * FROM `chat` WHERE `token`='" . $token . "' AND `id`>'" . $get_read[6] . "' ";
$unread = mysqli_query($con,$read_sql);
$html_output = "";
$all_results = array();
$last_id_updated=0;
while ($message = mysqli_fetch_array($unread,MYSQLI_BOTH)) {
$all_results[] = $message;
}
$size_arr=mysqli_num_rows($unread);
for ($i=0; $i < $size_arr; $i++)
{
if ($all_results[$i]['sender'] == "uid")
{ $html_output .= '<li class="left clearfix"> <div class="chat-body1 clearfix"><p>'.$all_results[$i][message].'</p> <div class="chat_time pull-right">'.$all_results[$i][time].'</div> </div> </li>';}
else if ($all_results[$i]['sender'] == "tid")
{ $html_output .= '<li class="left clearfix admin_chat"> <div class="chat-body1 clearfix"> <p>'.$all_results[$i][message].'</p> <div class="chat_time pull-left">'.$all_results[$i][time].'</div> </div> </li>';}
$last_id_updated=$all_results[$i]['id'];
}
$read_update;
if($size_arr) {
if(isset($_SESSION['id']))
{
$read_update="UPDATE `chat_read` SET `last_id_uid`= '".$last_id_updated."' WHERE token='".$token."'";
}
else if(isset($_SESSION['tid']))
{
$read_update="UPDATE `chat_read` SET `last_id_tid`= '".$last_id_updated."' WHERE token='".$token."'";
}
$res=mysqli_query($con,$read_update);}
if($res)
echo $html_output;
}
}
}

Load data after search function using ajax in one php page

I'm new with ajax and php. I had created a page where it loads the data using ajax. The data is shown using pagination. The thing is, I can't figure out on how to make the results search loading back to birds.php.
birds.php
<script type="text/javascript">
$(document).ready(function(){
function loading_show(){
$('#loading').html("<img src='../~ww319/images/loading.gif'/>").fadeIn('fast');
}
function loading_hide(){
$('#loading').fadeOut('fast');
}
function loadData(page){
loading_show();
var search = $('#search').val();
$.ajax
({
type: "POST",
url: "../~ww319/load_data.php",
data: "page="+page+"&search="+search,
success: function(msg)
{
$("#container").ajaxComplete(function(event, request, settings)
{
loading_hide();
$("#container").html(msg);
});
}
});
}
loadData(1); // For first time page load default results
$('#container .pagination li.active').live('click',function(){
var page = $(this).attr('p');
loadData(page);
});
});
</script>
<div class="entry">
<form action="../~ww319/load_data.php" method="POST">
<fieldset>
<legend>Searching</legend><br />
<input type="text" id="search" name="search" />
<input type="submit" value="Search" onClick="loadData(1);" /><br /><br />
<input type="hidden" name="page" value="1" />
</fieldset>
</form>
<br />
<div id="loading"></div>
<div id="container">
<div class="data"></div>
<div class="pagination">
</div>
</div>
</div>
load_data.php //this is the page to load the data to birds.php
<?php
if(isset($_POST['page']))
{
$page = $_POST['page'];
$cur_page = $page;
$page -= 1;
$per_page = 2;
$previous_btn = true;
$next_btn = true;
$first_btn = true;
$last_btn = true;
$start = $page * $per_page;
include 'connect.php';
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
if(isset($_POST['search'])){
$search = $_POST['search'];
$searchPar = '';
if(!empty($search)){
$searchPar = "WHERE (`species` LIKE '%".$search."%') OR (`location` LIKE '%".$search."%')";
}
$query = "SELECT * from birds $searchPar LIMIT $start, $per_page";
$result1 = mysql_query($query) or die('MySql Error' . mysql_error());
$msg = "";
if(mysql_num_rows($result1) > 0){
while($result = mysql_fetch_array($result1)){
$msg .= "<li><img src=".$result['imgThumb']."></li>";
}
$msg = "<div class='data'><ul>" . $msg . "</ul></div>"; // Content for Data
$query_pag_num = "SELECT COUNT(*) AS count FROM birds WHERE (`species` LIKE '%".$search."%') Or (`location` LIKE '%".$search."%')";
$result_pag_num = mysql_query($query_pag_num);
$row = mysql_fetch_array($result_pag_num);
$count = $row['count'];
$no_of_paginations = ceil($count / $per_page);
if ($cur_page >= 5) {
$start_loop = $cur_page - 2;
if ($no_of_paginations > $cur_page + 2)
$end_loop = $cur_page + 2;
else if ($cur_page <= $no_of_paginations && $cur_page > $no_of_paginations - 4) {
$start_loop = $no_of_paginations - 4;
$end_loop = $no_of_paginations;
} else {
$end_loop = $no_of_paginations;
}
} else {
$start_loop = 1;
if ($no_of_paginations > 5)
$end_loop = 5;
else
$end_loop = $no_of_paginations;
}
$msg .= "<div class='pagination'><ul>";
// FOR ENABLING THE FIRST BUTTON
if ($first_btn && $cur_page > 1) {
$msg .= "<li p='1' class='active'>First</li>";
} else if ($first_btn) {
$msg .= "<li p='1' class='inactive'>First</li>";
}
// FOR ENABLING THE PREVIOUS BUTTON
if ($previous_btn && $cur_page > 1) {
$pre = $cur_page - 1;
$msg .= "<li p='$pre' class='active'>Previous</li>";
} else if ($previous_btn) {
$msg .= "<li class='inactive'>Previous</li>";
}
for ($i = $start_loop; $i <= $end_loop; $i++) {
if ($cur_page == $i)
$msg .= "<li p='$i' style='color:#fff;background-color:#983D3A;' class='active'>{$i}</li>";
else
$msg .= "<li p='$i' class='active'>{$i}</li>";
}
// TO ENABLE THE NEXT BUTTON
if ($next_btn && $cur_page < $no_of_paginations) {
$nex = $cur_page + 1;
$msg .= "<li p='$nex' class='active'>Next</li>";
} else if ($next_btn) {
$msg .= "<li class='inactive'>Next</li>";
}
// TO ENABLE THE END BUTTON
if ($last_btn && $cur_page < $no_of_paginations) {
$msg .= "<li p='$no_of_paginations' class='active'>Last</li>";
} else if ($last_btn) {
$msg .= "<li p='$no_of_paginations' class='inactive'>Last</li>";
}
echo $msg;
}
else{ // if there is no matching rows do following
$msg .= "no results found.";
echo $msg;
}}
else{
$query_pag_data = "SELECT * from birds LIMIT $start, $per_page";
$result_pag_data = mysql_query($query_pag_data) or die('MySql Error' . mysql_error());
$msg = "";
while ($row = mysql_fetch_array($result_pag_data)) {
$msg .= "<li><img src=".$row['imgThumb']."></li>";
}
$msg = "<div class='data'><ul>" . $msg . "</ul></div>"; // Content for Data
/* --------------------------------------------- */
$query_pag_num = "SELECT COUNT(*) AS count FROM birds";
$result_pag_num = mysql_query($query_pag_num);
$row = mysql_fetch_array($result_pag_num);
$count = $row['count'];
$no_of_paginations = ceil($count / $per_page);
if ($cur_page >= 5) {
$start_loop = $cur_page - 2;
if ($no_of_paginations > $cur_page + 2)
$end_loop = $cur_page + 2;
else if ($cur_page <= $no_of_paginations && $cur_page > $no_of_paginations - 4) {
$start_loop = $no_of_paginations - 4;
$end_loop = $no_of_paginations;
} else {
$end_loop = $no_of_paginations;
}
} else {
$start_loop = 1;
if ($no_of_paginations > 5)
$end_loop = 5;
else
$end_loop = $no_of_paginations;
}
$msg .= "<div class='pagination'><ul>";
// FOR ENABLING THE FIRST BUTTON
if ($first_btn && $cur_page > 1) {
$msg .= "<li p='1' class='active'>First</li>";
} else if ($first_btn) {
$msg .= "<li p='1' class='inactive'>First</li>";
}
// FOR ENABLING THE PREVIOUS BUTTON
if ($previous_btn && $cur_page > 1) {
$pre = $cur_page - 1;
$msg .= "<li p='$pre' class='active'>Previous</li>";
} else if ($previous_btn) {
$msg .= "<li class='inactive'>Previous</li>";
}
for ($i = $start_loop; $i <= $end_loop; $i++) {
if ($cur_page == $i)
$msg .= "<li p='$i' style='color:#fff;background-color:#983D3A;' class='active'>{$i}</li>";
else
$msg .= "<li p='$i' class='active'>{$i}</li>";
}
// TO ENABLE THE NEXT BUTTON
if ($next_btn && $cur_page < $no_of_paginations) {
$nex = $cur_page + 1;
$msg .= "<li p='$nex' class='active'>Next</li>";
} else if ($next_btn) {
$msg .= "<li class='inactive'>Next</li>";
}
// TO ENABLE THE END BUTTON
if ($last_btn && $cur_page < $no_of_paginations) {
$msg .= "<li p='$no_of_paginations' class='active'>Last</li>";
} else if ($last_btn) {
$msg .= "<li p='$no_of_paginations' class='inactive'>Last</li>";
}
echo $msg;
}
}
The search results would be shown on load_data.php instead of loading back to birds.php.
Try this:
birds.php
<script type="text/javascript">
$(document).ready(function(){
function loading_show(){
$('#loading').html("<img src='../~ww319/images/loading.gif'/>").fadeIn('fast');
}
function loading_hide(){
$('#loading').fadeOut('fast');
}
function loadData(page){
loading_show();
var search = $('#search').val();
$.ajax
({
type: "POST",
url: "../~ww319/load_data.php",
data: "page="+page+"&search="+search,
success: function(msg)
{
$("#container").ajaxComplete(function(event, request, settings)
{
loading_hide();
$("#container").html(msg);
});
}
});
}
loadData(1); // For first time page load default results
$('#container .pagination li.active').live('click',function(){
var page = $(this).attr('p');
loadData(page);
});
});
</script>
<div class="entry">
<form action="../~ww319/load_search.php" method="POST">
<fieldset>
<legend>Searching</legend><br />
<input type="text" name="search" id="search"/>
<input type="button" value="Search" onClick="loadData(<?php $_POST['page'] ?>);" /><br /><br />
</fieldset>
</form>
<br />
<div id="loading"></div>
<div id="container">
<div class="data"></div>
<div class="pagination">
</div>
</div>
</div>
And your search query should be generated as follows:
$searchPar = '';
if(!empty($search)){
$searchPar = "WHERE (`species` LIKE '%".$search."%') OR (`location` LIKE '%".$search."%')";
}
$query = "SELECT * from birds $searchPar LIMIT $start, $per_page";
why don't try this http://www.datatables.net/examples/styling/jqueryUI.html ?
it was useful for me and it implement many functionalities like instant search that you will surely like

Categories

Resources