jQuery page refresh not reading or executing php - 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.

Related

Ajax not redirecting me to next page

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.

Deleted rows removed from page but not from mysql database (PHP/jQuery)

I'm a complete beginner and have built a basic To-Do List application using PHP/jQuery. The application allows the user to add and remove tasks from a list (stored in a MySQL database).
I'm having issues with the delete function. When the delete button is clicked, it removes the task from the list but it must be remaining in the database, as it reappears once the page is refreshed.
I have no idea where I'm going wrong! Any help appreciated. See below code:
index.php :
<!DOCTYPE html>
<html>
<head>
<title>To-Do List</title>
<link rel="stylesheet" type="text/css" href="/style.css" media="all" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<div class="main">
<div class="list">
<ul>
<?php
require("db_connect.php");
$query = mysql_query("SELECT * FROM tasks ORDER BY date ASC, time ASC");
$numrows = mysql_num_rows($query);
if($numrows>0) {
while ( $row = mysql_fetch_assoc( $query ) ){
$task_id = $row['task_id'];
$task_desc = $row['task_desc'];
echo '<li><span>'.$task_desc.'</span><img id="'.$task_id.'" class="delete" width="10px" src="images/delete.png" /></li>';
}
}
?>
</ul>
</div>
<form class="new" autocomplete="off">
<input type="text" name="new-task" placeholder="Add a new task..." />
</form>
</div>
</body>
<script>
add_task();
delete_task();
function add_task() {
$('.new').submit(function() {
var new_task = $('.new input[name=new-task]').val();
if(new_task !== '') {
$.post('add_task.php', { task: new_task }, function ( data ) {
$('.new input[name=new-task]').val('');
$(data).appendTo('.list ul').hide().fadeIn();
delete_task();
});
}
return false;
});
}
function delete_task() {
$('.delete').click(function() {
var current_element = $(this);
var task_id = $(this).attr('task_id');
$.post('delete_task.php', { task_id: task_id }, function() {
current_element.parent().hide().fadeOut("fast", function() {
$(this).remove();
});
});
});
}
</script>
delete_task.php :
<?php
$task_id = strip_tags( $_POST['task_id'] );
require("db_connect.php");
mysql_query("DELETE FROM tasks WHERE task_id='$task_id'");
?>
You have an error in your delete_task function. There is no such attr as 'task_id'. Try to replace
var task_id = $(this).attr('task_id');
With
var task_id = $(this).attr('id');
Besides #IvanGajic answer is correct, also write your delete query like this:
mysql_query('DELETE FROM tasks WHERE task_id="' . $task_id . '"');

Loading a query with AJAX

function showUser(str) {
if (str=="") {
document.getElementById("content").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("content").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","paginas.php?q="+str,true);
xmlhttp.send();
}
I got this script from a website, it goes with this
<?php
$q = htmlspecialchars($_GET['q']);
$con = mysqli_connect('localhost','root',NULL,'ttrpg');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM content WHERE Pagina = '".$q."' ORDER BY ID ASC";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
echo '<div class="container">';
echo $row['Text'];
echo "</div>";
}
echo "</table>";
mysqli_close($con);
?>
I also used this:
<body onload="showUser('Home')">
I didn't change the function's name because there's no need for that
The problem I'm having is that when I load the page, there's nothing showing up inside the div.
When I press a link with for example onclick="showUser('Apple')" the text inside the div DOES change, but to the text from Home, this text doesn't ever go away, except when I reload the page
If you want to load a script on page load you can use
<script>
showUser('Home');
</script>
just before
</body> or </html> /* it will also work at the end of all html codes.*/
If you want to just print the query you executed in ajax file then you can simply use
echo $sql="SELECT * FROM content WHERE Pagina = '".$q."' ORDER BY ID ASC";
you can also see the whole ajax headers, parameters sent and response using firefox's firebug or chrome 's developer tools using inspect element then going to nework it will show ajax request and response.
Additionally you can use print_r($_REQUEST) in your ajax php file.
EDITS: I have written code to work for your needs using ajax. This will call home pages content once the page loads from fetching record from table content. If you click on about button then it will fetch content of about page from content table.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title></title>
<meta name="" content="">
<style>.msg{ color:#ff0000;}
#contentloader{ background-color:#fff; border:1px solid #333; padding:10px; }
</style>
</head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
function ajaxContentLoad(page){
q = {
'page':page,
}
$.ajax({
type:'post',
data:q,
url:'ajaxData.php',
beforeSend: function(){
$("#msg").text("sending request to server...");
},
complete:function (){
$("#msg").text("request received and loaded");
},
success:function(result, textStatus, jqXHR) {
$("#contentloader").html(result);
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
})
}
$().ready(function(e){
ajaxContentLoad('Home');
})
</script>
<body>
<div style="padding: 20px; margin:20px auto; width:80%; background: #eee">
<button id="btn1" value="Home" onclick="ajaxContentLoad('Home');">Home</button>
<button id="btn1" value="About" onclick="ajaxContentLoad('About');">About</button>
<p id="msg" class="msg"></p>
<div id="contentloader">
Content on page load
</div>
</div>
</body>
</html>
and here is ajaxData.php file
<?php
$q = htmlspecialchars($_REQUEST['page']);
$con = mysqli_connect('localhost','root',admin,'demo');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"demo");
$sql="SELECT * FROM tbl_content WHERE page = '".$q."' ORDER BY ID ASC";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
echo '<div class="container">';
echo $row['content'];
echo "</div>";
}
mysqli_close($con);

