Ajax not redirecting me to next page - php

I am trying to pass the ID of the clicked image to next page. When I developed my code, it didn't redirect me to the next page. When I click F12 and check the POST in network, it shows that the variable is passed correctly to the next page as shown in the attached image but it didn't redirect me to the next page. So now I know that the variable is passed and received correctly in the next page but I need what needed in my code to direct me to the next page,
Note: when I tried to put window.location.href = 'userevent.php'; it redirect me but without the variable and gives me error (Notice: Undefined index: clicked in)
Also when I use url: '#userevent.php.Action("delivery", "service")',, it gives me network status 403
this is my code:
<?php
session_start();
require "init.php";
login();
?>
<html>
<!--...-->
<head>
<meta charset="utf-8">
<title> Ghost </title>
<!-- <link rel="Stylesheet" href="css/style1.css">-->
<link rel="stylesheet" href="css/style2.css" media="screen" type="text/css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script >
function myFunction(clicked) {
document.getElementById('test').innerHTML = clicked;
$.ajax({
type: "POST",
//url: '#userevent.php.Action("delivery", "service")',
url: 'userevent.php',
dataType:'json',
data: {"clicked": clicked},
success: function(data){
}
});
window.location.href = 'userevent.php';
}
</script>
</head>
<body>
<div class="sidenav">
Main Page
About Us
</div>
<div class="login-box">
<h1>Add Event</h1>
<div>
<p id="test"> </p>
<?php
// LOGIN USER
function login(){
global $con;
global $counter;
echo "<table align='center' >";
//$email = $mysqli->escape_string('');
$query="SELECT * FROM events ORDER BY ID ASC";
$result=mysqli_query($con,$query);
if ( $result->num_rows == 0 ) // User doesn't exist
echo "User with that ID doesn't exist!";
else { // User exists
$counter = 0;
$emptyArray = [];
while($row = $result->fetch_assoc())
{
$emptyArray[$counter]= $row["ID"];
if($counter == 0)
{
echo '<tr>';
}
echo '<td><img id=' . $row["ID"]. ' onClick="myFunction(this.id)" src="images/' . $row["photo"]. '" width="250px" height= "250px" alt="Avatar" >
<h1 id = "GFG_DOWN" style =
"color:white;text-align:center; font-size: 20px; font-weight: bold;"> '.$emptyArray[$counter].'
</h1> </td>';
$counter++;
if($counter == 3)
{
echo "</tr>";
$counter = 0;
}
}
}
}
mysqli_close($con);
?>
and this is the code in the second page:
<div class='textbox'>
<label> ID: ".$_POST['clicked']."</label>
</div>

The entire point of Ajax is that that request is made with JavaScript and the response is handled by JavaScript without navigating to a new page.
If you want to make a POST request and navigate to the resulting page, then use a <form>
window.location.href = 'userevent.php';
it redirect me but without the variable
Assigning a URL to location.href triggers browser navigation (with a GET request) to that URL.
It is a completely different request to the Ajax request so it doesn't have the data from that request.
Again: Use a form for this.
I read the data from database and I get the clicked id of the images.
Put the data you want to send in a submit button instead.
<form method="POST" action="userevent.php">
<?php while($row = $result->fetch_assoc()) ?>
<button name="clicked" value="<?php echo htmlspecialchars($row["ID"]); ?>">
<img src="images/<?php echo htmlspecialchars($row["photo"]); ?> alt="Put useful and unique alt text so people know what they are selecting if they can't see the image">
</button>
<?php } ?>
</form>

I think you are better off making a small form, since you want to send the user to a new page when clicking.
<?php while($row = $result->fetch_assoc()) ?>
<form action="userevent.php" method="POST">
<input type="hidden" name="clicked" value="$row["ID"]">
<img src="images/{{ $row['photo'] }}" class="img">
</form>
<?php } ?>
$('.img').click(function() {
this.form.submit();
});
*Edited to reflect your current edits.

Related

How to make ajax load more content, using button pagination work

