i'm trying to make a notification tab work but do not seem to get it right. The dropdown is working fine but the ajax call to newfriends.php is not working right, when viewed with firebug there are no results to be seen in the dropdown.Quite confusing.
(note the dropdown menu is located in header and can only be displayed if the session is initialised)
here is the ajax used in jquery:
function load_notifications(view=''){
$.ajax({
url: "notification/new_friends.php",
method: "POST",
data:{view:"view"},
dataType:"json",
success: function(data){
$(".dropdown-menu").html(data.notification);
if(data.unseen_notification>0){
$(".badge1").html(data.unseen_notification);
}
}
});
//$(".dynamic-notification").load("notification/pm_n.php");
// $(".dynamic-notification-f").load("notification/new_friends.php");
};
load_notifications();
$(document).on("click",".count_friend", function(){
load_notifications('yes');
});
//loads every 2 seconds for chat
setInterval(function(){load_notifications();},2000);
here is the new_friends.php content:
<?php
include '../includes/dbconfig.inc.php';
if (isset($_POST['view'])) {
if($_POST['view'] !=''){
$update="update friends set count='1' where friend_one=:session and count='0'";
$stmt=$conn->prepare($update);
$stmt->bindValue(":session", $_SESSION['uname']);
$stmt->execute();
}
$sql123="select id from friends where friend_two=:sess_uname and count='0'";
$stmt123=$conn->prepare($sql123);
$stmt123->bindValue(":sess_uname", $_SESSION['uname']);
$stmt123->execute();
$request_count=$stmt123->fetchColumn();
//$count_friend=$stmt123->rowCount();
/*$sql_f_count="select *from user where user_id=:session_id and activated='1' limit 1";
$stmt_f_count=$conn->prepare($sql_f_count);
$stmt_f_count->bindValue(":session_id", $_SESSION['id']);
$stmt_f_count->execute();
$user_details=$stmt_f_count->fetchAll();
$friend_badge=$user_details[0]['friend_count_badge'];*/
require "notification/friend_request_notification.php";
// $new_friends="<span class='dropdown'><a href='#' data-placement='bottom' class='btn dropdown-toggle' data-toggle='dropdown' title='Friend Requests' data-html='true'><span class='count_friend' style=' height:33px; width:30px;'><span class='badge1 label label-pill'>".$count."</span><img src='img/logo/group-button-white.png' style='height:25px; width:27px;' alt='new_friends_alert'></span></a><ul class='dropdown-menu'></ul></span>";
//if($request_count[0]>0){
//$new_friends="<a href='#' data-placement='bottom' class='btn' data-trigger='focus' title='Friend Requests' data-toggle='popover' data-html='true' data-content='".$friend_requests."'><span class='count_friend' style=' height:33px; width:30px;'><img src='img/logo/group-button-white.png' style='height:25px; width:27px;' alt='new_friends_alert'></span><span class='badge'>".$friend_badge."</span></a>";
/*}else{
$new_friends="<a href='all_notifications.php'><img src='img/logo/group-button-black.png' style='height:25px; width:27px;' alt='new_friends_alert'></a>";
}*/
//echo $new_friends;
//}
$data=array(
'notification'=>$friend_requests,
'unseen_notification' =>$request_count[0][0]
);
}
echo json_encode($data);
and the code for friend requests output:
<?php
//error_reporting(0);
require_once 'includes/dbconfig.inc.php';
$sql = "select * from friends where friend_two=:session and accepted='0' order by friends_date_made asc";
$stmt = $conn->prepare($sql);
$stmt->bindparam(":session", $_SESSION['uname']);
$stmt->execute();
$numrows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$friend_requests="";
if ($numrows < 1) {
$friend_requests = "You do not have any friend requests";
echo "$friend_requests";
exit();
} else {
foreach ($numrows as $i=>$row1 ) {
$reqid = $row1['friend_id'];
$user1 = $row1['friend_one'];
$datemade = $row1['friends_date_made'];
$datemade1 = strftime("%B %d, %y", strtotime($datemade));
$sql = "SELECT * FROM user WHERE uname=:user1 LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bindparam(":user1", $user1);
$stmt->execute();
$thumbrow = $stmt->fetchAll(PDO::FETCH_ASSOC);
$user1avatar = $thumbrow[$i]['avatar'];
$user1id=$thumbrow[$i]['user_id'];
if ($user1avatar =="") {
$user1pic = '<img src="img/avatardefault.png" height="50" style="float:left;" width="50" alt="'.$user1.'" class="user_pic">';
} else {
$user1pic = '<img src="../user/user/'.$user1id.'/'.$user1avatar.'" height="50" style="float:left;" width="50" alt="'.$user1.'" class="user_pic">';
}
$friend_requests .= '<li><div id="'.$reqid.'" float="right" class="friendrequests">
'. $user1pic .'
<div class="user_info '.$reqid.'" id="'.$reqid.'"><small>' . $datemade1 . '</small>
'.$user1.' is requesting your friendship<br /><br />
<button id="'.$reqid.'" name="'.$_SESSION['uname'].'" sess="'.$_SESSION['id'].'" class="accept_btn btn btn-warning">Accept</button><span class="show-spinner"></span> or
<button id="'.$reqid.'" name="'.$_SESSION['uname'].'" sess="'.$_SESSION['id'].'" class="reject_btn btn btn-warning">Reject</button>
</div>
</div><hr></li>';
}
}
You currently have data:{view:"view"}.
Which means that you are passing string 'view' in the body of your request.
Change it to something like:
function load_notifications(thisview=''){
var theData = {
view: thisview
}
$.ajax({
url: "notification/new_friends.php",
method: "POST",
data: theData,
dataType:"json",
success: function(data){
Related
I have this php page with javascript ajax which calls another php file. But every time it calls, it refreshes the page.
I tried these two codes but still it keeps refreshing after calling the `php file:
e.preventDefault();
//and
return false;
But still it keeps redirecting/refreshing to the same page. I don't even have redirecting headers in php file I'm calling.
This is my HTML
<div class="col-md-3 col-sm-6 col-6 ad-image">
<label for="file1">
<img id="blah1" src="http://placehold.it/500" alt="..." class="img-thumbnail">
<input type="button" value="Remove Photo" style="margin-top: 5px;" class="btn btn-danger btn-sm" id="image-remove-btn-1">
<small id="textCount" class="form-text text-center bold">Thumbnail</small>
</label>
</div>
Here's my javascript
$("#image-remove-btn-1").click(function (e) {
e.preventDefault(); //doesn't work still page keeps refreshing
$('#blah1').attr('src', 'http://placehold.it/500');
var userId =<?php echo $userId ?>;
var adId =<?php echo $adId ?>;
deletePhoto('blah1', userId, adId); //this is the function with ajax
$(this).hide();
return false; //doesn't work still page keeps refreshing
});
Here's the deletePhoto() function:
function deletePhoto(imgeName, userid, adId) {
$(document).ready(function () {
$.ajax({
url: 'includes/remove-ad-image-inc.php',
dataType: 'text', // what to expect back from the PHP script, if anything
data: {
userId: userid,
adId: adId,
imgeName: imgeName
},
type: 'post',
success: function (php_script_response) {
alert(php_script_response); // display response from the PHP script, if any
}
});
});
}
This is my php remove-ad-image-inc.php I am calling through above ajax
<?php
include_once './dbConnection.php';
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$userId = mysqli_real_escape_string($conn, filter_input(INPUT_POST, "userId"));
$adId = mysqli_real_escape_string($conn, filter_input(INPUT_POST, "adId"));
$imgeName = mysqli_real_escape_string($conn, filter_input(INPUT_POST, "imgeName"));
if (isset($userId) && isset($adId) && isset($imgeName)) {
$sql = "SELECT * FROM adimage WHERE adimageno=? AND adid=? AND userid=?;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "error!";
} else {
mysqli_stmt_bind_param($stmt, "sii", $imgeName, $adId, $userId);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_assoc($result)) {
$ImageId = $row['adimageid'];
}
$fileName = "../uploads/ad/adImage-" . $ImageId . "-" . $adId . "-" . $userId . "*";
$fileInfo = glob($fileName);
$fileExt = explode(".", $fileInfo[0]);
$fileActualExt = $fileExt[1];
$file = "../uploads/ad/adImage-" . $ImageId . "-" . $adId . "-" . $userId . "." . $fileActualExt;
array_map('unlink', glob($fileName));
$sql = "UPDATE adimage SET adimagestatus=1 WHERE adimageid='$ImageId';";
mysqli_query($conn, $sql);
exit();
}
}
Can someone please help me with a solution?
I have created that toggles a material icon to on/off.
When the icon is off I need to run a delete query.
When the icon is on I need to run a insert query.
I know I need to use AJAX and am still new to it.
What I am having trouble understanding is whether I refernece the current PHP file or some other php file. Iknow I have to write my query and execute it in a PHP file, but not sure to do that. I do not want to reload the pagebecuase I lose other information by doing so.
I basically owuld like to update the icon and execute the required SQL stmnt.
Any help is appreciated.
What I have so far:
JAVASCRIPT:
//update the favorites icon
function updateFavorites(id){
if($(this).find('#staricon'+id)){
if($('#staricon'+id).hasClass('star-color')) {
$('#staricon'+id).removeClass('star-color');
//update the table
deleteFavorites();
}
else {
$('#staricon'+id).addClass('star-color');
addFavorites();
}
}
}
//delete the item from the table
function deleteFavorite(){
$.ajax({
type: "POST",
url: "somePHPFile.php",
cache: false,
data:{id:'#staricon'+id},
}).done(function( msg ) { console.log(msg);
});
}
PHP:
//check to see if this is a favorite
$query = "SELECT * FROM favorites WHERE story_id = " . $story_id;
$result = mysqli_query($conn, $query);
$is_fav = mysqli_num_rows($result);
if ($is_fav > 0) {
echo '<a class=" stats pull-right " href="javacript:void" ><span id="staricon' . $story_id .'" class="star-color" onclick="updateFavorites(' . $story_id . ')"><i class=" material-icons " title="Favorite" >star</i></span></a>';
}
else {
echo '<a class=" stats pull-right " href="javacript:void" ><span id="staricon' . $story_id .'" onclick="updateFavorites(' . $story_id . ')"><i class=" material-icons " title="Favorite" >star</i></span></a>';
}
I have update my code to reflect the following:
JAVASCRIPT:
function updateFavorites(id){
if($(this).find('#staricon'+id)){
if($('#staricon'+id).hasClass('star-color')) {
$('#staricon'+id).removeClass('star-color');
$.ajax({
type: "POST",
url: "showStoryCards.php",
data: {
id: $(this).data(id),
enabled: !$(this).hasClass('star-color') //delete
},
})
}
else {
$('#staricon'+id).addClass('star-color');
$.ajax({
type: "POST",
url: "showStoryCards.php",
data: {
id: $(this).data("id"),
enabled: $(this).hasClass('star-color') //insert
},
})
}
}
PHP:
echo $story_title ;
$query = "SELECT count(*) FROM favorites WHERE story_id = ?";
$sql= $conn->prepare($query);
$sql->bind_param("s", $story_id);
$sql->execute();
$result = $sql->get_result();
$is_fav = mysqli_num_rows($result);
if ($is_fav == 0) {
echo '<a class=" stats pull-right " href="javacript:void" ><span
id="staricon' . $story_id .'" class="star-color"
onclick="updateFavorites(' . $story_id . ')"><i class=" material-icons "
title="Favorite" >star</i></span></a>';
}
else {
echo '<a class=" stats pull-right " href="javacript:void" ><span
id="staricon' . $story_id .'" onclick="updateFavorites(' . $story_id .
')"><i class=" material-icons " title="Favorite" >star</i></span></a>';
}
if (isset($_POST['enabled'])){
if($_POST['enabled']) { // INSERT query
$sql = "INSERT INTO favorites VALUES( " . $id . ", '1') ";
$sql->execute();
} else {// Delete query
}
}
My icons update to the appropriate on /off colors but I still cannot get the query to fire. It does not even appear that the call back to the PHP page is functioning as I cannot retrieve the $_POST.
Use prepared statements because you're opening yourself to injection attacks.
Try this query
$query = "SELECT * FROM favourites WHERE story_id = ?";
$sql= $conn->prepare($query);
$sql->bind_param("s", $story_id);
$sql->execute();
$result = $sql->getResult();
print_r($result);
Simplify it all.
$(document).ready(function() {
$('#staricon').on('click', function() {
// Prevent multiple clicks before the first one finishes.
// There is probably a more elegant way to do this.
if(active){
return;
}
active = false;
//console.log($(this).hasClass('star-color'));
//console.log($(this).data("id"));
$.ajax({
type: "POST",
url: "somePHPFile.php",
data: {
id: $(this).data("id"),
enabled: !$(this).hasClass('star-color')
},
}).done(function(msg) {
active = true;
$(this).toggleClass('star-color');
console.log(msg);
});
});
});
/*
PHP
// Use ID and enabled to add or delete from db.
if($_POST['enabled']) {
// INSERT query
} else {
// Delete query
}
*/
div.star-color {
background-color: #FF00FF;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="staricon" data-id="1" class="star-color">Test</div>
Hello to every one and thank you for your time.
My problem is that i can not display the json_encode from my php database but in my chrome the data is appear.
The $.each is not dispaly all only one
enter image description here
now the code for the php :
comment.php
$data = $_REQUEST;
$photo_id =38;//$data['photo_id_comment'];
$con = mysqli_connect('localhost','root','','gallery');
$sql = "SELECT * FROM comments";
$sql .= " WHERE photo_id = " . $database->escape_string($photo_id);
$sql .= " ORDER BY photo_id ASC";
$result = mysqli_query( $con,$sql);
$arr = array();
$row_count = mysqli_num_rows($result);
while ($row = mysqli_fetch_array($result)) {
array_push($arr , $row);
}
mysqli_close($con);
echo json_encode($arr);
And the ajax to retrieve data is: script.js
function refreshComment() {
requestData = $("#photo_id_comment").serialize();
$.ajax({
url: "http://localhost/udemy/app_php/includes/comment.php",
type: "get",
data: requestData,
dataType: "text",
success : function (data) {
jQuery.each(data, function(index, item) {
//now you can access properties using dot notation
$('#chat_box').val( $('#chat_box').val() + item.body + '\n');
/* $('#author_comment').html(item.author);
$('#chat_box').html(item.body);*/
});
},
error: function (http, status, error) {
alert('Some error occurred :'+error);
}
});
return false;
}
setInterval( refreshComment , 5000 );
And the html where the data is not display is: photo.php.
<div class="media">
<a class="pull-left" href="#">
<img class="media-object" src="http://placehold.it/64x64" alt="">
</a>
<div class="media-body">
<h4 id="author_comment" class="media-heading"></h4>
<p id="chat_box"></p>
<p class="text-info">This is post at: </p>
</div>
</div>
Please try this one,
$sql = "SELECT * FROM comments WHERE photo_id = " . $database->escape_string($photo_id) ORDER BY photo_id ASC";
$result = mysqli_query( $con,$sql);
$arr = array();
while ($row = mysqli_fetch_array($result)){
$arr[] = $row;
}
echo json_encode($arr);
and change ,
dataType:'json' instead of dataType:'text'
in script.
change dataType:text to dataType:JSON
EDIT
use this instead of $.each
for(var i = 0;i < data.length ; i++)
{
/*access data as data[i].orfeas*/
}
PHP
$array = array();
$i = 0;`
foreach($res as $r){
$array[$i] = $r;
$i++;
}
header('Content-Type:Application/json');
echo json_encode($array);
EDIT2
USE Header to help jQuery to identify the response type and then jQuery will parse the JSON and you can access it by using a loop above mentioned
in your script.js file make change on success function of ajax:-
success : function (data) {
$.each($.parseJSON(data), function(key,item){
$('#chat_box').val( $('#chat_box').val() + item.body + '\n');
});
}
What is wrong here?
My PHP/HTML (The only part that matters):
if(isset($_POST['submit']))
{
$date = date('Y-m-d', strtotime(str_replace("-","/",$_POST['dateOfEntry'])));
$username = $_POST['user'];
$query = 'SELECT `ID`, `Date`, `Description`, `TypeOfDowntime`, `Machine#` FROM `machineissuesreport` WHERE `Date`="'.$date.'" AND `UpdatedBy` = "'.$username.'" ORDER BY `ID` DESC';
$conn = mysqli_query($connection, $query);
while($row = mysqli_fetch_array($conn))
{
echo '<tr>';
echo '<td style="text-align: center" width="5px"><input type="button" name="edit" value="Edit"></td>';
echo '<td style="text-align: center" width="5px">Delete</td>';
echo '<td style="display: none;"><input type="hidden" value='.$row['ID'].'></td>';
echo '<td>'.$row['Date'].'</td>';
echo '<td>'.$row['Description'].'</td>';
echo '<td>'.$row['TypeOfDowntime'].'</td>';
echo '<td>'.$row['Machine#'].'</td>';
echo '</tr>';
}
}
?>
My Ajax/Javascript:
$(document).ready(function()
{
$('.delete').click(function()
{
if(confirm("Are you sure you want to delete this row?"))
{
var del_id = $(this).attr('id');
var $ele = $(this).parent().parent();
$.ajax({
type: 'POST',
url: 'machineEntryLogEdit.php',
data: {'del_id':'del_id'},
success: function(data)
{
$ele.fadeOut().remove();
},
error: function (xhr, status, error)
{
alert(this);
}
});
}
});
});
My PHP (on an external script: machineEntryLogEdit.php):
include('connServer.php');
$deleteID = $_POST['del_id'];
$query = 'DELETE FROM `machineissuesreport` WHERE `ID` ="'.$deleteID.'"';
$result = mysqli_connect($connection, $query);
if(isset($result))
{
echo "YES";
}
else
{
echo "NO";
}
?>
I have searched around and around for solutions but no avail. The only things it does is delete the record from the HTML table, but not from the database, causing the supposed-to-be-deleted row to reappear after refresh. I am still very new to AJAX (in fact I just learned it myself today) and still reading the documentations and forums. Thanks.
This should be data: {'del_id': del_id} remove quotes so it react as a variable, not just a single string. And one more thing, your delete query does not execute cause you're using :
$result = mysqli_connect($connection, $query);
Should be mysqli_query like the one you did on selecting data's part:
$query = 'DELETE FROM `machineissuesreport` WHERE `ID` ="'.$deleteID.'"';
$result = mysqli_query($connection, $query);
It looks to me like you didn't pass the submit variable in your data. If you want to include a form you need to pass the data, right now the server is receiving only one parameter, del_id
I have a problem with my like system an user can give more than 1 like but the system register on the db just one, i think is a problem related to AJAX.
This is the button:
<a class="btn btn-xs btn-white" name="btn" onclick="usercountcomments(<?php echo $value['user_id'].",".$value['personal_closest_id'].",".$value['id']; ?>)"><i class="fa fa-star"></i><span id="countVal1_<?php echo $value['id']; ?>"><?php echo $value['countcomments']; ?></span> Cool </a>
And this one is the jscript AJAX script:
function usercountcomments(user_id,postId,id){
var a = $("#countVal1_"+id).text();
var display = document.getElementById("countVal1_"+id);
var count = a;
var user_comments="cool";
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>social/commentcool/" +user_id+"/"+postId+"/"+user_comments,
data:{ user_comments : user_comments},
success: function(data) {
count++;
display.innerHTML = count;
// alert(a++);
}
});
}
What can I do to prevent the user giving more than one like ?
you can use cookie
<?php
$id =$_GET['id'];
if(isset($_COOKIE['like'.$id])) {
echo "error";
exit;
}else {
$sql = "UPDATE post SET likecount=likecount+1 WHERE id=$id";
$conn->query($sql);
$sql = "SELECT likecount from post where id=$id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
echo $row['likecount'];
setcookie('like'.$id,true, time() + (86400 * 30), "/");
}
}