I have status active/Deactive Buttons when user clicks on active status it turns into deactive with red color and vice versa
currently i'm able to update my status #backend but everytime i should refresh to see my changes!!
my requirement is during active/deactive process of changing status i want to load ajax image loader where loader image should overlay entire screen. and my status should be updated in mysql db!!
please any help is appricated Thanks!
Php Code
<?php
include 'db.php';
$sql = "select * from sections order by id asc";
$data = $con->query($sql);
$str='';
if($data->num_rows>0)
{
while( $row = $data->fetch_array(MYSQLI_ASSOC))
{
$str.="
"?>
<div class="row">
<div class="col-md-1">
<?php
if ($row['status'] == '1')
{
?>
<a href="#" class="btn btn-success btn-sm active" ida='<?php echo $row['id'];?>'></a>
<?php }
else if($row['status'] == '0')
{
?>
<a href="#" class="btn btn-danger btn-sm deactive" idde='<?php echo $row['id'];?>'></a>
<?php } ?>
</div>
</div>
<?php
}
}
else
{
$str .= "<p style='text-align:left;'>No Data Available</p>";
}
echo $str;
?>
Jquery Code
<script type="text/javascript">
$('body').delegate('.active','click',function(e){
var IdStatus = 0;
var id = $(this).attr('ida');
$.ajax({
url:"pages/status1.php",
data:{
status:IdStatus,
id:id
},
dataType:'html',
success:function()
{
alert('success');
}
});
e.preventDefault();
return false;
});
$('body').delegate('.deactive','click',function(e){
var IdStatus = 1;
var id = $(this).attr('idde');
$.ajax({
url:"pages/status1.php",
data:{
status:IdStatus,
id:id
},
dataType:'html',
success:function()
{
alert('success');
}
});
e.preventDefault();
return false;
});
</script>
PHP Updation Code
<?php
if(isset($_REQUEST['status']))
{
$status = $_REQUEST['status'];
$id = $_REQUEST['id'];
$sql = 'update sections set status='.$status.' where id='.$id.'';
$result = mysql_query($sql);
if($result)
{
echo 'updated successfully';
}
else
{
echo 'failed to update';
}
}
?>
Try this script with mentioned changes:
Changes:
Keep same attribute as data-id for both the operations
loaderElem will be the loader container which should be there in your DOM
BODY is nothing but a body selector, just to avoid redundant selectors
var elem = $(this); is used as I need this reference after success callback
Also make habit of using error callback as you might need to handle that case
var BODY = $('body');
var loaderElem = $('#loader');
BODY.delegate('.active', 'click', function(e) {
loaderElem.show();
var IdStatus = 0;
var elem = $(this);
var id = elem.attr('data-id');
$.ajax({
url: "pages/status1.php",
data: {
status: IdStatus,
id: id
},
dataType: 'html',
success: function() {
elem.removeClass('active').addClass('deactive');
loaderElem.hide();
alert('success');
}
});
e.preventDefault();
return false;
});
BODY.delegate('.deactive', 'click', function(e) {
loaderElem.show();
var IdStatus = 1;
var elem = $(this);
var id = elem.attr('data-id');
$.ajax({
url: "pages/status1.php",
data: {
status: IdStatus,
id: id
},
dataType: 'html',
success: function() {
elem.removeClass('deactive').addClass('active');
loaderElem.hide();
alert('success');
}
});
e.preventDefault();
return false;
});
Try using beforeSend option of $.ajax()
$('body').delegate('.active','click',function(e){
var IdStatus = 0;
var id = $(this).attr('ida');
$.ajax({
url:"pages/status1.php",
beforeSend: function() {
// do overlay stuff
},
data:{
status:IdStatus,
id:id
},
dataType:'html',
success:function()
{
// remove overlay stuff
alert('success');
}
});
e.preventDefault();
return false;
});
Related
I am working on a jQuery load more data scroll, which when I click on category link it will sort the data based on that category I click, which is working well. It only load first six how can I fix this issue.
index.php
Category
<div class="container">
<div class="row" id="results"></div>
<div id="loader_image" align="center">
<img src="loader.gif" alt="" width="50">
</div>
<div id="loader_message" align="center"></div>
</div>
<script type="text/javascript">
//For The Scroll
var busy = false;
var limit = 6
var offset = 0;
var where = '<?php if(isset($_GET["where"])) {echo $_GET['where'];} else {echo ' ';} ?>';
function displayRecords(lim, off, where) {
$.ajax({
type: "GET",
async: false,
url: "<?php echo(link);?>getrecords.php",
data: "limit=" + lim + "&offset=" + off + "&where=" + where,
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
success: function(html) {
$("#results").append(html);
$('#loader_image').hide();
if (html == "") {
$("#loader_message").html('<button class="btn btn-default" type="button">No more records.</button>').show()
} else {
// $("#loader_message").html('<button class="btn btn-default" type="button">Loading please wait...</button>').show();
$('#loader_image').show();
}
window.busy = false;
}
});
}
$(document).ready(function() {
// start to load the first set of data
if (busy == false) {
busy = true;
// start to load the first set of data
displayRecords(limit, offset, where);
}
$(window).scroll(function() {
// make sure u give the container id of the data to be loaded in.
if ($(window).scrollTop() + $(window).height() > $("#results").height() && !busy) {
busy = true;
offset = limit + offset;
where = '<?php if(isset($_GET["where"])) {echo $_GET['where'];} else {echo ' ';} ?>';
// this is optional just to delay the loading of data
setTimeout(function() { displayRecords(limit, offset, where); }, 500);
// you can remove the above code and can use directly this function
// displayRecords(limit, offset);
}
});
});
</script>
getrecords.php
$where = '';
if(isset($_GET['where'])){
$search = str_replace('-',' ', $_GET['where']);
$where .= "WHERE category LIKE '%$search%'";
}
$limit = (intval($_GET['limit']) != 0 ) ? $_GET['limit'] : 6;
$offset = (intval($_GET['offset']) != 0 ) ? $_GET['offset'] : 0;
$sql = "SELECT * FROM users {$where} ORDER BY id ASC LIMIT $limit OFFSET $offset";
try {
$stmt = $user->runQuery($sql);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $res) {
?>
<div class="col-sm-4 my-4 text-center">
<div class="card">
<img class="rounded-circle img-fluid d-block mx-auto" src="http://placehold.it/200x200">
<h3><?php echo ucwords($res['name']); ?></h3>
<small><?php echo $res['category']; ?></small>
</div>
</div>
<?php
}
}
?>
see below preview it image of the issue
If the loading icon is never removed check the console for any errors. You're setting the loading icon to be shown in the beforeSend function but have no error property in the ajax handler.
Remove $("#results").append(html); from the top of your success: function(html) { .. } and move it into the else portion of your if statement. You do this so you're not attempting to append an empty string, or an unwanted string, for no reason and we have finer control over it via our if/else logic.
You'll also want to remove $('#loader_image').show() from the else statement. You're re-showing it even though the ajax call has been processed successfully.
See the cleaned up success function below.
success: function(html) {
$('#loader_image').hide();
if (html == "") {
$("#loader_message").html('<button class="btn btn-default" type="button">No more records.</button>').show()
} else {
$("#results").append(html);
}
window.busy = false;
}
New ajax call:
$.ajax({
type: "GET",
async: false,
url: "<?php echo(link);?>getrecords.php",
data: "limit=" + lim + "&offset=" + off + "&where=" + where,
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
success: function(html) {
$('#loader_image').hide();
if (html == "") {
$("#loader_message").html('<button class="btn btn-default" type="button">No more records.</button>').show()
} else {
$('#results').append(html);
}
window.busy = false;
},
error: function(error) {
console.log(error);
$('#loader_image').hide();
$('#loader_message').html('There was an error processing your request.').show();
}
});
how do we disable the button when all posts are loaded ?
all post loaded = button disabled or hide
or show another way ajax load more pagination codeigniter :(
I know little english sorry
Controller
public function getCountry(){
$page = $_GET['page'];
$this->load->model('posts_model');
$posts = $this->posts_model->getCountry($page);
foreach($posts as $post){
echo "<h3>".$post->post_title."</h3><td>".$post->post_content."</td>";
}
exit;
}
Model
public function getCountry($page){
$offset = 2*$page;
$limit = 2;
$sql = "select * from posts limit $offset ,$limit";
$result = $this->db->query($sql)->result();
return $result;
}
Script
<script>
$(document).ready(function(){
getcountry(0);
$("#load_more").click(function(e){
e.preventDefault();
var page = $(this).data('val');
getcountry(page);
});
});
var getcountry = function(page){
$("#loader").show();
$.ajax({
url:"<?php echo base_url() ?>welcome/getCountry",
type:'GET',
data: {page:page}
}).done(function(response){
$("#ajax_table").append(response);
$("#loader").hide();
$('#load_more').data('val', ($('#load_more').data('val')+1));
scroll();
});
};
var scroll = function(){
$('html, body').animate({
scrollTop: $('#load_more').offset().top
}, 1000);
};
</script>
In your get country function you can do like this. so whenever you get the empty results it means no more result available and your button will be disabled.
<script>
var getcountry = function(page){
$("#loader").show();
$.ajax({
url:"<?php echo base_url() ?>welcome/getCountry",
type:'GET',
dateType:'json',
data: {page:page}
}).done(function(response){
if(response.result == 'success') {
$("#ajax_table").append(response.data);
$("#loader").hide();
$('#load_more').data('val', ($('#load_more').data('val')+1));
scroll();
} else {
$("#load_more").prop('disabled',true);
}
});
};
</script>
In your controller make this changes
public function getCountry(){
$page = $_GET['page'];
$this->load->model('posts_model');
$posts = $this->posts_model->getCountry($page);
$response = array();
$data = '';
if(!empty($posts)) {
foreach($posts as $post){
$data .= "<h3>".$post->post_title."</h3><td>".$post->post_content."
</td>";
}
$response = array('result'=>'success','data'=>$data);
} else {
$response = array('result'=>'error');
}
echo json_encode($response)
}
I am using javascript to alert user if he is sure to delete row from database.
In html table I am using column for deleting rows.
<td><center><a href="" id="brisi" value="<?=$r['Id']; ?>" class="delete" data-confirm="Are you sure that you want to delete?"><i class="fa fa-times"></i></center>
I am using script to alert user then to navigate to php script to delete row
<script>
var deleteLinks = document.querySelectorAll('.delete');
for (var i = 0; i < deleteLinks.length; i++) {
deleteLinks[i].addEventListener('click', function(event) {
event.preventDefault();
var choice = confirm(this.getAttribute('data-confirm'));
if (choice==true) {
var x =document.getElementById("brisi").value;
$.ajax({ url: 'edit/delete.php?a=1',
type: 'post',
success: function(output) {
document.getElementById("brisi").value = output;
}
});
}
if (choice==false) {
return false;
}
});
}
</script>
Php script
<?php
if ($_GET['a']==1) {
$id = test_input($_POST['brisi']);
echo $id;
}
?>
I am trying to send value of each row. For some reason my js does not work, could anyone provide quick advice?
you should change your html
<td><center><a href="javascript:;" data-value="<?=$r['Id']; ?>" class="delete" data-confirm="Are you sure that you want to delete?"><i class="fa fa-times"></i></center>
and also change javascript
$('.delete').off('click').on('click', function(e){
e.preventDefault();
var choice = confirm($(this).data('confirm'));
if(choice){
var x = $(this).data('value');
$.ajax({
url: 'edit/delete.php?a=' + x,
type: 'post',
success: function(output) {
document.getElementById("brisi").value = output;
}
});
}
else{
return false;
}
});
and php code
<?php
if (isset($_GET['a']) && $_GET['a'] != ''){
$id = test_input($_GET['a']);
echo $id;
}
?>
onclick="return confirm('Are you sure you want to delete this item?');"
I would like to know why you are checking for this:
var x =document.getElementById("brisi").value;
And you don't use it.
I hope also that 'brisi' is the unique ID only for this element.
Next you are doing a POST request with ajax:
$.ajax({ url: 'edit/delete.php?a=1',
type: 'post',
success: function(output) {
document.getElementById("brisi").value = output;
}
});
I notice in your PHP you are trying to GET your posted vriable:
if ($_GET['a']==1) {
$id = test_input($_POST['brisi']);
echo $id;
}
And you should do:
if (isset($_POST['a') && $_POST['a'] == 1) {
$id = test_input($_POST['brisi']);
echo $id;
}
And finally what is this function doing:
test_input($_POST['brisi'])
You don't have any posted value with this index.
To recap If you need more help please post your complete HTML form.
I have a problem with my code. I am studying jquery ajax. And I have a difficulty in it. I am creating an 'add to cart' function in my simple e-commerce site. And I am doing this with database interaction. Here's what I did so far.
Here's my PHP part
$product_id = $_GET['product'];
....
<input type="hidden" name="cart_product_id" id="cart_product_id" value="<?php echo $product_id; ?>" />
<input type="hidden" name="cart_user_id" id="cart_user_id" value="<?php echo $_SESSION['member']; ?>" />
Here's my javascript part
function notification_message(type) {
var confirmation = '';
if(type == 'cart') {
confirmation = '#cart_confirm';
} else {
confirmation = '#wishlist_confirm';
}
$(confirmation).dialog({
resizable: false,
height: 220,
modal: true,
draggable: false,
buttons: {
"Yes": function() {
if(type == 'cart'){
add_cart();
} else {
add_wishlist();
}
},
"No": function() {
$( this ).dialog( "close" );
}
}
});
}
//this is the main function I need to process
function add_cart(){
var cart_product_id = $("#cart_product_id").val();
var cart_user_id = $("#cart_user_id").val();
var url_add_cart = '<?php echo $_SERVER['DOCUMENT_ROOT'].'ahm/secure/aroma/aroma_shop.php'; ?>';
console.log(url_add_cart);
$.ajax({
type: 'POST',
url: url_add_cart,
data: { user_id: cart_user_id, product_id: cart_product_id },
dataType: 'json',
success: function(d) {
console.log(d);
}
});
}
function add_wishlist(){
alert('wishlist');
}
$('#register_user').click(function(){
$('#failed').dialog('close');
});
function failed() {
$("#failed").dialog({
resizable: false,
height: 220,
modal: true,
draggable: false,
});
}
$(document).ready(function(){
$("#mycart").click(function(){
var product_id = $('#mycart').data('cart-id');
var member_id = '<?php echo $_SESSION[member]; ?>';
var type = 'cart';
notification_message(type);
});
$("#mywishlist").click(function(){
var product_id = $('#mywishlist').data('wishlist-id');
var member_id = '<?php echo $_SESSION[member]; ?>';
var type = 'wishlist';
if (member_id == '') {
failed();
} else {
notification_message(type);
}
});
});
Now here's my separate PHP file that contains the sql query it contains.
function get_cart($user_id) {
$query = mysql_query("SELECT * FROM product_cart WHERE user_id = ".$user_id."");
$row = mysql_fetch_array($query);
return $row;
}
function count_cart($user_id) {
$query = mysql_query("SELECT COUNT(*) AS cart_total FROM product_cart WHERE user_id = ".$user_id."");
$row = mysql_fetch_array($query);
return $row['cart_total'];
}
//now, how can I access here the variable I set in the PHP?
function insert_cart(){
//this should be the query part but I dont know how to access the variable
}
In ajax call, you can pass some variable with the url, say url_add_cart+"type=insert_cart"
Then at start of PHP, check-
if(isset($_GET['type'] == "insert_cart"))
echo insert_cart();
Now, in that function just get your variables as- $_POST['user_id'] and $_POST['product_id']; do the processing and return whatever you want to return.
Note, return your array after json encoding it- echo json_encode($result_array) - also, use echo not return; since ajax call just get the contents of the url (just like curl)
can anyone help me...how do i put an conditional alert dialog box in ajax that if the data in a query is successfully saved or the data already been saved.
I want to do is if the query is saved an alert box will pop-op same goes to if the data is already been saved.
script code:
<script type="text/javascript">
$(document).ready(function () {
$('#updates').click(function (e) {
e.preventDefault();
var data = {};
data.region_text = $('#t_region').val();
data.town_text = $('#t_town').val();
data.uniq_id_text = $('#t_uniq_id').val();
data.position_text = $('#t_position').val();
data.salary_grade_text = $('#t_salary_grade').val();
data.salary_text = $('#t_salary').val();
for(var $x=1;$x<=15;$x++) {
data['id'+$x+'_text'] = $('#id'+$x).val();
data['aic'+$x+'_text'] = $('#aic'+$x).val();
data['name'+$x+'_text'] = $('#name'+$x).val();
data['optA'+$x+'_text'] = $('#optA'+$x).val();
data['optB'+$x+'_text'] = $('#optB'+$x).val();
data['optC'+$x+'_text'] = $('#optC'+$x).val();
data['optD'+$x+'_text'] = $('#optD'+$x).val();
data['other_qual'+$x+'_text'] = $('#other_qual'+$x).val();
data['interview'+$x+'_text'] = $('#interview'+$x).val();
data['total'+$x+'_text'] = $('#total'+$x).val();
}
$.ajax({
type: "POST",
url: "insert.php",
data: data,
cache: false,
success: function (response) {
// We are using response to distinguish our outer data variable here from the response
}
});
});
});
</script>
insert.php code:
<?php
include('../connection.php');
date_default_timezone_set('Asia/Manila');
$region = #$_POST['region_text'];
$town = #$_POST['town_text'];
$uniq_id = #$_POST['uniq_id_text'];
$position = #$_POST['position_text'];
$salary_grade = #$_POST['salary_grade_text'];
$salary = #$_POST['salary_text'];
$dupesql = "SELECT * FROM afnup_worksheet WHERE funiq_id = '$uniq_id'";
$duperow = mysql_query($dupesql);
if(mysql_num_rows($duperow) > 0){
exit;
}else{
for($n=1;$n<=15;$n++) {
$id = #$_POST['id'.$n.'_text'];
$aic = #$_POST['aic'.$n.'_text'];
$name = #$_POST['name'.$n.'_text'];
$optA = #$_POST['optA'.$n.'_text'];
$optB = #$_POST['optB'.$n.'_text'];
$optC = #$_POST['optC'.$n.'_text'];
$optD = #$_POST['optD'.$n.'_text'];
$other_qual = #$_POST['other_qual'.$n.'_text'];
$interview = #$_POST['interview'.$n.'_text'];
$total = #$_POST['total'.$n.'_text'];
if(!empty($name)){
$query = "INSERT INTO afnup_worksheet (faic,fregion,ftown,funiq_id,fposition,fsalary_grade,fsalary,fnl_name,edu_attain,experience,seminars,eligibility,other_qual,interview,ftotal,dateinputed)
VALUES
('$aic','$region','$town','$uniq_id','$position','$salary_grade','$salary','$name','$optA','$optB','$optC','$optD','$other_qual','$interview','$total',CURRENT_TIMESTAMP)";
$resource = mysql_query($query) or die(mysql_error());
}
}
}
?>
Just return that status from PHP:
if(mysql_num_rows($duperow) > 0){
echo "1"; // Dup status
exit;
}else{
// All your else code.. echo must be the last thing inside your else block
echo "2"; // Saved status
}
Then in your ajax success callback you check it:
$.ajax({
type: "POST",
url: "insert.php",
data: data,
cache: false,
success: function (response) {
if (Number(response) == 1)
{
alert("Dup message");
}
else
{
alert("Saved message");
}
}
});
Instead of exit; in your conditinal for dupes, you could echo "duplicate". Also you should remove die() after your $resource and add if ($resource) echo "ok"; else echo "error";
Then in your success function(response) in javascript you can do if (response=="...") echo duplicate; else if ...
This is just basic explanation, but it should be enough to point you in the right direction.