basic usage of AJAX with php for Database update and retrieval

(Just a heads up, its a Lengthy question but im sure its very basic question for a ajax-php coder)
Im trying to 'update db on some drag n drop event on one page' and 'reflect that change in other page without reload'. I have already written pretty much all the code, need your help in figuring out what is wrong. Here is the Html that I have written,
First_html_file:
<head>
<title>Coconuts into Gunnybags</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div id="coconuts" style="float:left">
<div class="coconut1" ondragover="allowDrop(event)" ondrop="drop(event)">
<img id="drag1" ondragstart="drag(event)" draggable="true" src="coconut.png">
</div>
<div class="coconut2" ondragover="allowDrop(event)" ondrop="drop(event)">
<img id="drag2" ondragstart="drag(event)" draggable="true" src="coconut.png">
</div>
</div>
<div class="gunnybag" style="float:right">
<div id="place1" ondragover="allowDrop(event)" ondrop="drop(event)"></div>
<div id="place2" ondragover="allowDrop(event)" ondrop="drop(event)"></div>
</div>
</body>
so there are 2 drag-able coconuts and there are 2 placeholders(place1 & place2). What I want to do is when the coconuts are dragged and placed on one of the placeholders, database's values should be updated. (say when a coconut is placed in 1st placeholder, place_id 1 - true, place_id 2 - false)
For this, I'm making ajax call to a php file from JS's drop function like this..
JS_file:
function drop(ev)
{
ev.preventDefault();
var data=ev.dataTransfer.getData("coconut");
ev.target.appendChild(document.getElementById(data));
var state = true;
var id = ev.target.id;
$.ajax({
url: "db_update.php", //calling db update file.
type: "POST",
data: { id: id, state: state }, //2 variables place_id and its state(True/False)
cache: false,
success: function (response) { //I dont know what to do on success. Can this be left blank like, success: ?
$('#text').html(response);
}
});
}
This is my db_update,
db_update:
<?php
$state = $_POST['state']; //getting my variables state 'n ID
$id = $_POST['id'];
function begin()
{
mysql_query("BEGIN");
}
function commit()
{
mysql_query("COMMIT");
}
$con=mysql_connect("sqlservername","myuname", "mypass") or die(mysql_error());
mysql_select_db("my_db", $con) or die(mysql_error());
$query = "UPDATE gunnybag SET state = '{$state}' where id='{$id}'"; //will this work? or am I doing something wrong here??
begin();
$result = mysql_query($query);
if($result)
{
commit();
echo "successful";
}
?>
On the receiving side I want to update the coconuts in the gunnybag without reloading the page, so I have written this ajax which uses db_fetch.php
ajx.js file:
window.onLoad = doAjax;
function doAjax(){
$.ajax({
url: "db_fetch.php",
dataType: "json",
success: function(json){
var dataArray = JSON.decode(json);
dataArray.each(function(entry){
var i=1;
if(entry.valueName==true){
$q('place'+i).css( "display","block" );
}
else{
$q('place'+i).css( "display","none" );
}
i=i++;
})
}
}).complete(function(){
setTimeout(function(){doAjax();}, 10000);
});
}
here is the db_fetch.php:
<?php
try{
$con=mysql_connect("sqlservername","myuname", "mypass") or die(mysql_error());
}
catch(Exception $e){
echo $e;
}
mysql_select_db("my_db", $con) or die(mysql_error());
$q = mysql_query("SELECT 'state' FROM 'gunnybag' "); //fetching all STATE from db
$query = mysql_query($q, $con);
$results = mysql_fetch_assoc($query);
echo json_encode($results); //making it JSON obj
?>
Finally my other page where this ajax is being called from.
Second_html_file:
<head>
<title>Coconuts into Gunnybags</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
<script type="text/javascript" src="ajx.js"></script>
//if i simply include the ajax script here will it be called
//automatically? i want this script to keep up with the changes in db.
</head>
<body>
<div class="gunnybag" style="float:right">
<div id="place1" style="display: ;"><img id="drag1" draggable="true" src="coconut.png"></div>
<div id="place2" style="display: ;"><img id="drag2" draggable="true" src="coconut.png"></div>
</div>
</body>
MAP:
First_html_file->JS_file->db_update :: Second_html_file->ajx.js->db_fetch.
Please point out what is wrong in this code, also respond to the //comments which are put along code.
Your response is much appreciated. Thanks! #help me get this right#
For ref I have hosted the files here, http://www.nagendra.0fees.net/admin.html & http://www.nagendra.0fees.net/cng.html
First thing I see is:
You say:
var id = event.target.id;
but you decalare ev in drop(ev)
so change that:
var id = event.target.id;
to:
var id = ev.target.id;
for starters.
Then you should use mysqli since mysql is deprecated:
Your code is also open for SQL-injections, so change:
$state = $_POST['state']; //getting my variables state 'n ID
$id = $_POST['id'];
to:
$state = ($_POST['state']) ? true : false;
$id = intval($_POST['id']); //make sure an integer