I intend to load more videos into a div/page using load more button pagination with ajax, xhr status shows status as ok(200) but no video content is loaded.
videos.php:
<div id="videosline " class="col-md-3 content-grid ">
<?php //code to get first 3 videos working ?>
</div>
<button id="loadvideos" class="btn ">Load More</button>
//ajax jquery code to load in more three videos at every button click
$(document).ready(function(){
var videoscount = 3;
$("#loadvideos").click(function(){
videoscount = videoscount + 3;
$.ajax({
type:"GET",
url:"loadmore.php",
data:{
'videosnewcount':videoscount
},
sucess: function(data){
$('videosline').append(data);
}
});
loadmore.php:
<?php
include 'master.php';//some php config and db config
$videosnewcount = 3;
$condition = [];
array_push($condition,['mediatype = ' => ['video/mp4','AND']]);
$data = find('files',$condition,["ORDER BY " => "id DESC","LIMIT" => $videosnewcount ]); //php function for mysql query
foreach($data as $video) { ?>
<?php if($video['mediatype'] == 'video/mp4') { ?>
<?php include('cards/video.php'); ?>
}
}
?>
cards/video.php:
<?php if(explode('/',$video['mediatype'])[0] == 'video') { ?>
<a href="mediafile.php?id=<?= $video['id']?>&medianame=<?= $video['filename']?>"><div style=" height:;">
<video controlslist="nodownload" oncontextmenu="return false;" poster="member/<?= $video['poster'] ?>" style="height:250px; width:100%; " type="video/mp4" class="pr100" src="member/<?= $video['path'] ?>" > </video</div></a><?php } ?>
I don't know if it matters but in loadmore.php, you are not getting the GET parameter from the Ajax call so I don't know why you are sending it.
What do matters, is that loadmore.php is not echoing any data so your Ajax response should be empty. Also, I can't see that your sending any query to your database. Where is the "SELECT from table WHERE..."?

PHP create table then allow user to click button getting information from table

I have created a HTML page and it uses PHP to take data from a database and store it into the table created. How can I get it so when the user clicks a button it will preform a certain task according to the row in the table using php?
I am wanting to take information from a database and create new rows in a HTML table. In those rows will be data from the database, there's also a button on each row. When the user clicks that button I want it to call a function using the specified 'name' which is represented by the variable $nam.
<?php
ob_start();
session_start();
require_once 'dbconnect.php';
if( !isset($_SESSION['user']) ) {
header("Location: index.php");
exit;
}
$deny = array("222.222.222", "333.333.333");
if (in_array ($_SERVER['REMOTE_ADDR'], $deny)) {
header("location: http://www.google.com/");
exit();
}
$res=mysqli_query($con,"SELECT * FROM users WHERE userId=".$_SESSION['user']);
$userRow=mysqli_fetch_array($res);
?>
<!DOCTYPE html>
<html>
<?php header("Access-Control-Allow-Origin: http://www.py69.esy.es"); ?>
<head>
<title>ServiceCoin</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css" />
<link rel="stylesheet" href="scripts/home/index.css" />
</head>
<body>
<center>
<h3>Welcome, <?php echo $userRow['userName']; ?>. You Currently Have <span id="services"><?php echo $userRow['userServices']; ?></span> Services</h3>
<p id="error"></p>
<button onclick="send_coins()" class="button">Send Coins</button>
<button onclick="create_service()" class="button">Create A Service</button>
<button onclick="send_coins()" class="button">My Services</button>
<h3>View Services</h3>
<span><?php
$users = 1;
$num = 1;
echo "<center><table width=1000><th>Buy</th><th>Service Name</th><th>Service Cost</th><th>Service Description</th><th>Service Provider Name</th>";
while($users < 100 && $num < 100){
$res=mysqli_query($con,"SELECT * FROM users WHERE userId=".$users);
$userRow=mysqli_fetch_array($res);
$id = 0;
while($id != 10){
$id = $id + 1;
if($userRow['userService'.$id] === 'null'){
}else if(!empty($userRow['userService'.$id])){
echo "<tr><td name=$num ><input type=submit value=buy ></td><td class=services width=250 align=center>".$userRow['userService'.$id]."</td><td class=services width=250 align=center>".$userRow['userServiceCost'.$id]."</td><td class=services class=services width=500 align=center>".$userRow['userServiceDes'.$id]."<td class=services width=500 align=center>".$userRow['userServiceName'.$id]."</tr>";
//echo $id."Error: ".$con->error;
$num = $num + 1;
$id = $id + 1;
}
}
$users = $users + 1;
}
echo "All Services Loaded";
echo "</table></center>";
?></span>
<span class="text-danger"><?php echo $msg; ?></span>
</center>
</body>
<script lang="text/javascript" src="scripts/home/index.js"></script>
</html>
<?php ob_end_flush(); ?>
Firstly, you cannot call PHP functions on a user action without using something called Ajax. This is because once the HTML code is supplied to the user's web browser it is client side and clicking buttons won't allow you to request info from the server (unless it's new pages) unless you call the php file containing the function code through Javascript (using Ajax).
For example, create a "functions.js" file and insert the following code:
function FuncName(NameOfRow){
$.post('phpfunctionfile.php', {NameOfRow: NameOfRow}, function(data) {
if(data==1){
//Some sort of code, maybe display a modal with some sort of control panel to do something.
}
}
}
Then in the php file code your function and echo back whatever you want as the variable "data" (echo $data;). Of course you can redirect to new pages etc in this file (I have never tried it before though it should work).
Now in the originaly code assuming you are calling each function depending on userServiceName'.$id if that's unique key in your table you want to call your Javascript function using this value as the parameter. I haven't tested the following code and I'm not sure if it's actually what you want, but you should get the idea from the following code and then be able to adapt it for what you are creating.
echo "<tr><td name=$num onClick="FuncName('".$userRow['userServiceName'.$id]."' ><input type=submit value=buy ></td><td class=services width=250 align=center>".$userRow['userService'.$id]."</td><td class=services width=250 align=center>".$userRow['userServiceCost'.$id]."</td><td class=services class=services width=500 align=center>".$userRow['userServiceDes'.$id]."<td class=services width=500 align=center>".$userRow['userServiceName'.$id]."</tr>";
If this isn't a clear enough explanation please say so. I'll happily provide you some of my code that will better show how I've done it before.

How to get the id to set a session variable in php

This first part isn't having any issues now.
<?php
session_start();
while($row = $result->fetch_assoc()){
echo "<div id='name' style='margin-top:50px;'><h2>" . $row['name'] . "</h2>";
echo "<a href='nextPage.php'><img class='pic' src='".$row['imageURL']."' data-id='".$row['id']."' height='100px'/></a></div>";
echo "<div id='bio' style='border-bottom:1px solid #000;'><p>" . $row['bio'] . "</p></div>";
}
?>
<script type="text/javascript">
$(document).on('click', '.pic', function(){
var id = $(this).data('id');
$.ajax({
type: 'POST',
url: 'setSession.php',
data: {myId: id}
});
});
</script>
After I click an image I just get php error messages telling me there is an undefined variable. I currently have 'setSession.php' as a separate page, not sure if it's supposed to be or not.
**Next Page**
<?php
session_start();
include("connect.php");
$result = mysqli_query($con, "select * from table");
mysqli_close($con);
?>
<!doctype html>
<html>
<head>
<title></title>
</head>
<body>
<div class="wrapper">
<img src="<?php echo $row['imageURL'];?>" height="200px"/><br/>
<div class="textSection" style="text-align:center;">
<h2><?php echo $row['name'];?></h2>
<p>
<?php echo $row['bio'];?>
</p>
</div>
</div>
</body>
</html>
firstly, you should start session in that page like this.
session_start();
then access the session variable like this.
$_SESSION['your_key_here'];// this will return the value stored in session.
Put data attribute data-id on img tag and change ids into class since ids should be unique like so :
<img class='pic' src='" . $row['imageURL'] . "' data-id='" . $row['id'] . "' height='100px'/></a></div>";
And register click handler to img using its class together with AJAX request to set data id into session variable like so :
$(document).on('click', '.pic', function() {
var id = $(this).data('id'); // get id value from data-id attribute
$.ajax({
type : 'POST',
url : 'setSession.php',
data : {
myId : id
},
success : function(msg) { /* do something here for success request */ }
});
});
Finally. in setSession.php page :
<?php
session_start();
$_SESSION['id'] = $_POST['myId']; // this come from ajax request
echo "something"; // and this will available on ajax success callback
?>

Create Input-box with validation in JavaScript popup box

I'm confuse in this topic what should I do and How.?
I would like to have popup box which ask for the password before delete the user from the list. If Password(as some value eg. ex12345) is correct then delete the user If no then say Password is incorrect.
I have my PHP page with simple popup. I would like to have popup with the inputbox
Any help will be appreciate.
here is my code. as view.php
<html>
<head>
<meta charset="utf-8">
<title>LogIn Information System</title>
<link rel="stylesheet" media="screen" href="stylesS.css" >
<script>
function confirmDelete(delUrl)
{
if (confirm("Are you sure you want to delete"))
{
document.location = delUrl;
}
}
</script>
</head>
<body>
<div class="header-top">
<a href="//home" class="utopia-logo">
<img src="//images/logo.png" alt="asd" />
</a>
</div><!-- End header -->
<table class = "button_table">
<tr>
<td><button class="submit" type="submit">Home</button></td>
<td><button class="submit" type="submit">Search</button></td>
<td><button class="submit" type="submit">Customer List</button></td>
<?php
if($_SESSION['valid']=='admin'){
echo "<td><button class='submit' type='submit'><a href='add.php'>Add User</a></button></td>";
echo "<td><button class='submit' type='submit'><a href='users.php'>View User</a></button></td>";
}
?>
<td><button class="submit" type="submit">Logout</button></td>
</tr>
</table>
<form class="contact_form" action="search.php" method="post" name="contact_form">
<ul>
<li>
<h2>Search Results</h2>
<span class="required_notification">Following search matches our database</span>
</li>
</li>
<?php
echo "<table border='0' width='100%'>";
echo "<tr class='head'>";
echo "<th>Name</th>";
echo "<th>Last Name</th>";
echo "<th>Phone</th>";
echo "<th>Action</th>";
echo "</tr>";
while($row = mysql_fetch_array($find)){
echo "<tr class='t1'>";
echo "<td>".$row['fname']."</td>";
echo "<td>".$row['lname']."</td>";
echo "<td>".$row['phone']."</td>";
?>
<td>
<a href="edit.php?id=<?php echo $row['id'];?>" class='action'>Edit</a> |
Serve
</td>
<?php
echo "</tr>";
}
echo "</table>";
?>
</li>
</ul>
</form>
</body>
</html>
Delete.php
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
// get id value
$id = $_GET['id'];;
}
$rec = "delete from data where id='$id'";
if(mysql_query($rec)){
echo "<center></h1>Selected Customer serve by DC</h1></center>"."<br />";
echo "<center></h6>Please wait while you are redirected Home in 3 seconds..</h6> </center>"."<br />";
header('Refresh: 3; url=home.php');
}
else{
die("Data failed to delete in the database");
}
?>
Okay here is an example of what I think you are asking for:
I separated the js in the header so you could better understand. first one does the pop up box and second script does the ajax call. Remember this is a very basic example
Test.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
//select all the a tag with name equal to modal
$('a[name=modal]').click(function(e) {
//Cancel the link behavior
e.preventDefault();
//Get the A tag
var id = $(this).attr('href');
//Get the screen height and width
var maskHeight = $(document).height();
var maskWidth = $(window).width();
//Set heigth and width to mask to fill up the whole screen
$('#mask').css({'width':maskWidth,'height':maskHeight});
//transition effect
$('#mask').fadeIn(1000);
$('#mask').fadeTo("slow",0.9);
//Get the window height and width
var winH = $(window).height();
var winW = $(window).width();
//Set the popup window to center
$(id).css('top', winH/3-$(id).height()/3);
$(id).css('left', winW/2-$(id).width()/2);
//transition effect
$(id).fadeIn(2000);
});
//if close button is clicked
$('.window .close').click(function (e) {
//Cancel the link behavior
e.preventDefault();
$('#mask').hide();
$('.window').hide();
});
//if mask is clicked
$('#mask').click(function () {
$(this).hide();
$('.window').hide();
});
$(window).resize(function () {
var box = $('#boxes .window');
//Get the screen height and width
var maskHeight = $(document).height();
var maskWidth = $(window).width();
//Set height and width to mask to fill up the whole screen
$('#mask').css({'width':maskWidth,'height':maskHeight});
//Get the window height and width
var winH = $(window).height();
var winW = $(window).width();
//Set the popup window to center
box.css('top', winH/2 - box.height()/2);
box.css('left', winW/2 - box.width()/2);
});
});
</script>
<script type="text/javascript">
function ConfirmDelete()
{
var confirm = document.getElementById('confirm').value;
var dataString = 'password='+ confirm;
if(confirm.length>0)
{
$.ajax({
type: "GET",
url: "delete.php",
data: dataString,
success: function(server_response)
{
document.getElementById("results").style.display = "block";
$('#results').html(server_response).show();
$('#mask').hide();
$('.window').hide();
}
});
}
return false;
}
</script>
<style type="text/css">
#mask{position:absolute;left:0;top:0;z-index:9000;background-color:#222;display:none}
.window{position:fixed;left:0;top:0;width:450px;height:200px;display:none;z-index:9999;padding:20px}
#dialog1{padding:10px 10px 8px 25px;border:2px solid #a1a1a1;width:450px;height:200px; background-image:url('imgs/bg.jpg');
</style>
</head>
<body>
Delete this Entry
<!-- Start of MODAL BOX -->
<div id="dialog1" class="window" align="center">
<font color="#FFFFFF">If you are sure you wish to delete this please enter your admin password</font><br>
<font color="#FFFFFF"><b>test password ( Admin )</b></font>
<input type="password" id="confirm"/><br><br>
<input type="submit" name="confirm_delete" onclick="ConfirmDelete()" value="Confirm Delete">
</div><!-- End of MODAL BOX -->
<div id="mask"></div><!-- Mask to cover the whole screen -->
<div id="results" class="results" style="display:none;"> </div>
</body>
</html>
the call page this is where you will have your php
delete.php
<?PHP
if($_GET['password'] === "Admin")
{
//sucess do your delete here
echo " this was the correct password ";
}
else
{
//failure
echo " Password incorrect!! ";
}
?>
do JS check on client side and use CRSF on server side - http://en.wikipedia.org/wiki/Cross-site_request_forgery
Here is a good example: CSRF (Cross-site request forgery) attack example and prevention in PHP

jQuery page refresh not reading or executing php

sorry if the title is a little.. vague i couldnt pin it down.
So i am developing a friend request system which works i guess similar in concept to facebook. So you get a request and it lists them without a page reload.
However i get the div 'refreshing' or so i think i cant test the php which is where i have a problem, i will post the relevent code and files below.
It may look a little long winded but it shouldnt be too bad in reality. My php code should keep executing the query which is looking at the database in the updateFriendBox.php however it doesnt seem to be doing this. My code may be messy as well so I apologise.
myaccount.php
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript" type="text/javascript">
function refreshDiv()
{
$.get('updateFriendBox.php', function(data){$('#refresh').html(data);});
}
$(function()
{
refreshDiv();
setInterval(refreshDiv, 5000);
});
function box(x){
if($('#'+x).is(":hidden")){
$('#'+x).slideDown(200);
} else {
$('#'+x).hide();
}
}
</script>
<?php
$addBox = '<div style="display:inline; padding:5px;">
Show/Hide Friend Requests
</div>';
// a bit further down in the code where its all called:
<? echo $addBox; ?></span>
<div class="friendSlide" id="fRequ" style="height:240px; overflow:auto;">Your friend requests: <br />
<div id="refresh"> <?php // this is where the refresh call is ?>
</div>
</center>
</div>
</div>
</div>
updateFriendBox.php:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript" type="text/javascript">
function acceptFriendRequest(x) {
var url = "friendParse.php";
$.post(url,{ request: "acceptFriend", reqID: x}, function(data){
$("#req"+x).html(data).show().fadeOut(5000);
});
}
function denyFriendRequest(x) {
var url = "friendParse.php";
$.post(url,{ request: "denyFriend", reqID: x}, function(data){
$("#req"+x).html(data).show().fadeOut(5000);
});
}
</script>
</head>
<body>
<?php
include 'dbc.php';
$sql = "SELECT * FROM friendRecu WHERE mem2='" . $_SESSION['user_id'] . "' ORDER BY id ASC LIMIT 10";
$query = mysql_query($sql)or die(mysql_error());
$num_rows = mysql_num_rows($query);
if($num_rows < 1) {
echo "No friend requests";
} else {
while($row = mysql_fetch_array($query)){
$requestID = $row['id'];
$req = $row['mem1'];
$sqlName = mysql_query("SELECT full_name FROM users WHERE id='$req'");
while($row = mysql_fetch_array($sqlName)){
$requesterName = $row['full_name'];
}
echo '<hr /><table width="100%", cellpadding="5"><tr><td width="17%" align="left"><div style="overflow:hidden; height:50px; color:white;"></div></td> <td width="83%">' . $requesterName . ' added you as a friend
<span id="req' . $requestID . '">
Accept
||
Deny
</span></td></tr>
</table>';
}
}
?>
I think you are having a problem because your updateFriendBox.php is returning too much. Remove all that inline JS code, place it in an include file, and include it from myaccount.php. You also shouldn't have <head> and <body> sections in your updateFriendBox.php file.
The ajax call here doesn't create a whole new page, you're getting additional HTML to add to the original page.
So the only thing you should have there is your SQL query, the loop, and your HTML output for each data row.

Categories