I am displaying ajax likes on number of posts but the problem is that when i click 'like button' the likes (without loading the page) display on first post only and when i refresh the page all the likes display on their own places.
I want to show ajax like on the particular post not on only the first one. I guess i need to pass the ID in success function but i do not know how. Here is the code.
In my code: a Rumor is a post, Like = approve, dislike = disapprove.
View Ajax + That Particular part of Html View
function approve_rumor(r_id) {
// alert("dfdfdf");
$.ajax({
type: "post",
url: "<?php echo base_url('Home1/approve_rumor') ?>",
data: {
r_id: r_id
},
cache: false,
success: function(val) {
if (true) {
$('#showapp').html(val);
} else {
// <?php //echo base_url('Login'); ?>;
alert("You need to Login");
}
}
});
}
<span class="like-listing fll approve" onclick="approve_rumor(<?php echo $rumors->rumor_id; ?>)">
<i class="fa fa-thumbs-o-up" aria-hidden="true"></i>
</span>
<span id="showapp" class="fll"><?php echo $rumors->rumor_totalapprovals ?></span>
Controller
function approve_rumor() {
if ($this - > session - > userdata('user_email', 'user_id')) {
$this - > load - > model('rumor_model');
$r_id = $this - > input - > post('r_id');
$data['user_id'] = $this - > session - > userdata('user_id');
$data['rumor_id'] = $r_id;
$this - > rumor_model - > ApproveRumor($data);
//$this->load->view('home1',['approval'=>$approval]);
} else {
return redirect('Login');
}
}
function ApproveRumor($data) {
// echo "<pre>";
// print_r($data);
// exit;
$r_id = $data['rumor_id'];
$query = $this - > db - > insert('approval', $data);
if ($query) {
$a = $this - > db - > query("SELECT * , count(rumor_id) as count_like FROM approval WHERE rumor_id = $r_id ");
echo "<pre>";
print_r($a - > row() - > count_like);
$totalapprovals = $a - > row() - > count_like;
$this - > db - > query("UPDATE rumors SET rumor_totalapprovals = $totalapprovals WHERE rumor_id = $r_id");
// echo $totalapprovals;
// $this->db->where('rumors.rumor_id',$r_id);
// $res = $this->db->update('rumors',$totalapprovals);
} else {
echo "0";
}
}
A cool way I've found to pass data through to the $.ajax callback function is adding a custom option and then referencing it in the $.ajax callback as this.optionProp:
$.ajax({
type: "post",
url: "your/url/here",
data: {
r_id: r_id
},
r_id:r_id, //Your custom option
cache: false,
success: function(val) {
console.log("r_id: " + this.r_id); //The custom option can be referenced with this.optProp
}
});
Let me know if this helps or is not what you are looking for and we'll get it fixed
You need to return an object from your server side function that has an id attribute so you can call it after success like this:
function approve_rumor(r_id) {
// alert("dfdfdf");
$.ajax({
type: "post",
url: "<?php echo base_url('Home1/approve_rumor') ?>",
data: {
r_id: r_id
},
cache: false,
success: function(val) {
var id = val.id; //gets the id attribute from the returned val Object
}
});
}
Related
I have created an AJAX function that gets an input from a user and returns a match from an SQL database into a drop down box with PHP. When the user clicks on an item from the drop down it fills the box with the SQL data and fills two more boxes with other necessary data. Next, I can get the data from all boxes and put it into an interactive table using javascript. This function works most of the time but sometimes the variables lose the necessary data before the user clicks to append it to the table. It also feels like it needs some optimization so that the AJAX request isn't so resourceful. Is there any better way to pull data from the SQL database? Maybe a JSON file?
AJAX
//Getting value from "ajax.php".
function fill(Value) {
$('#search').val(Value);
$('#display').hide();
}
$(document).ready(function() {
$("#search").keyup(function() {
var food_name = $('#search').val();
if (food_name == "") {
$("#display").html("");
}
else {
$.ajax({
type: "GET",
url: "ajax.php",
data: {
search: food_name
},
success: function(html) {
$("#display").html(html).show();
}
});
}
});
});
function fill2(Value2) {
$('#search2').val(Value2);
$('#display2').hide();
}
$(document).ready(function() {
$("#search2").keyup(function() {
var food_category = $('#search2').val();
if (food_category == "") {
$("#display2").html("");
}
else {
$.ajax({
type: "GET",
url: "ajax.php",
data: {
search: food_category
},
success: function(html) {
$("#display2").html(html).show();
}
});
}
});
});
function fill3(Value3) {
$('#search3').val(Value3);
$('#display3').hide();
}
$(document).ready(function() {
$("#search3").keyup(function() {
var food_time = $('#search3').val();
if (food_time == "") {
$("#display3").html("");
}
else {
$.ajax({
type: "GET",
url: "ajax.php",
data: {
search: food_time
},
success: function(html) {
$("#display3").html(html).show();
}
});
}
});
});
PHP
<?php
include "config.php";
if (isset($_GET['search'])) {
$Name = $_GET['search'];
$Query = "SELECT food_name, food_category, food_time FROM food WHERE food_name LIKE '%$Name%' ";
$ExecQuery = MySQLi_query($link, $Query);
echo '
<ul>
';
while ($Result = MySQLi_fetch_array($ExecQuery)) {
?>
<li onclick='fill("<?php echo $Result['food_name']; ?>")'>
<p onclick='fill2("<?php echo $Result['food_category']; ?>")'>
<p2 onclick='fill3("<?php echo $Result['food_time']; ?>")'>
<a>
<?php echo $Result['food_name']; ?>
<?php echo $Result['food_category']; ?>
<?php echo $Result['food_time']; ?>
</li></a>
<?php
}}
?>
</ul>
I have read many answers on stack overflow but I can't find an apt answer. I want to send multiple variables from php file to a javascript file. I want to use those variables later separately. So please explain with a simple example of how to get the variables from php file and how to use them separately later.
This is my js.
<script>
function here(card_numb) {
alert("pk!");
$.ajax({
url: 'details.php',
type: "GET",
dataType: 'json',
data: ({
card_number: card_numb
}),
success: function(data) {
console.log('card_number:'+data.card_number+'book_issued:'+data.book_isued);
}
});
}
I'm getting the alert 'pk!'. But $.ajax ain't working.
This is details.php
<?php
if(isset($_GET['card_number'])){
$card_number = $_GET['card_number'];
$query = "Select * from users where card_number = '".$card_number."'";
$query_run = mysqli_query($link,$query);
$row_numb =#mysqli_num_rows($query_run);
if($row_numb == 0){
echo "<div class='bdiv1'>No such number found!</div>";
} else{
$row=mysqli_fetch_assoc($query_run);
$book1 = $row['user_name'];
$arr = array('isued_book' => $book1,'card_number' => $card_number);
echo json_encode($arr);
exit();
}
}
?>
Thank you!
somthing.js - ur jspage
<script>
function here(card_numb) {
$.ajax({
url: 'details.php',
type: 'GET',
dataType: 'json',
data: {
card_number: card_numb
},
success: function(data) {
console.log('card_number:'+data.card_number+'book_issued:'+data.isued_book);
}
});
}
success: function(result){
console.log('variable1:'+result.var1+'variable2:'+result.var2+'variable3:'+result.var3);
} });
details.php
<?php
if(isset($_GET['card_number'])){
$card_number = $_GET['card_number'];
$query = "Select * from users where card_number = ".$card_number;
$query_run = mysqli_query($link,$query);
$row_numb =#mysqli_num_rows($query_run);
if(!$query_run){
echo "<div class='bdiv1'>No such number found!</div>";
} else {
$row=mysqli_fetch_assoc($query_run);
$book1 = $row['user_name'];
$arr = array('isued_book' => $book1,'card_number' => $card_number);
echo json_encode($arr);
exit();
}
if the currect value get in $row you can get the result in console
I am using AJAX to loadmore data from an image gallery.
I pass PHP variable to set the $page number and other data. Each time I loadmore data from AJAX, I would like the $page to increase by 1 so next time, it gets the next data on the list. Here is my JS
$(window).bind('scroll', function() {
if($(window).scrollTop() >= $('#postswrapper').offset().top + $('#postswrapper').outerHeight() - window.innerHeight) {
$('div#loadmoreajaxloader').show();
$.ajax
({
url: "loadmore.php",
method: "get",
data: { page: "<?=$page?>", perpage: "<?=$perpage?>"},
success: function(html)
{
if(html)
{
$("#postswrapper").append(html);
$('div#loadmoreajaxloader').hide();
// ###### THIS IS NOT WORKING
<? $page++; ?>
}
else
{
$('div#loadmoreajaxloader').html('<center>No more posts to show.</center>');
}
}
}); // close AJAX
} // close if()
}); // close $(window)
I tried incorporating <? $page++; ?> in the success function, but it's not working.
I USE THE $page variable inside my SQL query
HERE IS MY loadmore.php CODE
if (isset($_GET['page']))
{
$page = $_GET['page'];
$perpage = $_GET['perpage'];
$start = ($page -1) * $perpage ;
$sql = mysql_query("select * from ..... limit ".$start.", ".$perpage." ");
$html = '';
while($blog2 = mysql_fetch_array($sql))
{
$html .='HTML GOES HERE';
}
echo $html;
exit;
}
What I'm trying to achieve is to load the SQL query starting from the next page every time I load more data... Any suggestions on how I should proceed?
First, remember to sanitize any user input in your PHP file to prevent sql injection:
$page = $_GET['page'];
$perpage = $_GET['perpage'];
// escape the values, or make sure they are numbers, e.g.:
if(!is_numeric($page))
$page = 0;
if(!is_numeric($perpage))
$perpage = 10; // or whatever default value
And write your PHP values into Javascript variables and use those in your js code:
var pageNumber = <?= $page ?>;
var perPage = <?= $perpage ?>;
$(window).bind('scroll', function() {
if($(window).scrollTop() >= $('#postswrapper').offset().top + $('#postswrapper').outerHeight() - window.innerHeight) {
$('div#loadmoreajaxloader').show();
$.ajax
({
url: "loadmore.php",
method: "get",
data: { page: pageNumber, perpage: perPage},
success: function(html)
{
if(html)
{
$("#postswrapper").append(html);
$('div#loadmoreajaxloader').hide();
// use the js variable
pageNumber++;
}
else
{
$('div#loadmoreajaxloader').html('<center>No more posts to show.</center>');
}
}
}); // close AJAX
} // close if()
}); // close $(window)
No
PHP runs server-side, the AJAX runs client side. You need a javascript variable there (although you can set its initial value with PHP).
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;
});
I want to load more than 10 rows from my table with jQuery, but it's not working.
My php code: (...chat.php?load=archive)
} else if (isset($_GET["load"]) && $_GET["load"] == "archive") {
echo "<script type='text/javascript' src='includes/js/chatArchive.js'></script>";
$limit = (int)$_POST["limit"];
$result = mysql_query("SELECT * FROM `chat` ORDER BY `date` DESC LIMIT ".$limit.", 2");
if (mysql_num_rows($result)) {
while($db = mysql_fetch_array($result)) {
echo "..."; // My datas...
}
echo "<div style='text-align: center; margin: 10px 0 10px 0;'>\n";
echo "<input type='submit' value='Load more rows' class='loadMore'>\n";
echo "</div>\n";
}
}
My JS file: (chatArchive.js)
var limit = 50;
$(document).ready(function() {
$(".loadMore").click(function() {
limit += 10;
$.ajax({
url: "../../../system/functions/chat.php?load=archive",
type: "POST",
data: { "limit" : limit },
success: function() {
alert("Success...");
console.log(limit); // This displayed my console!!!
}
});
});
});
Can anyone point out the problem?
Function which is defined as a callback for success property has an argument, usually called data, which is the returned value from your script. So, you should change your success function as follows:
success: function(data) { // see data here
alert("Success...");
console.log(limit); // This displayed my console!!!
console.log( data ); // check what data contains
}
Also it's a good practice to add error callback, which will indicate that something bad happens:
$.ajax({
url: "../../../system/functions/chat.php?load=archive",
....
error: function() {
alert("Bad thing happenned!");
}
)};
your ajax method is POST but in your php script you check GET request
if (isset($_GET["load"]) && $_GET["load"] == "archive")
Change Your ajax method to GET