How to get new session value after some time using PHP - php

I need to get the new session value after some second using PHP. My code is below.
<button class="btn nextbtnbgdiv open2" type="button">Next <span class="fa fa-arrow-right"></span></button>
<div class="fyndspacecategory fyndsheightsubc nano">
<div class="nano-content">
<?php
$cat_id= $_SESSION['cid'];
?>
</div>
</div>
Here when user is clicking on next button the div section is opening and the the value is fetching from session. Here i need after some second always the updated $_SESSION['cid'] will fetch at each time click on next button.

In order to fetch the updated $_SESSION['cid'] you will need to make a call to the server to return this value, you can do so by embedding the value into an element i.e.
Back-end (i.e. get_session.php):
<html>
<body>
<div id="session"><?= $_SESSION['cid'] ?></div>
</body>
</html>
Front-end:
<button class="btn nextbtnbgdiv open2" type="button">Next <span class="fa fa-arrow-right"></span></button>
<div class="fyndspacecategory fyndsheightsubc nano">
<div class="nano-content"><?php $cat_id= $_SESSION['cid']; ?></div>
</div>
<script>
jQuery(function($) {
$(document).on( 'click', '.nextbtnbgdiv', function() {
$('.fyndspacecategory .nano-content').load('/get_session.php', '#session');
});
});
</script>
Or you could use a header within a page to access $_SESSION['cid'].
<?php
if ( isset( $_GET['get_session'] ) && $_GET['get_session'] ) {
header( 'X-Session: ' . $_SESSION['cid'] );
exit;
}
?>
<button class="btn nextbtnbgdiv open2" onclick="javascript:getSession();" type="button">Next <span class="fa fa-arrow-right"></span></button>
<div class="fyndspacecategory fyndsheightsubc nano">
<div class="nano-content" id="sessionId"><?php $cat_id= $_SESSION['cid']; ?></div>
</div>
<script>
function getSession() {
var request = new XMLHttpRequest();
request.onerror = function() { console.warn('An error occurred while checking session.'); };
request.open('HEAD', '?get_session=true', true);
request.onload = function() {
if ( request.getResponseHeader('X-Session') ) {
document.getElementById("sessionId").innerHTML = request.getResponseHeader('X-Session');
}
};
request.send();
}
</script>
This is not tested but should be enough to give you a start to complete your goal.

Related

Why does ajax only work on the newest post?

I'm creating a social media site with php & mysqli. On the index page all post are loaded using a while loop and on the profile page that specific users post are loaded the same way. I have the like button hooked to ajax so you can like without refresh but it only works on the latest post.
The inside the while loop I have include('post.php') and this is what is in there.
<div class="post_options" id="post_options">
<div class="op_container like<?php echo $row['id'] ?>">
<i class="fa-regular fa-heart"></i> Like
</div>
<div class="op_container">
<i class="fa-regular fa-comment"></i> Comment
</div>
<div class="op_container">
<i class="fa-solid fa-share"></i> Share
</div>
</div>
</div>
<script>
const button = document.querySelector(".post_options .like<?php echo $row['id'] ?>")
button.onclick = () => {
let xhr = new XMLHttpRequest();
xhr.open("GET", "db/like_unlike.php?userid=<?php echo $_SESSION['id'] ?>&contentid=<?php echo $row['id'] ?>", true);
xhr.onload = () => {
if(xhr.readyState === XMLHttpRequest.DONE){
if(xhr.status === 200){
button.classList.toggle("active")
}
}
}
xhr.send();
}
</script>
What i understand from your code is that your script is outside the while loop. Hence it is taking the last value from your loop as the $row variable will store latest value.
You can add data attribute to your post div and then get that value on button click
<div class="post_options" id="post_options" data-id="<?php echo $row['id'] ?>">
<div class="op_container like<?php echo $row['id'] ?>">
<i class="fa-regular fa-heart"></i> Like
</div>
<div class="op_container">
<i class="fa-regular fa-comment"></i> Comment
</div>
<div class="op_container">
<i class="fa-solid fa-share"></i> Share
</div>
</div>
<script>
const button = document.querySelector(".post_options")
button.onclick = () => {
var contentid = $(this).data('id');
let xhr = new XMLHttpRequest();
xhr.open("GET", "db/like_unlike.php?userid=<?php echo $_SESSION['id'] ?>&contentid="+contentid, true);
xhr.onload = () => {
if(xhr.readyState === XMLHttpRequest.DONE){
if(xhr.status === 200){
button.classList.toggle("active")
}
}
}
xhr.send();
}
</script>

trying to load php file with ajax

