Im a beginner in PHP. I want to add the Functionality to like button. Whenever a user clicks like button then the insert query is to be run to insert values in db. There are several images on home page, the corresponding productimage info(productid) must be inserted in product_likes db.`
<?php
$user_name=$_SESSION['user_name'];
$query="SELECT * FROM product_info";
$result= mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) {
?>
<div class="w3-container"><br>
<img src="<?php echo "img/product_img/".$row['productimage'].""; ?>">
<p><b>Product Name: </b><?php echo"".$row["productname"].""?><br>
</p>
<form id="like" method="post" action="home1.php">
<button type="submit" name="like"><i class="fa fa-heart"></i> Like</button>
<?php
if(isset($_POST['like'])){
$result=mysqli_query($con,"INSERT INTO product_likes VALUES ('','".$row['productid']."','".$row1['sellerid']."','".$buyerid."')");
}
?>
</form>
</div>
<?php } ?>`
But whenever I run this the same productid, sellerid and buyerid corresponding to first image are inserted in database and only the first image is displayed. Is there a way to correct this issue?
First thing that you need to understand is, PHP is server side language, gets executed before the client, and JavaScript is client side language, gets executed after the server side has finished processing and there's no going back to the server.
When you want to do something like speaking to a server based on user's behaviour, you need to have an end-point configured and fire an AJAX call to the server. Simple example using jQuery to like a post would be:
$(function() {
$("a").click(function(e) {
e.preventDefault();
$this = $(this);
if ($(this).text().trim() == "Like") {
$.post("/posts/like", {
PostID: 1
}, function(res) {
if (res == "success")
$this.text("Unlike");
});
$this.text("Unlike");
} else {
if ($(this).text().trim() == "Unlike") {
$.post("/posts/unlike", {
PostID: 1
}, function(res) {
if (res == "success")
$this.text("Like");
});
$this.text("Like");
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Like
The above example kinda "works", because of the fall-back, but pretty much this is the concept. The whole PHP code that makes the "Like" or "Unlike" should be given separately and using jQuery's AJAX function, you need to fire it off.
Both the above URLs: /posts/unlike and /posts/like take in a data parameter PostID and based on that make the necessary changes in the database.
Related
I have been working on Like and Unlike feature with jQuery, AJAX and PHP. I am getting jQuery post request from indirect page. For example I have 2 PHP pages, viewProfile.php and LikeMail.php. LikeMail.php is being called by AJAX function in viewProfile.php.
Here is Section of viewProfile.php page's description
-----------------
| Like/Unlike |
-----------------
Here is button which actually comes from LikeMail.php by this AJAX function:
function like()
{
var req = new XMLHttpRequest();
req.onreadystatechange = function()
{
if(req.readyState==4 && req.status==200)
{
document.getElementById('like1').innerHTML=req.responseText;
}
}
req.open('POST','LikeMail.php','true');
req.send();
}
setInterval(function(){like()},1000);
HTML:
<div id="like1"></div>
Output is being shown here in this div. Button above may be Like or Unlike depends on the condition in LikeMail.php which will be described below in LikeMail.php description section.
When one of them (buttons) Like or Unlike is clicked. It then calls respective jQuery click function which sends post request to LikeMail.php.I have mentioned Indirect page in title because Like or Unlike buttons actually exists in LikeMail.php page. But due to AJAX call these buttons are being shown in viewProfile.php page. So I then send post requests through viewProfile.php to actual page LikeMail.phpIt is jQuery post for Unlike button
$(document).ready(function(){
$('#Unlike').unbind().click(function(){
$.post("LikeMail.php",
{Unlike: this.id},
function(data){
$('#response').html(data);
}
);
});
});
It is jQuery post or Like button
$(document).ready(function(){
$('#Like').unbind().click(function(){
$.post("LikeMail.php",
{Like: this.id},
function(data){
$('#response').html(data);
}
);
});
});
End of description section of viewProfile.php page
Here is Section of LikeMail.php page's description
Like or Unlike button is shown in viewProfile.php page depends upon this code:
$check_for_likes = mysqli_query($conn, "SELECT * FROM liked WHERE user1='$user1' AND user2='$user2'");
$numrows_likes = mysqli_num_rows($check_for_likes);
if (false == $numrows_likes) {
echo mysqli_error($conn);
}
if ($numrows_likes >= 1) {
echo '<input type="submit" name="Unlike" value="Unlike" id="Unlike" class="btn btn-lg btn-info edit">';
}
elseif ($numrows_likes == 0) {
echo '<input type="submit" name="Like" value="Like" id="Like" class="btn btn-lg btn-info edit">';
}
Button depends upon these two above conditions.
Now when Like button is clicked, post request from viewProfile.php comes here.
if(isset($_POST['Like'])) //When Like button in viewProfile.php is clicked then this peace of code inside if condition should run and insert some record in database
{
$total_likes = $total_likes+1;
$like = mysqli_query($conn, "UPDATE user SET user_Likes = '$total_likes' WHERE user_id = '$user2'");
$user_likes = mysqli_query($conn, "INSERT INTO liked (user1,user2) VALUES ('$user1','$user2')");
$query3 = "INSERT INTO notification (user1, user2, alert, notificationType) VALUE ('$user1','$user2','unchecked','like')";
if (mysqli_query($conn, $query3)) {
echo "Like";
} else {
echo mysqli_error($conn);
}
}
Similarly when Unlike button is clicked. This peace of code should run.
if(isset($_POST['Unlike'])) //This is the condition for Unlike button. It should delete record from databse
{
$total_likes = $total_likes-2;
$like = mysqli_query($conn, "UPDATE user SET user_Likes='$total_likes' WHERE user_id='$user2'");
$remove_user = mysqli_query($conn, "DELETE FROM liked WHERE user1='$user1' AND user2='$user2'");
$query3 = "DELETE FROM notification WHERE user1='$user1' AND user2='$user2' AND notificationType='like'";
$check = mysqli_query($conn, $query3);
if ($check) {
echo "Unlike";
} else {
echo mysqli_error($conn);
}
}
Problem:
Main problem is that jQuery post request is not being sent from viewProfile.php to LikeMail.php. Is there any way to send jQuery post request from indirect page?
I'm making a custom WYSIWYG editor with a save function, and through the save function I have run some code to get everything within a certain div, save it into a data table or overwrite it. But right now, I'm trying to load the page back.
The process is as follows: you press the save button, and it runs a PHP script called save.php, which is seen below.
My issue is that I want it to load or echo the contents within a certain div on the original html page. How would I go about doing that? I need it to work like Javascript's innerHTML function, basically.
Below are the files I use, at least the relevant parts.
test.html:
<form method="post" name="blog-post" id="blog-post">
<input type="hidden" name="postID" value="1"><!--Get the post's id-->
<div class="blog-editor-bar">
<a href="#" data-command='save'
onclick="submitForm('save.php');">
<i class='fa fa-save'></i>
</a>
</div>
<div id="blog-textarea" contenteditable>
</div>
<textarea style="display:none;" id="blog-post-cont" name="post-content"></textarea>
</form>
test.js:
function submitForm(action){
var theForm = document.getElementById("blog-post");
theForm.elements("post-content").value = document.getElementById("blog-textarea").innerHTML;
theForm.action = action;
theForm.submit();
}
save.php:
$conn = mysqli_connect('localhost', 'root', '', '');
if (mysqli_connect_errno()){
echo "<p>Connection Failed:".mysqli_connect_error()."</p>\n";
}
//store stuff in database
//Get Variables
$postid = $_POST['postID'] ? $_POST['postID'] : null;
$post = $_POST['post-content'] ? $_POST['post-content'] : null;
//if exists, overwrite
if($postid != null || $postid != ""){
$sqlSave = "SELECT * FROM wysiwyg.post WHERE idpost = $postid";
$rSave = mysqli_query($conn, $sqlSave) or die(mysqli_error($conn));
if(mysqli_num_rows($rSave)){
$sqlOverwrite = "INSERT INTO wysiwyg.post(post) VALUES(?) WHERE idpost = ?";
$stmt = mysqli_prepare($conn, $sqlOverwrite);
mysqli_stmt_bind_param($stmt, "sd", $post, $postid);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
mysqli_close($conn);
} else {
newSave();
}
loadSave();
}
function newSave(){
$sqlNewSave = "INSERT INTO wysiwyg.post(post) VALUES(?)";
$stmt = mysqli_prepare($conn, $sqlNewSave);
mysqli_stmt_bind_param($stmt, "s", $post);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
function loadSave(){
$sqlLoad = "SELECT * FROM wysiwyg.post WHERE idpost = $postid";
$rLoad = mysqli_query($conn, $sqlLoad) or die(mysqli_error($conn));
//This is the part I'm stuck on
}
Thank you all in advance for helping me out! I've been stuck on it for at least a few hours!
EDIT: Before people comment on SQL Injections, I have taken it into consideration. This is me getting the code working on my localhost before I run it through a ton of anti-sql injection methods that I have already done in the past. The code i provide is only important to the functionality at this point.
EDIT #2: The anti-injection code already exists. I guess i seem to have forgotten to provide that information. I repeat, the code I have provided here is only code relating to functionality. I have escaped the strings, trimmed, etc. and more, but that code is not necessary to provide for people to get an understanding of what it is i am trying to do.
You can use an AJAX request to communicate with the server, send data and receive a response. There are many good tutorials out there, but since I first learned it in W3Schools website I am going to refer you there.
JavaScript tutorial.
jQuery tutorial.
You can use an AJAX request which is written like this:
<script>
$(document).ready(function(){
$.ajax({ //start an AJAX call
type: 'GET', //Action: GET or POST
data: {VariableName: 'GETvalue'}, //Separate each line with a comma
url: 'Destination.php', //save.php in your case
success: function(data)){ //if values send do this
//do whatever
}
}); //end ajax request
});
</script>
This allows you to send information to your php page without refreshing
So in my example you can do this on the PHP side
<?php
echo $_GET['VariableName'];
?>
Will echo out "GETvalue as specified in the data section of the Ajax call"
EDIT************
In the AJAX call you can add dataType if you want json
$.ajax({
type: 'GET',
data: {VariableName: 'GETvalue'},
dataType: 'json' // Allows Json values or you can change it to whatever you want
url: 'Destination.php',
i want to make an like-unlike button below the post. registered user can give like. i have make the button, but i don't have idea how to send a record when user click the button. i guess i need like table, so this below is table and it field that i have :
user : id_user, username
posting : id_post, id_user, content
like : id_like, id_user, id_post
posting page and like button script :
<?php
include "database_connection.php";
$query=$dbc->query("select user.username, posting.content FROM posting inner join user on user.id_user = posting.id_user where id_post='$_GET[id]'");
$array= $query->fetch_array()
?>
<!doctype html>
<html>
<head>
<script type="text/javascript" src="post.js"></script>
</head>
<body>
<?php echo $array['username'];?>
<?php echo $array['content'];?>
<!--THIS IS LIKE BUTTON-->
<a class="like-button" href="#"><i class="fa fa-thumbs-up"></i></a>
<!--LIKE BUTTON END-->
</body>
</html>
post.js
$(function() {
$('.like-button').click(function(){
var obj = $(this);
if( obj.data('liked') ){
obj.data('liked', false);
obj.html('<i class="fa fa-thumbs-up"></i>');
}
else{
obj.data('liked', true);
obj.html('<i class="fa fa-thumbs-down"></i>');
}
});
});
Alright, so I've taken the time to create a basic working example for you.
I've included the workings of post.js in an inline script rather than a separate file for simplicity with including a PHP variable inside of the script.
Your HTML Page
<?php
include "database-connection.php";
$user = 1;// get your accessing user ID (not user id of poster)
$post = $_GET['id'];
// query checks whether user has liked the post or not and returns it as well
$query=$dbc->prepare("
SELECT `user`.`username`, `posting`.`content`, IFNULL(`like`.`id_like`,0) AS `id_like`
FROM `posting`
INNER JOIN `user` ON `user`.`id_user` = `posting`.`id_user`
LEFT JOIN `like` ON `like`.`id_user` = ? AND `like`.`id_post` = ?
WHERE `posting`.`id_post`=?");
// bind the parameters to avoid injection
$query->execute(array($user, $post, $post));
$array= $query->fetch(PDO::FETCH_ASSOC);
?>
<!doctype html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script type="text/javascript">
// previously post.js
$(function() {
$('.like-button').click(function(e){
e.preventDefault();
var obj = $(this);
// ajax query that returns a JSON object with the result of the request
$.getJSON('likes.php',{post:obj.data('post'), user: <?php echo $user; ?>}, function(data){
//console.log(data); // uncomment for debugging
if(data.error){
// query returned error, handle it however you want
} else {
if (data.like == 1){ // user now likes the post
obj.html('<i class="fa fa-thumbs-up"></i>');
} else { // user now doesn't like the post
obj.html('<i class="fa fa-thumbs-down"></i>');
}
}
});
});
});
</script>
</head>
<body>
<?php echo $array['username'];?>
<?php echo $array['content'];?>
<!--THIS IS LIKE BUTTON-->
<?php
if ($array['id_like']==0){
// user hasn't liked the post, show thumbs down
echo '<a class="like-button" href="#" data-post="'.$post.'"><i class="fa fa-thumbs-down"></i></a>';
} else {
// user has liked the post, show thumbs up
echo '<a class="like-button" href="#" data-post="'.$post.'"><i class="fa fa-thumbs-up"></i></a>';
}
?>
<!--LIKE BUTTON END-->
</body>
</html>
likes.php (the PHP script)
<?php
include "database-connection.php";
$post = $_GET['post'];
$user = $_GET['user'];
$result = (object) ['like'=>null, 'post'=>$post, 'user'=>$user];
$q = $dbc->prepare("SELECT id_like FROM `like` WHERE id_post=? AND id_user=?");
$q->execute(array($post, $user));
$r = $q->fetch(PDO::FETCH_OBJ);
if ($q->rowCount() > 0){
$like = $r->id_like;
} else {
$like = 0;
}
if ($like == 1){
// user likes post, so we unlike it by setting id_like to 0 (for false)
$like = 0;
$u = $dbc->prepare("UPDATE `like` SET id_like = 0 WHERE id_post=? AND id_user=?");
} elseif ($q->rowCount()>0) {
// update because the record exists
$like = 1;
$u = $dbc->prepare("UPDATE `like` SET id_like = 1 WHERE id_post=? AND id_user=?");
} else {
// create the record because it doesn't exist yet
$like = 1;
$u = $dbc->prepare("INSERT INTO `like` (id_like, id_post, id_user) VALUES(1, ?, ?)");
}
if($u->execute(array($post, $user))){
// update succeeded
$result->like = $like;
} else{
// there was an error
$result->error = 'failed to execute in database';
}
// return the json object to your page
echo json_encode($result);
Again, this is just the basics of how this would work. You will have to research logins, sessions, and security for yourself to manage the user who are accessing, posting, and liking the content. But I hope this helps!
Send the request to PHP page on click of like button and handle it there to update the database.
You will need to send an Ajax request to the server and then handle in in a PHP script.
Here's a way to do that.
post.js:
$(function() {
$('.like-button').click(function(){
var obj = $(this);
if( obj.data('liked') ){
obj.data('liked', false);
obj.html('<i class="fa fa-thumbs-up"></i>');
}
else{
obj.data('liked', true);
obj.html('<i class="fa fa-thumbs-down"></i>');
}
$.post('url/to/your_script.php', {
action: 'updateLikeStatus',
status: obj.data('liked'),
post_id: obj.data('id') // ID of the object that user "liked"
});
});
});
You can read more about jQuery.post() here. And here's documentation on more general jQuery.ajax() method.
your_script.php (script that deals with Ajax requests) might look something like this:
<?php
include "database_connection.php";
if (isset($_POST['action']) && $_POST['action'] === 'updateLikeStatus') {
$id_user = $_SESSION['user_id'];
$id_post = $_POST['post_id'];
if ($_POST['status'] === true) {
// adding "like"
$query = $dbc->query("
INSERT INTO like
(id_user, id_post)
VALUES ({$id_user}, {$id_post});
");
$query->query();
} else {
// removing "like"
$query = $dbc->query("
DELETE FROM like
WHERE id_user = {$id_user}
AND id_post = {$id_post};
");
$query->query();
}
}
Note that this code is just an example, you shouldn't use it directly in the production. For one thing, you can't put variables from $_POST directly into a MySQL query, because it will create an SQL Injection type vulnerability, allowing people to perform arbitrary queries on your server. One way to avoid it is by using prepared statements.
Another problem is that you will need to deal with the user authentication and authorization. I've used $_SESSION['user_id'] in my example, but it won't work unless you initialize session and populate user_id value first. Sessions are required so that one user can't like posts on behalf of another user. You can read more about sessions here.
I'm a total AJAX noob, so please forgive me, but this is what I'm trying to do...
I have a php form that submits the information via ajax to a parser file. I need to get a few ids from that form to the parser file so I can use them in my sql update. I'll try to keep my code simple but give enough info so someone can answer.
My form is being generated via a foreach loop that iterates through a list of teams and grabs their various characteristics. For simplicity, let's say the main thing I need to get to the parser file is that team_id.
I'm not sure if I need to add
<input type="hidden" name="team_id" value="<?=$team->id ?>">
or
<tr data-teamid="<?=$team->id; ?>">
or something like that to my form....but either way, it gets passed through this AJAX file...
<script type="text/javascript">
function updateNames() {
jQuery('#form-message, #form-errors').html("");
var post_data = jQuery('form[name="update_names"]').serialize();
$.ajax({
url: 'parsers/update_names.php',
method: 'POST',
data : post_data,
success: function(resp) {
if(resp == 'success'){
jQuery('#form-message').html("Names and Scores have been Updated!");
}else{
jQuery('#form-errors').html(resp);
}
}
});
return false; // <--- important, prevents the link's href (hash in this example) from executing.
}
jQuery(document).ready(function() {
$(".linkToClick").click(updateNames);
});
</script>
And is making it to my parser file, which looks like this...
require_once '../core/init.php';
$db = DB::getInstance();
$errors = [];
// $camp_id = Input::get('camp_id');
$camp_id = 18;
//Find the Teams that Belong to the Camp
$sql = "SELECT * FROM teams WHERE camp_id = $camp_id";
$teamsQ = $db->query($sql);
$all_teams = $teamsQ->results();
//validation and sanitization removed for simplicity.
if(empty($errors)){
$fields = [];
foreach($_POST as $k => $v){
if($k != 'camp_id'){
$fields[$k] = Input::get($k);
}
}
$db->update('teams',$all_teams->id,$fields);
echo 'success';
}else{
echo display_errors($errors);
}
SO. The main question I have is how do I get that camp_id and team_id into the parser file so I can use them to update my database?
A secondary question is this...is the fact that the form is being generated by a foreach loop going to make it difficult for the ajax to know which field to update?
So, how would I get that camp_id to
$sql = "SELECT * FROM teams WHERE camp_id = $camp_id";
And the team_id to
$db->update('teams',$all_teams->id,$fields);
I tried to break this down to the simplest form and it's still not getting to the function. This code...
<form name="update_names" method="post">
<input type="hidden" name="team_id" value="<?=$teams->id ?>">
<button onclick="updateNames();return false;" class="btn btn-large btn-primary pull-right">test</button>
<script type="text/javascript">
function updateNames() {
alert('test');
}
</script>
Gives me... Uncaught ReferenceError: updateNames is not defined
The jQuery .serialize() method uses the name attribute of an element to assign a variable name. It ignores the element's id, any classes and any other attribute. So, this is the correct format if using .serialize():
<input type="hidden" name="team_id" value="<?=$team->id ?>">
Looking at your ajax code, your parser file would be called parsers/update_names.php.
To verify that the desired field is getting to your parser file, add this to the top for a temporary test:
<?php
$tid = $_POST['team_id'];
echo 'Returning: ' .$tid;
die();
and temporarily modify the ajax code block to:
$.ajax({
url: 'parsers/update_names.php',
method: 'POST',
data : post_data,
success: function(resp) {
alert(resp);
{
});
return false;
If the ajax processor file (your "parser") receives the team_id data, then you will get that data returned to you in an alert box.
Thus, you can now determine:
1. That you are receiving the team_id information;
2. That the ajax back-and-forth communications are working
Note that you also can install FirePHP and echo text to the browser's console from the php processor file.
I'm trying to create a player edit system for an admin section of a football website.
The process goes as follows:
Once a coach has logged in on 'coaches.php', they can then choose what coaching session they want to look at via dropdown, which then populates the 'player' dropdown (done via js below)
coaches.php form
<form id="form1" name="form1" method="post" action="coachplayer.php?id=' .$id. '">
<label>Activity :</label>
<select name="activity" class="activity">
<option selected="selected">--Select Activity Group--</option>
<?php
include('dbconnect.php');
$sql=mysql_query("select activity from coaches where username='$coach'");
while($row=mysql_fetch_array($sql))
{
$activity2=explode(",",$row["activity"]);
foreach ($activity2 as $activity)
echo '<option value="'.$activity.'">'.$activity.'</option>';
} ?>
</select> <br/><br/>
<label>Player :</label> <select name="username" class="username">
<option selected="selected">--Select Player--</option>
</select>
<input name="thisID" type="hidden" value="<?php echo $id; ?>" />
<input type="submit" name="button" id="button" value="Log In" />
</form>
coaches.php js function
<script type="text/javascript">
$(document).ready(function()
{
$(".activity").change(function()
{
var activity=$(this).val();
var dataString = 'activity='+ activity;
$.ajax
({
type: "POST",
url: "ajax_city.php",
data: dataString,
cache: false,
success: function(html)
{
$(".username").html(html);
}
});
});
});
</script>
<style>
label
{
font-weight:bold;
padding:10px;
}
</style>
As the js above shows, the player list is handled via a separate page with a query on it as follows:
<?php
if($_POST['activity'])
{
$activity=$_POST['activity'];
$sql=mysql_query("SELECT id, username FROM stats WHERE activity='$activity'");
while($row=mysql_fetch_array($sql))
{
$id=$row['id'];
$username=$row['username'];
$activity=$row['activity'];
echo '<option value="'.$username.'">'.$username.'</option>';
}
}
?>
Once all of this is done, the coach submits the form, taking them to coachplayer.php. This is where the problem begins.
coachplayer.php is a template page, with empty fields filled with echo's, to echo the player details where necessary. A query runs to get the id of the selected player, bring up their details and fill the page. Instead, however, it echos what usually comes up if the query cannot find a matching result via $playerCount as shown below, saying "Player doesn't exist".
coachplayer.php SQL query
<?php
// Check to see the URL variable is set and that it exists in the database
if (isset($_GET['id'])) {
// Connect to the MySQL database
$targetU = preg_replace('#[^0-9]#i', '', $_GET['id']);
// Use this var to check to see if this ID exists, if yes then get the player
// details, if no then exit this script and give message why
$sql = mysql_query("SELECT * FROM stats WHERE id='$targetU' LIMIT 1");
$playerCount = mysql_num_rows($sql); // count the output amount
if ($playerCount > 0) {
// get all the product details
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$username = $row["username"];
$position = $row["position"];
$activity = $row["activity"];
$agegroup = $row["agegroup"];
$coach = $row["coach"];
$goals = $row["goals"];
$assists = $row["assists"];
$cleans = $row["cleans"];
$motm = $row["motm"];
$attend = $row["attend"];
}
} else {
echo "Player doesn't exist.";
exit();
}
} else {
echo "Data to render this page is missing.";
exit();
}
?>
As I'm sure you can tell, I'm not too great of a coder, so it's very possible that it's a simply var that needs changing but any ideas where I have gone wrong will be much appreciated.
Thank you in advance.
You are using a form with post method. And the action URL seems quite different
<form id="form1" name="form1" method="post" action="coachplayer.php?id=' .$id. '">
Change it to
<form id="form1" name="form1" method="post" action="coachplayer.php">
and in coachplayer.php. Use
isset($_POST['thisID']
Ok, I admit this is not an answer to your question BUT, to be honest there is no such thing as 'your question' - there are contents of four files each of them with their own problems, and an implicit request to grock all of those 4 files and tell you what does not work and how it should be made to work.
Having said that:
Divide and conquer. Make sure your first script does exactly what needs to be done. Then second, then 3rd and only then 4th.
Use tools: For javascript - Dev Tools or Firebug. For queries - MySQL Workbench
When testing JS use console (here you can try out your js code interactively.
) and source tabs - there you can set breakpoints and follow execution line by line. Look at network tab - there you can see request (headers) and responses.
When debugging PHP comment out all your code and use var_dump every step of the way. I use PHP Storm so that i can debug PHP line by line real time.
And better ask questions that can be described with the least lines of code
PS. You can simulate GET requests by typing url in browser - that way you know whether your server side works or not without relying on unreliable JS
Just a Quick look, but your sql Statement seems wrong. Your sql query will search for the Player with the id '$targetU'. Make sure to enter the variable correctly