How to dynamically display MySQL data using jQuery and PHP?

I have a PHP page that lists a bunch of words that it grabs from a MySQL database table. It displays the words in different sizes based on a count in the table:
<?php
$selectStr = "select * from test";
if ($results = MySQL($dbName, $selectStr))
{
$rowCount = MySQL_NUMROWS($results);
}
$i = 0;
while ($i < $rowCount)
{
echo '<div style="float: left; font-size:' . (MySQL_RESULT($results,$i,'count') * 5) . 'px;">' . MySQL_RESULT($results,$i,'word') . '</div>';
$i++;
}
?>
The trick is that I want the content to display dynamically. So if a user is sitting on the page, and one of the word counts goes up, I want the word to change size without the user refreshing the page.
I am a novice with jQuery. I have used it a bit before, but only using examples. Can someone steer me in a good direction to have my page dynamically change the content without refreshing?
You can auto refresh your page body like this ... give body id='body'
<html>
<head>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#body').load('wordscount.php').fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
</script>
</head>
<body>
<div id='content'></div>
</body>
Dont forget to include jquery inside your head tag
It calls the file rowfunctie.php every 30000ms and fills the topbar diff with with the result of the getRows function.
<div id="center-rows">
<div id="links">Nu </div>
<div id="rows">
<div id="topbar"></div>
</div>
<div id="rechts"> aantal rijen</div>
</div>
<script type="text/javascript">
function doRequest() {
jQuery("#topbar").fadeOut('slow', function() {
jQuery.ajax({
type: "GET",
url: "rowfunctie.php",
cache: false,
success: function(html){
jQuery("#topbar").html(html);
jQuery("#topbar").fadeIn('slow',function() {
setTimeout('doRequest()',30000);
});
}
});
});
}
doRequest();
</script>
rowfunctie.php should look like this beneath:
<?php
$selectStr = "select * from test";
if ($results = MySQL($dbName, $selectStr))
{
$rowCount = MySQL_NUMROWS($results);
}
$i = 0;
while ($i < $rowCount)
{
echo '<div style="float: left; font-size:' . (MySQL_RESULT($results,$i,'count') * 5) . 'px;">' . MySQL_RESULT($results,$i,'word') . '</div>';
$i++;
}
?>

Categories