i am new to ajax i am trying to build a website for movies so i need ajax to change the servers for the video but i can not do it how much i tried the div that i want to show is not being shown at all here is my codes
HTML
<?php
$get = $data->show(" SELECT * FROM servers ");
foreach ($get as $row) {
$id=$row['server_id'];
$name=$row['server_name'];
$link=$row['link'];
$movie=$row['film_name'];
?>
<button type="button" id="btn" class="btn btn-warning"><?php echo "$name"; ?></button>
<input type="hidden" id="serverid" value="<?php echo $id ?>">
<?php } ?>
<div id="show">
</div>
AJAX
<script type="text/javascript">
$(document).ready(function (){
$('#btn').click(function (){
var serverid = $('#serverid').val()
$.ajax({
url:"../../control/operation/index/view_movie.php",
method:"POST",
data:{serverid:serverid},
success:function(data)
{
$("#show").html(data);
}
});
});
});
</script>
view_movie.php
if (isset($_POST['serverid'])) {
$id=$_POST['serverid'];
$getuser = $data->getdata(" SELECT * FROM servers WHERE server_id='$id' ");
$link=$getuser['link'];
} ?>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="<?php echo $link ?>" allowfullscreen></iframe>
</div>
</div>
nothing is shown on the div that called show

Div not showing in a jQuery Ajax Call

