I'm trying to do AJAX search for my application but I have some problems.
I have table posts with fields id, title, summary, content. I want to make posts search by title.
In my controller I load model posts and my index function look like this
function index()
{
$search= $this->input->post('search');
$query = $this->posts->search_posts($search);
echo json_encode ($query);
}
in my model posts.php I put this function
function search_posts($search){
$this->db->select("id,title,summary,content");
$whereCondition = array('title' =>$search);
$this->db->where($whereCondition);
$this->db->from('posts');
$query = $this->db->get();
return $query->result();
}
and my view look like this
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="<?php echo base_url('css/style.css');?>">
<script type="text/javascript" language="javascript" src="http://www.technicalkeeda.com/js/javascripts/plugin/jquery.js"></script>
<script type="text/javascript" src="http://www.technicalkeeda.com/js/javascripts/plugin/json2.js"></script>
<script>
$(document).ready(function(){
$("#search").keyup(function(){
if($("#search").val().length>3){
$.ajax({
type: "post",
url: "http://localhost/blogFinal/index.php/blog",
cache: false,
dataType: 'json';
data:'search='+$("#search").val(),
success: function(response){
$('#finalResult').html("");
var obj = JSON.parse(response);
if(obj.length>0){
try{
var items=[];
$.each(obj, function(i,val){
items.push($('<li/>').text(val.title + " " + val.summary));
});
$('#finalResult').append.apply($('#finalResult'), items);
}catch(e) {
alert('Exception while request..');
}
}else{
$('#finalResult').html($('<li/>').text("No Data Found"));
}
},
error: function(){
alert('Error while request..');
}
});
}
return false;
});
});
</script>
</head>
<body>
<div id="wrap">
<header>
<h1><?php echo anchor('','My Blog'); ?></h1>
</header>
<div id="container">
<div id="loginDiv"><?php echo anchor('admin/logout','Logout'); ?></div>
<hr/>
<input type="text" name="search" id="search" />
<ul id="finalResult"></ul>
</div>
<div style="clear: both;"> </div>
I make this by following tutorial but it doesn't work for me.
Can somebody help me please? Thanks!
Related
I am making a product displaying page of an ecommerce website. The products are to be filtered by brands on the basis of brands that are checked by the customer. For this I have used an ajax request everytime a brand is checked. The problem is that the page cannot receive the get variables that i am sending to the same page. The ajax request is not giving any errors and also the chrome debugger side is also not showing any error at all. This is the page:
snapshot of the products page
And this is the code of the page:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<?php
session_start();
include('includes/pdo_connect.php');
include('includes/pdo_functions.php');
$logged_in;
$user_first_name;
if(isset($_SESSION['user'])){ //Determining if the user is logged in or not.
if($_SESSION['user']=='user'){
$user_id = $_SESSION['user_id'];
global $logged_in;
$logged_in = true;
global $user_first_name;
$user_first_name = $_SESSION['user_first_name'];
}
} else {
$_SESSION['user'] = 'guest';
$user_id = $_SERVER['REMOTE_ADDR'];
}
$cat;
if(isset($_GET['cat'])){
global $cat;
$cat = $_GET['cat'];
}
include('includes/logged_in.php');
if(isset($_GET['brand_list'])){
$brand_list = $_GET['brand_list'];
} else {
echo "<script>alert('value not received');</script>";
}
?>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="styles/list_style.css?<?php echo time(); ?>">
<link rel="stylesheet" type="text/css" href="styles/thickbox.css" media="screen">
<script type="text/javascript" src="js/jquery-3.1.1.js"></script>
<script type="text/javascript" src="js/thickbox.js"></script>
<?php
$where = array();
if(!empty($brand_list)){
echo "ajax working";
if(strpos($brand_list, ',')!==false){
$brand_choices = explode(',', $brand_list);
$barray = array();
foreach($brand_choices as $value) {
$barray[] = "brand_id = $value";
}
$where[] = '('.implode(' OR ', $barray).')';
} else {
$where[] = '(brand_id= '.$brand_list.')';
}
} else {
//echo "ajax not working ";
}
$w = implode(' AND ', $where);
$w = "where product_cat=$cat ".$w;
$filter_query = "select * from products $w ";
echo "filter query: ".$filter_query;
$first_load = 'filter';
function show_filtered(){
//echo "<script>alert('filter query working');</script>";
global $filter_query;
global $con;
global $brand_name;
try{
$stmt = $con->prepare($filter_query);
$stmt->execute();
$result = $stmt->fetchAll();
foreach ($result as $data) {
$product_id = $data['product_id'];
$product_cat = $data['product_cat'];
$product_brand = $data['product_brand'];
$product_title = $data['product_title'];
$product_price = $data['product_price'];
$product_desc = $data['product_desc'];
$product_image = $data['product_image'];
echo "
<div class='product_container $brand_name'>
<a href='details.php?pid=".$product_id."' alt='".$product_title."'>
<div class='img_div'>
<img src='admin/product_images/".$product_image."?".time()."' alt='".$product_title."'/>
</div>
<div class='index_product_desc'>".$product_title."</div>
<div class='index_product_price'>₹".$product_price."</div>
</a>
</div>
";
}
} catch(PDOException $e){
echo "Error in show_list(): ".$e->getMessage();
}
}
function show_brands(){
global $con;
global $cat;
global $brand_name;
try{
$query = "select * from cat_brand where cat_id = $cat";
$stmt = $con->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll();
//$brand = array();
foreach ($result as $data) {
$brand_id = $data['brand_id'];
//echo "<script>alert('$brand_id');</script>";
$query1 = "select * from brands where brand_id = $brand_id";
$stmt1 = $con->prepare($query1);
$stmt1->execute();
$result1 = $stmt1->fetchAll();
echo "<ul>";
foreach ($result1 as $data1) {
$brand_name = $data1['brand_title'];
echo "<li><input type='checkbox' value='$brand_id' id='$brand_name' class='brand_check' name='brandchoice'> $brand_name</li>";
}
echo "</ul>";
}
} catch(PDOException $e){
echo "Error in show_brands: ".$e->getMessage();
}
}
function show_price(){
}
?>
</head>
<body>
<div class="wrapper">
<header>
<div class="home_logo">
<a href="index.php">
<img src="images/skyshop_sumopaint.png" alt="Site Home">
</a>
</div>
<div class="login">
<?php user();?> |
<?php login_status(); ?>
</div>
<div class="form">
<form method="get" target="" name="searchbar_form">
<input type="text" name="searchbar" id="searchbar">
<input type="submit" id="search_button" value="Search">
</form>
</div>
</header>
<div class="menubar">
<div class="dropdown">
<button onclick="dropdownToggle()" class="dropdown-button">Shop By Category</button>
<ul class="dropdown-content" id="dropdownContent">
Categories
<?php getcats(); ?>
</ul>
</div>
<div class="menubar-div">
<ul class="menu-items">
<?php getcats(); ?>
</ul>
</div>
<div class="cart">
Cart (0)
</div>
</div>
<div class="content">
<div class="nav">
</div>
<div class="list_wrapper">
<!--/////////////////////////////////////////////// Filter div /////////////////////////////////////////////////////-->
<div class="filter">
<span class="filter_heading">Select Brands</span>
<a href="" class="clear" id="clear_brands">Clear<a>
<div class="brand_div">
<?php
show_brands();
?>
</div>
<div class="price_div">
</div>
</div>
<!--/////////////////////////////////////////////// List div ///////////////////////////////////////////////////////-->
<div class="list">
<div class="loading">
<img src="images/loadingAnimation.gif">
</div>
<?php
show_filtered();
?>
</div>
</div>
<div class="footer">
FOOTER
</div>
</div>
</div>
<?php
?>
<script type="text/javascript">
$(window).on('load', function(){
function filter(){
//alert("filter called");
$('.filter .list').css('opacity', 0.5);
$('.loading').css('visibility', 'visible');
var brandchoice = new Array();
$('input[name="brandchoice"]:checked').each(function(){
brandchoice.push($(this).val());
$('#clear_brands').css('visibility', 'visible');
});
if(brandchoice==""){
$('#clear_brands').css('visibility', 'hidden');
}
var brand_list = '&brand_list='+brandchoice;
var data = brand_list.substring(1, brand_list.length);
//alert(data);
$.ajax({
url: "list.php",
type: "GET",
data: data,
cache: false,
success: function(result){
$(".filter .list").css("opacity", 1);
$(".loading").css("visibility", "hidden");
},
error: function(jqxhr, exception){
console.log(jqxhr);
},
beforeSend: function(){
console.log("before send: "+data); //This is showing "brand_list=1" which is correct.
}
});
}
$('input[type="checkbox"]').on('change', filter);
$('#clear_brands').on('click', function(){
$('.brand_check').removeAttr('checked');
filter();
$('#clear_brands').css('visibility', 'hidden');
});
}); //end of jquery
</script>
</body>
</html>
I am using alert() in the beforeSend in the ajax request and it returns the correct data as expected. But the PHP section of the page does not received the values. There are no errors on the PHP side or the browser debug window.
I checked your code line by line. and figure out that you have code for ajax inside the function named "filter" function filter().
Now you are calling this filter function on by onclick event of the element with id clear_brands
$('#clear_brands').on('click', function(){
$('.brand_check').removeAttr('checked');
filter();
$('#clear_brands').css('visibility', 'hidden');
});
and by this code i came to know that at the end your ajax call is not being made because you click event was not triggered,
So either you should trigger this event on your document get ready or you have to do it by clicking on that element.
Just think about the flow once.
i was testing your script in my local and
with some modification i have made it working.
did some changes like
at the end of the script i just putted this code below.
$(document).ready(function(){
$('#clear_brands').trigger("click");
});
And ajax call was executed..
check out my entire HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<a href="" class="clear" id="clear_brands">Clear<a>
<script type="text/javascript">
$(window).on('load', function(){
function filter(){
//alert("filter called");
$('.filter .list').css('opacity', 0.5);
$('.loading').css('visibility', 'visible');
var brandchoice = new Array();
$('input[name="brandchoice"]:checked').each(function(){
brandchoice.push($(this).val());
$('#clear_brands').css('visibility', 'visible');
});
if(brandchoice==""){
$('#clear_brands').css('visibility', 'hidden');
}
var brand_list = '&brand_list='+brandchoice;
var data = brand_list.substring(1, brand_list.length);
//alert(data);
$.ajax({
url: "list.php",
type: "GET",
data: data,
cache: false,
success: function(result){
$(".filter .list").css("opacity", 1);
$(".loading").css("visibility", "hidden");
},
error: function(jqxhr, exception){
console.log(jqxhr);
},
beforeSend: function(){
console.log("before send: "+data); //This is showing "brand_list=1" which is correct.
}
});
}
$('input[type="checkbox"]').on('change', filter);
$('#clear_brands').on('click', function(){
$('.brand_check').removeAttr('checked');
filter();
$('#clear_brands').css('visibility', 'hidden');
});
}); //end of jquery
$(document).ready(function(){
$('#clear_brands').trigger("click");
});
</script>
</body>
</html>
In Chrome do Ctrl+Shift+I to open Developer Tools and check Console for errors and Network tab to see if the data is passed in request.
It is a widely asked question to help with this error but I have spent all day reading other answers and creating various versions for my code and still can not get anything else then this error. So I ask for your help.
My view:
<html>
<head>
<title></title>
<?=$head?>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?key=AIzaSyAhiKwDjhm1ZXS1jHBHErJf6pxT2TUCMM4"></script>
<script src="<?php echo base_url() ?>scripts/jquery.colorbox-min.js"></script>
<script src="<?php echo base_url() ?>scripts/gmaps.js"></script>
<link rel="stylesheet" href="<?php echo base_url() ?>css/colorbox.css">
<style type="text/css">
#map {
width: 700px;
height: 700px;
}
</style>
</head>
<body>
<button id="go-button" type="button">Click Me!</button>
<div class="multiselect">
<label><input type="checkbox" value="all" />All</label>
<label><input type="checkbox" name="filtrs1[]" value="manufacturer1" />manufacturer1</label>
<label><input type="checkbox" name="filtrs1[]" value="manufacturer2" />manufacturer2</label>
<label><input type="checkbox" name="filtrs1[]" value="manufacturer3" />manufacturer3</label>
<label><input type="checkbox" name="filtrs1[]" value="manufacturer4" />manufacturer4</label>
</div>
<div id="map"></div>
<script type="text/javascript">
var products= <?= json_encode($products);?>;
var allMap;
$(document).ready(function(){
var allMap = new GMaps({
el: '#map',
zoom: 7,
lat: 37.4419,
lng: -122.1419
});
loadJsonMap(allMap, products);
$('#go-button').click(function(){
var chb = $("input[name='filtrs1[]']:checked");
var filtrs1values = [];
$.each(chb,function(){
filtrs1values.push($(this).val());
});
$.post('<?php echo base_url() ?>index.php/products/filter', {
filtrs1 : filtrs1values
}, function(response){
allMap.removeMarkers();
loadJsonMap(allMap, response);
});
});
});
function loadJsonMap(map, data){
var markers_data = [];
$.each(data, function(key, val){
if (val.latitude != undefined && val.longitude != undefined) {
markers_data.push({
lat : val.latitude,
lng : val.longitude,
details : {
holder_id : val.holder_id
},
click : function(e){
if(e.details.holder_id !== undefined){
var url = '<?php echo base_url() ?>index.php/products/colorbox/' + e.details.holder_id;
$.colorbox({
open : true,
href : url,
iframe : false,
innerWidth : 400,
innerHeight : 400,
close : 'Aizvert'
});
}
}
});
}
});
map.addMarkers(markers_data);
}
</script>
</body>
</html>
where $.post calls for controller products:
public function filter()
{
$data['manufacturer'] = $this->input->post('filtrs1');
$result = $this->products_model->get_productsByManufacturer($data);
// $result = $this->security->get_csrf_token_name();
// $result = $this->security->get_csrf_hash();
header('Cache-Control: no-cache, must-revalidate');
header('Content-Type: application/json');
echo json_encode($result);
}
where in products_model:
function get_productsByManufacturer($data)
{
if(empty($data['manufacturer']){
$this->db->select("latitude,longitude, holder_id");
$query = $this->db->get('products');
return $query->result_array();
}else{
$this->db->select("latitude,longitude, holder_id");
$this->db->where_in('manufacturer', $data['manufacturer']);
$query = $this->db->get('products');
return $query->result_array();
}
}
I get error on $.post line. I checked filtrs1values array using consule.log and got ["manufacturer3", "manufacturer4"]. Also I have changed my controller and model code multiple times but always get the same error.
I have two pages. test1.php and test2.php.
All I want to do is hit submit on test1.php and test2.php be displayed within a div. This is actually working fine, BUT I need to pass an argument to test2.php to limit the results shown from the mySQL database (there'll only ever be one result from a database of 3000 items).
To be honest, I think this is within the javascript, but just not sure how to go about it....
test1.php is
<html>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
// Handler for .ready() called.
$('#SubmitForm').submit(function( event ) {
$.ajax({
url: 'test2.php',
type: 'POST',
dataType: 'html',
data: $('#SubmitForm').serialize(),
success: function(content)
{
$("#DisplayDiv").html(content);
}
});
event.preventDefault();
});
});
</script>
<body>
<div id="page">
<form id="SubmitForm" method="post">
<div id="SubmitDiv" style="background-color:black;">
<button type="submit" class="btnSubmit">Submit</button>
</div>
</form>
<div id="DisplayDiv" style="background-color:red;">
<!-- This is where test2.php should be inserted -->
</div>
</div>
</body>
test2.php is
$pageNum_test1 = 0;
if (isset($_GET['pageNum_test1'])) {
$pageNum_test1 = $_GET['pageNum_test1'];
}
$startRow_test1 = $pageNum_test1 * $maxRows_test1;
mysql_select_db($database_wing, $wing);
$query_test1 = "SELECT * FROM pilots";
$query_limit_test1 = sprintf("%s LIMIT %d, %d", $query_test1, $startRow_test1, $maxRows_test1);
$test1 = mysql_query($query_limit_test1, $wing) or die(mysql_error());
$row_test1 = mysql_fetch_assoc($test1);
if (isset($_GET['totalRows_test1'])) {
$totalRows_test1 = $_GET['totalRows_test1'];
} else {
$all_test1 = mysql_query($query_test1);
$totalRows_test1 = mysql_num_rows($all_test1);
}
$totalPages_test1 = ceil($totalRows_test1/$maxRows_test1)-1;
?>
<div id="page" style="background-color:yellow;">
<?php do { ?>
<?php
echo "Hello World.";
echo $row_test1['firstname']
?>
<?php } while ($row_test1 = mysql_fetch_assoc($test1)); ?>
</div>
<?php
mysql_free_result($test1);
?>
url: 'test2.php?pageNum_test1=' + num,
I think that's what you want.
i am newbie on codeigniter but trying to develop simple CMS on it.
my question is i have a side column in my main CMS view which have several links to other views,what i want to do is to load all the links in main CMS view in center div instead of going to another page every time. I know i can achieve this task through ajax but dont know how to do it on CODEIGNITER.
Here is how i want to acheieve it to my knowledge.
<script type="text/javascript">
function onLinkClick(value){
jQuery('#mang_server').load(value,
function(){alert('Content Successfully Loaded.')}
);
}
</script>
<body>
<div id="main">
<div id="header"> <img src="../img/logo.gif" width="101" height="29" alt="" />
<div id="middle">
<div id="left-column">
<h3>Header</h3>
<ul class="nav">
<?php foreach($ops as $operations)
{$op_name = $operations['admin_op'];
$op_link = $operations['link_to'];
?>
<li><?php echo $op_name ;?></li>
<?php } ?>
</ul>
Take a look on this simple example for ajax in codeigniter:
$.ajax({
url: '<?php echo base_url() ?>/controller_namer/method_name',
type: 'POST',
data: {view_param: "sidebar_html"},
success: function(response){
$('#div_id').html(response);
}
});
Now go to controllers/controller_name.php and create a method method_name;
function method_name() {
// Get Post Data
$View_Name = $this->input->post("view_param");
$this->load->view($View_Name);
// Alternate is create your html here
// ......
}
hope this will help you.
#jogesh_pi
View Portion:
<script>
function onLinkClick(value){
/*Query('#mang_server').load(value,
function(){alert('Content Successfully Loaded.')}
);*/
$.ajax({
url: '<?php echo base_url() ?>/admin/load_view/',
type: 'POST',
data: {view_param: "value"},
success: function(response){
//$('#mang_server').html(response);
alert("response recieved");
}
enter code here
});
}
</script>
<li><?php echo $op_name ;?></li>
Controller Portion : admin
public function load_view($view_name){
$data['view_link'] = $this->admin_model->load_view_model($view_name);
$this->load->view($data);
}
Model portion : load_view_model
public function load_view_model($view_name){
$this->db->where('admin_op',$view_name);
$query = $this->db->get('admin_operations');
if($query->num_rows()>0){
foreach($query->results() as $rows ){
$data['link'] = $rows->link_to;
}
return $data->result_arrays();
}
}
I'm trying import images to HTML using PHP, but NivoSlider not loaded that.
I looked for the cause of the problem.
I am printing a alert message of response and the right.
Here is the HTML and AJAX query:
<div id="workcontent" class="pcontent" style="display:none;">
<div class="slider-wrapper theme-default">
<div id="slider" class="nivoSlider">
</div>
</div>
<script>
$(document).ready(function() {
var wl = $('#worklist div');
wl.on('click', function(){
var name = $(this).attr('id');
console.log(name);
$.ajax({
url: 'read.php',
type: 'POST',
data: { data : name }
}).done(function (response) {
$('#slider').prepend(response);
alert(response);
});
});
});
</script>
<div id="back"></div>
<div id="backcontainer">
<div id="back">
Back
</div>
</div><!--End backcontainer-->
</div><!--End content-->
And here is the other jQuery:
<script>
$(document).ready(function() {
$('#slider').nivoSlider(function(){alert('OK');});
});
</script>
This alert don't show! ):
Finally, here is the PHP code:
<?php
if (isset($_POST["data"])){
if ($_POST["data"] == "") {
echo "data ures";
} else {
$data = $_POST["data"];
$fname = "content/".$data."/*.*";
$files = glob($fname);
for ($i=0; $i<count($files); $i++)
{
$num = $files[$i];
echo '<img src="'.$num.'" data-thumb="'.$num.'">';
}
}
} else {
echo "nem jott data";
}
?>
Sorry for my bad english
NivoSlider doesn't take a function as an argument.
Also .nivoSlider() is probably called before the AJAX call returns it's response.
A better solution would be:
$(document).ready(function() {
$.ajax({
url: 'read.php',
type: 'POST',
data: { data : name }
}).done(function (response) {
$('#slider').prepend(response).nivoSlider( {} );
});
});
Now you can be fairly sure #slider contains the images from the response body so NivoSlider can act on them.