I've two different table, 1st is draft_table, and 2nd is fix_table, each table have same fields ( product & price )
i want to make data from draft_table, can be save to fix_table with checkbox, so just selected data will save to fix_table.
i've code like this :
AJAX
<script>
$(function(){
$("a.paid").click(function(){
if(confirm("Are you sure want save this?"))
{
id_array=new Array()
i=0;
$("input.chk:checked").each(function(){
id_array[i]=$(this).val();
i++;
})
$.ajax({
url:'<?php echo base_url(); ?>fix_data/set',
data:"kode="+id_array,
type:"POST",
success:function(respon)
{
if(respon==1)
{
window.parent.location.reload(true);
}
}
})
}
return false;
})
})
</script>
Views :
<?php
foreach($data_get->result_array() as $dp)
{
?>
<tr><td><input type="checkbox" name="chk[]" class="chk" value="<?php echo $dp['id_draft']; ?>" /></td>
<td><?php echo $dp['product']; ?></td>
<td><?php echo $dp['price']; ?></td>
</td></tr>
<?php
}
?>
Controller :
public function set_stts()
{
if($this->session->userdata('logged_in')!="")
{
$id_get = $this->input->post('kode');
$dt = $this->db->get_where("tbl_draft",$id_get)->row();
$product = $dt->product;
$price = $dt->price;
if ($this->input->post('kode')) {
$query = $this->db->query("INSERT INTO tbl_fix (product,price) VALUES (".$product.",".$price.")");
}
if($query){
echo 1;
}
else{
echo 0;
}
}
else
{
header('location:'.base_url().'dashboard_item');
}
}
After i Click submit in draft form, nothing happen, is there anyone may help me with this case?
Thank you
maybe you can change your controller like this :
public function set()
{
if($this->session->userdata('logged_in')!="")
{
$id_get = $this->input->post('kode');
$quer = $this->db->query("select * from tbl_draft WHERE id IN (".$id_get.")");
if ($this->input->post('kode')) {
foreach($quer->result_array() as $dp)
{
$a = $dp['product'];
$b = $dp['price'];
$query = $this->db->query("INSERT INTO tbl_fix (product,price) VALUES
('".$a."','".$b."')");
}
}
if($query){
echo 1;
}
else{
echo 0;
}
}
else
{
header('location:'.base_url().'dashboard_item');
}
}
Related
Ideally, In my database table, I have username, name, location, email.
Now I have a table in my view.php where it returns value from the database.
Table header consists of name, username, and more info where name and username comes directly from the database while more info will have a button for each row. When the button is clicked, it should display location and email in a pop up.
Question: How can I retrieve location and email of a user when the button is clicked specifically?
Example:
user1, joe doe, [button] -> user1 location, user1#email.com
user2, jay doe, [button] -> user2 location, user2#email.com
Codes: p.s. code includes pagination.
controller.php
function pagination() {
$config = array();
$config['base_url'] = base_url() . "controller/pagination";
$total_row = $this->model->record_count();
$config["total_rows"] = $total_row;
$config["per_page"] = 8;
$config['uri_segment'] = 3;
/* $config['use_page_numbers'] = TRUE; */
$config['num_links'] = $total_row;
$config['cur_tag_open'] = ' <a class="current">';
$config['cur_tag_close'] = '</a>';
$config['next_link'] = '<span aria-hidden="true">»</span>';
$config['prev_link'] = '<span aria-hidden="true">«</span>';
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data["results"] = $this->model->fetch_data($config["per_page"], $page);
$str_links = $this->pagination->create_links();
$data["links"] = explode(' ', $str_links);
// View data according to array.
$this->load->view("view-employees", $data);
}
model.php
public function record_count() {
return $this->db->count_all('users');
}
public function fetch_data($limit, $start) {
$this->db->limit($limit, $start);
$query = $this->db->get('users');
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
view.php
<tr>
<th>username</th>
<th>name</th>
<th>more</th>
</tr>
<tr>
<?php foreach ($results as $data) { ?>
<td><?php echo $data->username; ?></td>
<td><?php echo $data->name; ?></td>
<td>
<button type='button' class='btn'>
<?php echo $data->location;
echo $data->email;
?>
</button>
</td>
</tr>
You could write a Codeigniter-controller which will return email and location
Then you write Javascript-functions which will call this controller to retrieve the data asJSON-Data
Both, writing a controller which returns JSON and an example how to call this controller from JS can be found here:
Code Igniter - How to return Json response from controller
Try like this..
MODEL:
public function record_count() {
return $this->db->count_all('users');
}
public function fetch_data($limit, $start) {
$this->db->limit($limit, $start);
$query = $this->db->get('users');
if ($query->num_rows() > 0) {
return $query->result_array();
}
}
return false;
}
View:
<tr>
<th>username</th>
<th>name</th>
<th>more</th>
</tr>
<tr>
<?php foreach ($results as $data) { ?>
<td><?php echo $data['username']; ?></td>
<td><?php echo $data['name']; ?></td>
<td>
<button type='button' class='btn'>
<?php echo $data['location'];
echo $data['email'];
?>
</button>
</td>
<?php } ?>
</tr>
I am making a load more data function when pressing a button via Codeigniter
I got this problem in-front of me
can't solve it
maybe the problem is the array doesn't passed to the view !!
Can you help ?
Javascript
<script type="text/javascript">
$(document).ready(function(){
var num_ads = <?=$num_ads?>;
var loaded_ads = 0;
$("#more_button").click(function(){
loaded_ads += 10;
$.get("e3lanat/get_ads/" + loaded_ads, function(data){
$("#Ebda2").append(data);
});
if(loaded_ads >= num_ads - 10)
{
$("#more_button").hide();
//alert('hide');
}
})
})
</script>
View
<div id="Ebda2">
<?php foreach ($data['latest_messages'] as $ads)
{
echo $ads->current_price;
echo '<div class="water">';
echo 'div class="eye-top">';
echo '<img class="img-responsive" src="public/images/9.jpg" alt="">';
echo '</div>';
echo '<div class="title-blue">';
echo '<h4><a href="#">';
echo $ads->name;
echo "</a></h4>";
echo "<p>";
echo $ads->description;
echo'</p>';
echo '</div>';
}
?>
</div>
<div id="more_button">
more
</div>
Controller
function __construct(){
parent::__construct();
$this->load->model('ads_model');
}
public function index(){
if($this->session->userdata('logged_in'))
{
$this->load->model('ads_model');
$data['num_messages'] = $this->ads_model->num_ads();
$data['latest_messages'] = $this->ads_model->get_ads();
$this->load->view('e3lanat_view', $data);
}
else
{
redirect('signin', 'refresh');
}
}
public function insert_rows()
{
$i = 0;
while($i < 50)
{
$i++;
$data = array('name' => 'name ' . $i, 'description' => 'description ' . $i,
'user_id' => 9, 'cat_id' => '1',
'current_owner_id' => 10, 'cat_id' => '1',
'initial_price'=> $i+10,
'current_price'=> $i+50,
'increase_price'=> $i+30
);
$this->db->insert('ads', $data);
echo $i. '<br />';
}
}
public function get_ads($offset)
{
$this->load->model('ads_model');
$data['latest_messages'] = $this->ads_model->get_ads($offset);
$this->load->view('e3lanat_view/get_ads', $data);
}
**Model**
class ads_model extends CI_Model {
public function __construct()
{
parent::__construct();
}
function get_ads($offset=0)
{
$this->db->order_by('ads_id', 'desc');
$query = $this->db->get('ads', 10, $offset);
return $query->result();
}
function num_ads()
{
$query = $this->db->count_all_results('ads');
return $query;
}
}
Thanks in Advance :)
You are trying to load the view instead of returning data.
In Controller:
public function get_ads($offset) {
$this->load->model('ads_model');
$data['latest_messages'] = $this->ads_model->get_ads($offset);
return json_encode($data['latest_messages']);
}
In View Javascript:
$.get("e3lanat/get_ads/" + loaded_ads, function(data){
console.log(data);
});
Now you need to iterate over the JSON and append your data to the view. See how to Loop through JSON object List and appending data to the view will go something like this:
$("#Ebda2").append('<div class="water"> ...every thing inside... </div>');
change this
<?php foreach ($data['latest_messages'] as $ads)
to
<?php foreach ($latest_messages as $ads)
can some one help me out in updating edited value in mysql db using jquery/php.
I have three buttons edit/save/cancel
when i click on edit button span data pushed into input text and edit button replaced with save button!!
when i click on edit button i'll get span data in my text box with save and cancel button but when i try to update using save button its not updating in my db and in UI
Code
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function showdata()
{
$.ajax({
url:"pages/feeds.php",
type:'post',
async:false,
data:{
showtable:1
},
success:function(re){
$('#showdata').html(re);
}
});
}
$('#orders').delegate('.editOrder','click',function(e){
e.preventDefault(e);
var $li = $(this).closest('li'); $li.find('input.name').val($li.find('span.name').html());
$li.addClass('edit');
});
$('#orders').delegate('.cancelEdit','click',function(e){
e.preventDefault(e);
$(this).closest('li').removeClass('edit');
});
//Edit Code
$('body').delegate('.edit','click',function(){
var IdEdit = $(this).attr('ide');
$.ajax({
url:"pages/feeds.php",
type:"post",
data:{
editvalue:1,
id:IdEdit
},
success:function(show)
{
$('#id').val(show.id);
$('#url1').val(show.url);
}
});
});
//Ends
//Update Starts
$('.update').click(function(){
var id = $('#id').val()-0;
var urls = $('#url1').val();
$.ajax({
url:"pages/feeds.php",
type:"post",
async:false,
data:{
update:1,
id:id,
upurls:urls
},
success:function(up)
{
$('input[type=text]').val('');
showdata();
},
error:function(){
alert('error in updating');
}
});
});
//UPdate Ends
</script>
<style type="text/css">
ul li .edit{
display:none;
}
ul li.edit .edit{
display:initial;
}
ul li.edit .noedit{
display:none;
}
</style>
</head>
<body>
<ul id="orders">
<?php
$sql = "select * from demo";
$result = mysql_query($sql);
while($row = mysql_fetch_object($result))
{
?>
<li>
<span class="noedit name" value='<?php echo $row->id;?>'><?php echo $row->url;?></span>
<input id="url1" class="form-control edit name" value="<?php echo $row->id;?>"/>
<a ide='<?php echo $row->id;?>' id="edit" class='editOrder' href="#" style="display:block-inline;">EDIT</a>
<a idu='<?php echo $row->id;?>' id="update" class='update saveEdit' href='#' style='display:none;'>SAVE</a>
<a idd='<?php echo $row->id;?>' id="delete" class='delete' href="#" style="display:block-inline;">DELETE</a>
<a idc='<?php echo $row->id;?>' id="cancel" class='cancelEdit edit' href='#' style='display:none;'>CANCEL</a>
</li>
<?php } ?>
</ul>
</body>
</html>
<?php
//Edit Starts
if(isset($_POST['editvalue']))
{
$sql = "select * from deccan where id='{$_POST['id']}'";
$row = mysql_query($sql);
$rows = mysql_fetch_object($row);
header("Content-type:text/x-json");
echo json_encode($rows);
exit();
}
//Ends
//UPdate Starts
if(isset($_POST['update']))
{
$sql = "
update deccan
set
url='{$_POST['upurls']}'
where id='{$_POST['id']}'
";
$result = mysql_query($sql);
if($result)
{
//alert('success');
echo 'updated successfully';
}
else
{
//alert('failed');
echo 'failed to update';
}
}
?>
Alright. I was still missing the following code from you, so you'll have to add these yourself:
The HTML element with parameter id="id" needed for $('#id').val(text.id);
The HTML element with parameter id="url1" needed for $('#url1').val(text.url);
The PHP response code for JS function showdata(); inside feeds.php
Since I don't have your database here, I was unable to test the code. It should work fine, but if anything is wrong, just let me know:
PHP file: index.php
<?php
// Include PDO class
include_once("pdo.class.php");
// Database connection settings
define("DB_HOST", "localhost");
define("DB_USER", "username");
define("DB_PASS", "password");
define("DB_NAME", "database");
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<!-- CSS resources -->
<link rel="stylesheet" type="text/css" href="style.css">
<!-- Javascript resources -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="main.js"></script>
<title>Update Script</title>
</head>
<body>
<ul id="orders">
<?php
// Instantiate database
$db = new Database;
// Try getting data from database
Try {
// Query
$db->query("SELECT * FROM demo");
// Get results
$data = $db->resultset();
// Echo reults
foreach($data as $row){ ?>
<li>
<span class="noedit name" value="<?php echo $row['id']; ?>"><?php echo $row['url']; ?></span>
<input id="url1" class="form-control edit name" value="<?php echo $row['id']; ?>" />
<a data-ide="<?php echo $row['id']; ?>" class='editOrder' href="#" style="display:block-inline;">EDIT</a>
<a data-idu="<?php echo $row['id']; ?>" class='update saveEdit' href='#' style='display:none;'>SAVE</a>
<a data-idd="<?php echo $row['id']; ?>" class='delete' href="#" style="display:block-inline;">DELETE</a>
<a data-idc="<?php echo $row['id']; ?>" class='cancelEdit edit' href='#' style='display:none;'>CANCEL</a>
</li>
<?php }
//Catch any database errors
} Catch(PDOException $e){
echo "Database error:". $e->getMessage();
}
?>
</ul>
</body>
</html>
Javascript file: main.js
$('#orders').delegate('.editOrder','click',function(e){
e.preventDefault();
var $li = $(this).closest('li');
$li.find('input.name').val($li.find('span.name').html());
$li.addClass('edit');
});
$('#orders').delegate('.cancelEdit','click',function(e){
e.preventDefault();
$(this).closest('li').removeClass('edit');
});
//Edit Code
$('body').delegate('.edit','click',function(){
var IdEdit = $(this).attr('data-ide');
$.ajax({
url: "pages/feeds.php",
type: "POST",
data: 'editvalue=1&id='+IdEdit,
success: function(text){
$('#id').val(text.id);
$('#url1').val(text.url);
}
});
});
//Update Code
$('.update').click(function(){
var id = $('#id').val()-0;
var urls = $('#url1').val();
$.ajax({
url: "pages/feeds.php",
type: "POST",
async: false,
data: 'update=1&id='+id+'&upurls='+urls,
success: function(text){
$('input[type=text]').val('');
showdata();
},
error:function(){
alert('Error in updating');
}
});
});
function showdata(){
$.ajax({
url: "pages/feeds.php",
type: "POST",
async: false,
data: 'showtable=1',
success:function(text){
$('#showdata').html(text);
}
});
}
CSS file: style.css
ul li .edit{
display:none;
}
ul li.edit .edit{
display:initial;
}
ul li.edit .noedit{
display:none;
}
PHP file: feeds.php
<?php
// Include PDO class
include_once("pdo.class.php");
// Database connection settings
define("DB_HOST", "localhost");
define("DB_USER", "username");
define("DB_PASS", "password");
define("DB_NAME", "database");
// Instantiate database
$db = new Database;
// Edit
if(isset($_POST['editvalue']) && $_POST['editvalue'] == 1){
// Try getting data from database
Try {
// Query
$db->query("SELECT * FROM deccan WHERE id = :id");
// Prepare POST data (to prevent SQL injection)
$db->bind(":id", $_POST['id']);
// Get result
$data = $db->single();
// Set header JSON
header("Content-type:text/x-json");
// Return result
echo json_encode($rows);
} Catch(PDOException $e){
echo "Database error:". $e->getMessage();
}
} else if(isset($_POST['update']) && $_POST['update'] == 1){
// Try updating data in database
Try {
// Query
$db->query("UPDATE deccan SET url = :url WHERE id = :id");
// Prepare POST data (to prevent SQL injection)
$db->bind(":url", $_POST['upurls']);
$db->bind(":id", $_POST['id']);
// Execute Query
$db->execute();
// Return succes
echo 'updated successfully';
} Catch(PDOException $e){
echo "Database error:". $e->getMessage();
}
} else if(isset($_POST['showtable']) && $_POST['showtable'] == 1){
/*
This part was not included in your code, so write it
yourself using above data as examples
*/
}
?>
PHP file: pdo.class.php
<?php
Class Database {
private $host = DB_HOST;
private $user = DB_USER;
private $pass = DB_PASS;
private $dbname = DB_NAME;
private $dbh;
private $error;
private $stmt;
public function __construct(){
// Set DSN
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
// Set options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
// Create a new PDO instanace
try{
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
}
// Catch any errors
catch(PDOException $e){
$this->error = $e->getMessage();
return $this->error;
}
}
public function query($query){
$this->stmt = $this->dbh->prepare($query);
}
public function bind($param, $value, $type = null){
if (is_null($type)) {
switch (true) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
$this->stmt->bindValue($param, $value, $type);
}
public function execute(){
return $this->stmt->execute();
}
public function column(){
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_COLUMN);
}
public function resultset(){
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
public function single(){
$this->execute();
return $this->stmt->fetch(PDO::FETCH_ASSOC);
}
public function rowCount(){
return $this->stmt->rowCount();
}
public function lastInsertId(){
return $this->dbh->lastInsertId();
}
public function beginTransaction(){
return $this->dbh->beginTransaction();
}
public function endTransaction(){
return $this->dbh->commit();
}
public function cancelTransaction(){
return $this->dbh->rollBack();
}
public function debugDumpParams(){
return $this->stmt->debugDumpParams();
}
}
?>
I would normally have two scripts (.php) files.
One to display the form and one to catch the submission (possibly via ajax)
You can have both in the same .php file but then you'd want to check before outputting any text whether you have any POST data to process.
If you go with two files
view file:
<html>
<body>
<form method="POST" action="path/to/formname_submit.php">
your form fields go here
<input name="somefield"/>
...
</form>
<script>
//your jquery code
....
</script>
<body>
</html>
submit file
<?php
if (empty($_POST['id'])){
die("no ID");
};
if (empty($_POST['editvalue'])){
die("no editvalue");
}
//get a database connection
$db = mysqli(DBHOST,DBUSER,DBPASS,DBNAME);
$db->set_charset("utf8");
// read in the POST data
//should do some more validation / anti SQL injection
$editvalue = $db->escape_string($_POST['editvalue']);
$id = intval($_POST['id']);
$sql = "UPDATE sometable SET `field` = '$editvalue' WHERE id=$id";
if ($db->query($sql)){
echo 'Success';
}
else {
echo 'UPDATE ERROR:'.$db->errno.': '.$db->error;
}
your jquery can now send the data to the second script and see if the data coming back from the call is 'Success' and display an error if it's not.
Hello friends this i am facing some problem...I have multiple check boxes and by selecting each check box i am inserting the users details to database by Ajax. the records records are inserting to database but my problem is that , suppose i have 5 users in the page, suppose i am selecting the 3 user check boxes and submit , and if the insertion succeed then i want that the 3 selected users will not shown on page. i use Google many tips but can't solve the problem.
//this is the menu.php
<li class="invitetab"><span>Invite</span></li>
$('.invitetab').one('click', function(){
var rp = '<?php echo $baseUrl ;?>/themes/gr-mist/pagemenu/parts/';
var v = '<?php echo $_GET['pageid'];?>';
var userid = '<?php echo $_SESSION['db_user_info']['id'] ?>';
$( document ).ready(function() {
$.ajax({
url: ""+rp+"invite.php?pageid="+v+"&userid="+userid,
type: 'POST',
beforeSend: function()
{
$("#loading_img").show();
},
success: function(data)
{
$("#loading_img").hide();
$("#Invite").append(data);
}
});
});
});
//And this is the invite.php
$('.gr-post-btn-submit').click(function(){ // when a feature button is selected
var rp = '<?php echo $config->baseUrl ;?>/themes/gr-mist/pagemenu/parts/';
var v = '<?php echo $_GET['pageid'];?>';
var userid = '<?php echo $user_id ?>';
var serialize = $('.abc').serialize(); // takes all the values of the filter
$.ajax({
type : 'POST',
url: ""+rp+"sendinv.php?pageid="+v+"&userid="+userid, // sends the values to ajax file
data : serialize,
beforeSend: function()
{
$("#loading_own").show();
$("#Invite").css({ opacity: 0.5 });
},
success: function(data)
{
$("#loading_own").hide();
$("#Invite").css({ opacity: 5.6 });
// $("#Invite").show();
//this is the portion where we have to do some thing to hide the inserting check boxes
}
});
});
<form method="post" class="abc" id="" name="inviteform"
enctype="multipart/form-data" action="#">
<?php
$sql = "select * from gr_user_friendships where toid=$user_id and status = 1";
$pagd = $_GET['pageid'];
$liked_users = $db->select($sql);
$count = 0;
for($i=0; $i<count($liked_users); $i++)
{
$extrct_fr = "select * from gr_page_likes where page_id=".$pagd." and receiver_id=".$liked_users[$i]['fromid'];
//echo $extrct_fr;
$frnd = $db->select($extrct_fr);
if(count($frnd)>0)
{
$invt = $db->select("select * from gr_user_friendships where toid=$user_id and fromid!=$frnd[0]['receiver_id']");
$invt_id = $invt[0]['fromid'];
}
else
{
$invt_id = $liked_users[$i]['fromid'];
}
if(!empty($invt_id))
$count = 1;
$user = "Select * from gr_users where id = $invt_id";
//echo $user;
$table = mysql_query($user);
$dbc = mysql_fetch_array($table);
$usid= $dbc['id'];
$bab = $dbc['name'];
$imgs = $dbc['avatar'];
$image_of_fr = $_SERVER['DOCUMENT_ROOT']."/uploads/users/".$usid."/profile/profile-pic/thumb/".$imgs;
$image_location_f = $config->baseUrl."/uploads/users/".$usid."/profile/profile-pic/thumb/".$imgs;
if(file_exists($image_of_fr))
{
$imgp = $image_location_f;
}
else
{
$imgp = $config->baseUrl."/themes/gr-mist/includes/images.jpg";
}
if(!empty($invt_id)){
?>
<style type="text/css">
#users_<?php echo $invt_id ?>
{
width:147px;
height:54px;
display:inline-block;
}
</style>
<input type="checkbox" class="checkbox1" id="gcc_<?php echo $invt_id ?>" name="pgliker[]" value="<?php echo $invt_id ?>"/>
<img width="30" height="30" src="<?php echo $imgp;?>"/>
<?php echo $bab; ?>
<?php
}
}//end of for
?>
<br>
<?php if($count){ ?>
<span style="color:blue; font-weight:bold;" >
<input type="checkbox" id="selecctall"/> Select All</span>
<input type="button" name="gr_submits" class="gr-post-btn-submit" value="invite" id="submits"/>
<?php } ?>
</form>
and this is the sendinv.php
global $db;
$myliker = $_POST['pgliker'];
$pageid = $_GET['pageid'];
$userid = $_GET['userid'];
foreach($myliker as $tps)
{
$sql = "Insert into gr_page_likes values('',$pageid,$userid,$tps,0)";
$db->insert($sql);
}
/**In you invite.php put the element which you want to hide after success
form submission into one div*//
//replace your one with this one.
<div id="gcc_<?php echo $invt_id ?>">
<input type="checkbox" class="checkbox1" name="pgliker[]" value="<?php echo $invt_id ?>"/>
<img width="30" height="30" src="<?php echo $imgp;?>"/>
<?php echo $bab; ?>
</div>
/**Now make an array in your sendinv.php and encode it with json incode***/
//replace your sendinv.php with this one.
$arr = array();
foreach($myliker as $tps)
{
$sql = "Insert into gr_page_likes values('',$pageid,$userid,$tps,0)";
$db->insert($sql);
$arr[] = $tps;
}
echo json_encode($arr);
exit;
/**After in your invite.php in the success block run
jquery foreach with the data and hide the checked boxes with the ids associted after submission. */
$.each( data, function( key, value ) {
// alert( key + ": " + value );
$("#gcc_"+value).hide();//the div for each checked user
});
I have a code in which i am having checkboxes of two categories one of brand and and other of discount percentage.Based on those checkboxes,div s are getting filtered.Filteration of divs is happening ok but with a small issue.
Below is the firstphp page
<html>
<head>
<title>Insert title here</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
#image{
width:250px;
height:250px;
border:1px solid black;
}
</style>
</head>
<body>
<script type="text/javascript">
function get_check_value() {
var c_value = [];
$('input[name="brand"]:checked').each(function () {
c_value.push(this.value);
});
return c_value.join(',');
}
function get_disc_value(){
var d_value=[];
$('input[name="discount"]:checked').each(function () {
d_value.push(this.value);
});
return d_value.join(',');
}
$(document).ready(function(){
checkboxValidate = function (e) {
if(e)e.preventDefault();
alert("hi");
//var os = $('#originState').val();
//var c = $('#commodity').val();
//var ds = $('#destState').val();
var ser = get_check_value();
var disc=get_disc_value();
//var queryString = "os=" + os;
var data = "?ser=" + ser;
var queryString = "&ser=" + ser;
// alert(ser);
$.ajax({
//alert("ajax");
type: "POST",
url: "sortingajax.php",
data: {ser:ser,disc:disc},
dataType : 'html',
success: function (b) {
// alert(a+' ok. '+b)
$('#results').html(b);
console.log(b);
}
});
}
$( "[type=checkbox]" ).change(checkboxValidate);
checkboxValidate();
});
</script>
brand
<input type="checkbox" name="brand" value="Sunbaby" id="check" />Sunbaby
<br/>
<input type="checkbox" name="brand" value="Advance Baby" id="check"/>Advance Baby
<br/>
store
<br/>
<input type="checkbox" name="discount" value="10" />10
<br/>
<input type="checkbox" name="discount" value="20" />20
<br/>
<input type="checkbox" name="discount" value="30" />30
<br/>
<button id="btnSubmit">sort</button>
<div id="image">
<img src="http://img5a.flixcart.com/image/sunglass/4/u/y/mb-d4-09b-miami-blues-free-size-275x275-imadzkhuchryqjgp.jpeg" width="250px" height="250px"/>
</div>
<div id="results">
sdfsdfsdfsdfdsfgsdgsbsfgvf
</div>
</body>
</html>
Asortingajax.php-where i m checking with database
<?php
include('connection.php');
$query=$_POST['ser'];
$query2=$_POST['disc'];
$query=explode(",",$query);
$query = array_filter($query);
$query2=explode(",",$query2);
$query2 = array_filter($query2);
$result=count($query);
$result1=count($query1);
//echo $result;
echo $query;
echo $query1;
echo $result1;
$parts = array();
$brandarray=array();
$discarray=array();
$limit = 10;
$offset = 0;
foreach( $query as $queryword ){
$brandarray[] = '`BRAND` LIKE "%'.$queryword.'%"';
}
foreach( $query2 as $discword ){
$discarray[] = '`DPERCENT` < '.$discword.'';
}
if(!empty($query) && !empty($query2))
{
echo "both loops";
$countsql2='SELECT * FROM xml WHERE ('.implode ('OR',$brandarray).') AND ('.implode ('OR',$discarray).') ';
print($countsql2);
$combinesql=mysql_query($countsql2);
$androws123 = mysql_num_rows($combinesql);
$countArray1=array();
echo "<br />";
echo $androws123;
$totalrows=0;
$orsqlrows=0;
while($row = mysql_fetch_array($countsql3)) {
// Append to the array
$countArray1[] = $row;
//echo $row['PID']."<BR />";
}
if(empty($countArray1))
{
echo "or";
$orsql='SELECT * FROM xml WHERE ('.implode ('OR',$brandarray).') AND ('.implode ('OR',$discarray).') ';
$orsql1=mysql_query($orsql);
$orsqlrows = mysql_num_rows($orsql1);
$countArray2=array();
echo $orsqlrows;
while($row = mysql_fetch_array($countsql1)) {
// Append to the array
$countArray2[] = $row;
//echo $row['PID']."<BR />";
}
}
$totalrows=$orsqlrows+$androws123;
echo $orsqlrows;
echo "hi";
echo $androws123;
if($totalrows==$androws123)
{
echo "and";
foreach( $brandcheck as $queryword ){
$brandarray[] = '`BRAND` LIKE "%'.$queryword.'%"';
}
$brandsql='SELECT * FROM XML WHERE ('.implode ('OR',$brandarray).') AND ('.implode ('OR',$discarray).') limit '.$offset.', '.$limit.' ';
$brandsql1=mysql_query($brandsql);
$numrows = mysql_num_rows($brandsql1);
$countArray=array();
//print($brandsql);
echo "<br />";
while($row = mysql_fetch_array($brandsql1)) {
// Append to the array
$countArray[] = $row;
//echo $row['PID']."<BR />";
}
}
else{
foreach( $brandcheck as $queryword ){
$brandarray[] = '`BRAND` LIKE "%'.$queryword.'%"';
}
echo "orloop";
$brandsql='SELECT * FROM XML WHERE ('.implode ('OR',$brandarray).') AND ('.implode ('OR',$discarray).') limit '.$offset.', '.$limit.' ';
//print($brandsql);
$brandsql1=mysql_query($brandsql);
$numrows = mysql_num_rows($brandsql1);
$countArray=array();
//print($brandsql);
echo "<br />";
echo $numrows;
while($row = mysql_fetch_array($brandsql1)) {
// Append to the array
$countArray[] = $row;
//echo $row['PID']."<BR />";
}
}
}
?>
<?php
foreach($countArray as $array)
{
?>
<div>
<img src="<?php echo $array['IMAGEURL']?>"/></div>
<?php $i++; } ?>
I n the first php page.when i m checking one brand checkbox and one discount checkbox at a time,means one from both brand and discount are checked.div s are getting filtered correctly.but when i check two checkboxes out of discount checkboxes and one from brand,I am not getting divs filtered correctly whereas div s should get filtered.
Help me guys where i m doing wrong in above code...
Have you echoed the query to see what you get? It seems to me it's working fine as long as there's no actual implode 'glue' used (the 'OR'). I think you need to change the glue part to ' OR ' (notice the spaces around it).