I have a page using bootstrap 3 framework that has a button which when pressed collects data from another page (mydata.php) with ajax and echoes it out within <div id="results"> on the page. The code works fine but as soon as I add <div class=\"col-xs-6\"> to mydata.php nothing appears on the page although I can see it within firebug.
If I change $("#results").append(html); to $("#results").text(html); the html echoes onto the page but as text without any formatting. If I remove <div class=\"col-xs-6\"> from mypage.php the data gets displayed on the page as expected. Why is the data from mydata.php not displayed when I add <div class=\"col-xs-6\">?
<div class="container">
<div class="row">
<div class="col-xs-12 col-centered">
<div class="col-xs-8 col-md-3 col-lg-3">
<button type="submit" name="btn" value="search" id="myButton" class="search_button btn btn-small btn-default btn-pull-right">Press</button>
</button>
</div>
</div>
</div>
<div class="row">
<div id="results"><!--data displayed here-->
</div>
</div><!--Row-->
</div><!--Cont-->
jQuery
$(document).ready(function(){
$(function() {
$("#myButton").click(function() {
var btn = $("#myButton").val();
var data = 'btn='+ btn;
// if location is not empty
if(data) {
// ajax call
$.ajax({
type: "POST",
url: "mydata.php",
data: data,
success: function(html){
$("#results").append(html);
}
});
}
return false;
});
});
});
mydata.php looks like this:
<?php
if (isset($_POST['btn'])) {
echo "
<div class=\"col-xs-6\">
<ul>
<li><h4>Data in this Div</h4></li>
</ul>
</div>
<div class=\"col-xs-6\">
<ul>
<li><h4>And Data in this Div</h4></li>
</ul>
</div>";
}
?>
if you do not add jQuery library then include it
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-xs-12 col-centered">
<div class="col-xs-8 col-md-3 col-lg-3">
<button type="submit" name="btn" value="search" id="myButton"
class="search_button btn btn-small btn-default btn-pull-right">Press
</button>
</button>
</div>
</div>
</div>
<div class="row">
<div id="results"><!--data displayed here-->
</div>
</div><!--Row-->
</div><!--Cont-->
<script>
$(document).ready(function () {
$(function () {
$("#myButton").click(function () {
var btn = $("#myButton").val();
var data = 'btn=' + btn;
// if location is not empty
if (data) {
// ajax call
$.ajax({
type: "POST",
url: "http://localhost/edit.php", // your file path
data: data,
success: function (html) {
$("#results").append(html); // if you want to replace results div then change $("#results").html(html);
}
});
}
return false;
});
});
});
</script>
it is working fine my side, i have tested in my local side
this is output:
Removing the ajax part works without problems... Are you sure you are receiving that exact HTML?
$('#result').append("<div class=\"col-xs-6\">"+
"<ul>"+
"<li><h4>Data in this Div</h4></li>"+
"</ul>"+
"</div>"+
""+
"<div class=\"col-xs-6\">"+
""+
"<ul>"+
"<li><h4>And Data in this Div</h4></li>"+
"</ul>"+
"</div>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result">
</div>
$('#myButton').on('click',function(){
var form = jQuery("#form");
$.ajax({
url: 'mydata.php',
type: 'POST',
data: form.serialize(),
cache: false,
dataType : 'json',
success: function(data){
if(data==true){
$("#results").append(data);
}
if(data==false){
}
},
error: function(){
}
});
return false;
});

get value from php tag by ajax

i want to get images that i fetched from database in my page and show them again in div with id test by ajax i want to show fetched datas again in div with test id when i click on button with addCart class . i think i haveto get value of button that i set it to ids of products in my datbase . and my problem is how can i get id s in ajax code?
$(document).ready(function(){
$(".addCart").click(function(){
$.post(".addCart.val()",function(data){
$("#test").html(data).show();
});
});
});
<div id="test" style="background-color: grey"></div>
<?php while ($row = mysqli_fetch_array($products)):?>
<div class="span3">
<div class="product">
<div class="product-img">
<div class="picture">
<img src="images/<?php echo $row['image'] ?>" alt="" width="540" height="374" />
<div class="img-overlay">
توضیحات بیشتر
<button value="<?php echo $row['id']?>" class="btn buy btn-danger addCart">اضافه به سبد خرید</button>
</div>
</div>
</div>
<div class="main-titles no-margin">
<h4 class="title"><?php echo $row['price'] ?></h4>
<!--<h5 class="no-margin">محصول ویژه 434</h5>-->
</div>
<p class="desc"><?php echo $row['name']?></p>
<p class="center-align stars">
<span class="icon-star stars-clr"></span>
<span class="icon-star stars-clr"></span>
<span class="icon-star"></span>
<span class="icon-star"></span>
<span class="icon-star"></span>
</p>
</div>
</div> <!-- /product -->
<?php endwhile;?>
$(".addCart").click(function(event){
var id = event.target.val();
});
This will get an value of your button element. But is this id is a valid url to make a ajax call? I dont think so. Please checkout Jquery Docs before returning to work on this part of functionality
in your code you are not passing correct value to php file
please do correction in your code
$(document).ready(function(){
$(".addCart").click(function(){
var jq = $(this);
var cart_id = jq.val(); /* get cart value */
$.post("ajax.php",{cart_id:cart_id},function(data){
$("#test").html(data).show();
});
});
});
and fetch cart_id in php ajax.php file like this
<?php
if(isset($_POST['cart_id'])){
/* put your code here */
}
?>

How to delete row with jquery, ajax and PDO

I have two tables in mysql DB, 'cars' and 'address' which they have relation with primary key and 'on delete restrict' in DB so I can't delete some address which have car and that's good. Addresss in DB have columns 'street', 'number' and 'city'. I want to delete every location which has no cars but I don't know where I'm wrong in code, it doesn't work.I checked all paths and all is ok. Any suggestion appreciate.
This is my modal delete button:
<a href="#" data-toggle="modal" data-target="#delete_loc<?php echo $value['id']?>" role="button" class="btn btn-danger btn-sm">
<i class="fa fa-trash-o"></i> Delete
</a>
<div class="modal fade" id="delete_loc<?php echo $value['id']?>" tabindex="-1" role="dialog" aria-labelledby="mydelModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content" style="text-align:center;">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h2 class="modal-title" id="mydelModalLabel" style="color:#a80b27;text-transform:uppercase;font-size:1.6rem;">Warning !</h2>
</div>
<div class="modal-body">
<h5>Are you shure you want delete address ID <b><?php echo $value['id']?></b>?</h5>
</div>
<div class="modal-footer">
<input type="hidden" name="loc_id" id="loc_id" value="<?php echo $value['id']?>">
<a href="" role="button" class="btn btn-danger" id="del_loc">
Yes, I'm shure!
</a>
<button type="button" class="btn btn-default" data-dismiss="modal">No</button>
</div>
</div>
</div>
</div>
This is jquery and ajax:
$(document).ready(function() {
$('#del_loc').bind('click',function(e){
e.preventDefault();
var id = $('#loc_id').val();
var data = 'loc_id='+id;
$.ajax({
type: "POST",
url: "include/locations/delete.php",
data: data,
success: function(result){
if(result == 1){
window.location.replace("address.php?id=");
}
else{
err_msg = JSON.parse(result);
if(err_msg.nAddress){
$('.panel-footer').append('<span class="help-block" style="float:right;"><strong>'+err_msg.nAddress+'</strong></span>');
}
}
}
});
});
});
This is delete.php:
<?php
require '../../config/init.php';
require '../functions/locations.php';
require '../services/xss.php';
$loc_id = _e($_POST['loc_id']);
$data = deleteLoc($loc_id);
if(is_array($data)){
print_r(1);
}
else{
echo $data;
}
?>
And this is function named locations.php:
function deleteLoc($loc_id){
global $conn;
try{
$stmt = $conn->prepare('DELETE FROM address WHERE id=:id');
$stmt->bindParam(':id',$loc_id);
$stmt->execute();
$row[] = 'deleted';
return $row;
}
catch(PDOException $e){
if(DEBUG === true){
header('Location:../../error/db_error.php?err_msg='.$e->getMessage());
}
else{
header('Location:../../error/db_error.php?err_msg');
}
}
}
If you are getting the value loc_id value properly.I think following code will help you a lot. Let's try..
JavaScript
<script type="text/javascript">
$(document).ready(function() {
$('#del_loc').bind('click',function(e){
e.preventDefault();
var id = $('#loc_id').val();
var data = 'loc_id='+id;
//try here alert(id); For checking whether you are getting value or not
$.ajax({
type: "POST",
url: "include/locations/delete.php",
dataType:'JSON',
data: data,
success: function(result){
var res=eval(result);
if(res.success){
window.location.replace("address.php?id=");
}
else
{
if(res.nAddress){
$('.panel-footer').append('<span class="help-block" style="float:right;"><strong>'+err_msg.nAddress+'</strong></span>');
}
}
}
});
});
});
</script>
PHP delete.php
<?php
require '../../config/init.php';
require '../functions/locations.php';
require '../services/xss.php';
$loc_id = _e($_POST['loc_id']);
$data = deleteLoc($loc_id);
if(is_array($data)){
echo json_encode(array('success'=>true));
}
else{
echo json_encode($data);
}
?>

Categories