either ajax or php is broken but cant see where - javascript

i am having some trouble with some script on my site.
i followed part of a tutorial as i liked the friend adding part but didn't want to change the whole site.
i used his code but obviously had to change some it to work on my site.
the idea is you visit someone else's profile and you can click to either block or send a friend request.
i am not sure where the issue is. i cant see any thing wrong in the php but is is possible i am missing something there as i am no expert, i am even less of an expert with javascript/ajax so this leads me to believe i have broken something in that.
here are my codes.
//Script on the profile.php page
function friendToggle(type,user,elem){
var conf = confirm("Press OK to confirm the '"+type+"' action for user <?php echo $username; ?>.");
if(conf != true){
return false;
}
_(elem).innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "friend_system.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "friend_request_sent"){
_(elem).innerHTML = 'OK Friend Request Sent';
} else if(ajax.responseText == "unfriend_ok"){
_(elem).innerHTML = '<button onclick="friendToggle(\'friend\',\'<?php echo $id; ?>\',\'friendBtn\')">Request As Friend</button>';
} else {
alert(ajax.responseText);
_(elem).innerHTML = 'Try again later';
}
}
}
ajax.send("type="+type+"&id="+id);
}
//php script for the friend_system.php page
<?php
include_once("scripts/checkuserlog.php");
?>
<?php
if (isset($_POST['type']) && isset($_POST['id'])){
$id = preg_replace('#[^a-z0-9]#i', '', $_POST['id']);
$sql = "SELECT COUNT(id) FROM myMembers WHERE id='$id' AND activated='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$exist_count = mysqli_fetch_row($query);
if($exist_count[0] < 1){
mysqli_close($db_conx);
echo "$username does not exist.";
exit();
}
if($_POST['type'] == "friend"){
$sql = "SELECT COUNT(id) FROM blockedusers WHERE blocker='$id' AND blockee='$logOptions_id' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$blockcount1 = mysqli_fetch_row($query);
$sql = "SELECT COUNT(id) FROM blockedusers WHERE blocker='$logOptions_id' AND blockee='$id' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$blockcount2 = mysqli_fetch_row($query);
$sql = "SELECT COUNT(id) FROM friends WHERE user1='$logOptions_id' AND user2='$id' AND accepted='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row_count1 = mysqli_fetch_row($query);
$sql = "SELECT COUNT(id) FROM friends WHERE user1='$id' AND user2='$logOptions_id' AND accepted='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row_count2 = mysqli_fetch_row($query);
$sql = "SELECT COUNT(id) FROM friends WHERE user1='$logOptions_id' AND user2='$id' AND accepted='0' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row_count3 = mysqli_fetch_row($query);
$sql = "SELECT COUNT(id) FROM friends WHERE user1='$id' AND user2='$logOptions_id' AND accepted='0' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row_count4 = mysqli_fetch_row($query);
if($blockcount1[0] > 0){
mysqli_close($db_conx);
echo "$user has you blocked, we cannot proceed.";
exit();
} else if($blockcount2[0] > 0){
mysqli_close($db_conx);
echo "You must first unblock $user in order to friend with them.";
exit();
} else if ($row_count1[0] > 0 || $row_count2[0] > 0) {
mysqli_close($db_conx);
echo "You are already friends with $user.";
exit();
} else if ($row_count3[0] > 0) {
mysqli_close($db_conx);
echo "You have a pending friend request already sent to $user.";
exit();
} else if ($row_count4[0] > 0) {
mysqli_close($db_conx);
echo "$user has requested to friend with you first. Check your friend requests.";
exit();
} else {
$sql = "INSERT INTO friends(user1, user2, datemade) VALUES('$logOptions_id','$id',now())";
$query = mysqli_query($db_conx, $sql);
mysqli_close($db_conx);
echo "friend_request_sent";
exit();
}
} else if($_POST['type'] == "unfriend"){
$sql = "SELECT COUNT(id) FROM friends WHERE user1='$logOptions_id' AND user2='$id' AND accepted='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row_count1 = mysqli_fetch_row($query);
$sql = "SELECT COUNT(id) FROM friends WHERE user1='$id' AND user2='$logOptions_id' AND accepted='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row_count2 = mysqli_fetch_row($query);
if ($row_count1[0] > 0) {
$sql = "DELETE FROM friends WHERE user1='$logOptions_id' AND user2='$id' AND accepted='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
mysqli_close($db_conx);
echo "unfriend_ok";
exit();
} else if ($row_count2[0] > 0) {
$sql = "DELETE FROM friends WHERE user1='$id' AND user2='$logOptions_id' AND accepted='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
mysqli_close($db_conx);
echo "unfriend_ok";
exit();
} else {
mysqli_close($db_conx);
echo "No friendship could be found between your account and $user, therefore we cannot unfriend you.";
exit();
}
}
}
?>
i have been looking at it now for a couple of days and am starting to not see the wood for the trees.
When i click on the request as fiend button, i get the dialog box fine, click ok and then it replaces the button with "please wait..." but that is where it stops. i have checked and nothing is being added to the database niether.
any help you could offer would be much apreciated.
thanks

I have provided an example of using jQuery to do this simply.
Here is what your button and response box would look like.
<div id="responsemessage<?php ///YOU USER ID FROM PHP// ?>" style="padding:2px; display:none;"></div>
<input name="" type="button" value="Friend Me" onClick="friendToggle('friend','<?php ///YOU USER ID FROM PHP// ?>')"/>
<input name="" type="button" value="Block Me" onClick="friendToggle('block','<?php ///YOU USER ID FROM PHP// ?>')"/>
This is what your jQuery function would look like. You will need to include the jQuery lib in your header.
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>function friendToggle(type,user){
///This is the ajax request via jQuery///
$.ajax({
url: 'friend_system.php?action='+type+'&user='+user,
success: function(data) {
///This is where the response from you php is handled. Sky's the limit//
if(data == 'good'){
$("#responsemessage"+user).html('You now have a friend.');
}else{
$("#responsemessage"+user).html(data);
}
}});
}</script>
</head>
And here is the php to process the requests this would be in your friend_system.php
<?php
include('YOUR CONNECTION DETAILS FILE');
$act = $_REQUEST['action'];
if($act == 'friend'){
$a = mysql_query("SELECT * FROM friends WHERE user1 = '".$_REQUEST['user']."'");
if(mysql_num_rows($a) > 0){
echo 'You are already friends.';
}else{
mysql_query("INSERT INTO friends SET user1 = '".$_REQUEST['user']."', user2 = '', datemade = '".date('d-m-Y H:i')."'");
echo 'good';
}
}
if($act == 'block'){
mysql_query("INSERT INTO blockedusers SET blocker='YOUR ID HERE, HOPE ITS PASSED VIA SESSION' AND blockee='".$_REQUEST['user']."'");
echo 'You have blocked this user.';
}
?>
I hope this helps you... Also be sure to check out http://jquery.com/

Related

Alert box is not appear when I submit data

There are many similiar questions but I don't have any error, where I need to do changes.
I have put alert boxes in my code but non are appearing.
Here is my code-
if(isset($_POST['submit'])){
$test= "select * from stable where Email = '$Email'";
$queryResult = $conn->query($test);
$foundRows = $queryResult->num_rows;
if($foundRows >= 1)
$mailerr="Email already register";
else {
header("location:student.php?id=".$row['id']);
$sql = "INSERT INTO stable
(Firstname,Lastname,DOB,Email,Phno,
Gender,Address,City,ZipCode,State,Country,
Hobbies,Course,id,Time,Date,IP)
VALUES('$Firstname','$Lastname','$Dob','$Email',
'$Phno','$Gender','$Address','$City','$Zipcode',
'$State','$Country','$Hobby','$Course','',
'$Time','$date','$IP')";
if($conn->query($sql))
?>
<script> alert('Data Inserted successfully');
window.location.href='student.php?id=<?php echo $id;?>' </script>
<?php
}
}
You can wrap the script tag with all the js in string and echo it. it will work
if($conn->query($sql)){
echo "<script> alert('Data Inserted successfully')window.location.href='student.php?id="+$id+"</script>";
}
Try this:
if(isset($_POST['submit'])){
$test= "select * from stable where Email = '$Email'";
$queryResult = $conn->query($test);
$foundRows = $queryResult->num_rows;
if($foundRows >= 1)
$mailerr="Email already register";
else {
header("location:student.php?id=".$row['id']);
$sql = "INSERT INTO stable
(Firstname,Lastname,DOB,Email,Phno,
Gender,Address,City,ZipCode,State,Country,
Hobbies,Course,id,Time,Date,IP)
VALUES('$Firstname','$Lastname','$Dob','$Email',
'$Phno','$Gender','$Address','$City','$Zipcode',
'$State','$Country','$Hobby','$Course','',
'$Time','$date','$IP')";
if($conn->query($sql)){
echo "<script type='text/javascript'>alert('Data Inserted successfully');
window.location.href='student.php?id=".$id."';
</script>";
}
}
}

Deleting more tables at the same time & getting error when using ajax.response text

I have two problems.
First one:
I have a two tables in my database (gmembers and groups) and I want to check if a user quit from the group and there are no memebrs remaining in it delete that group. Firstly I collected every groups that has no members in an array called junk. Then I used a for loop to access every item of the junk array and delete from the database. But since I want to delete from two tables at the same time I had to use JOIN. I don't know why but this only delete from the gmembers table and nothing happens with the groups table.
I tried to tear it into two parts and delete once from the gmembers and then from the groups in another sql but I got the same result as I got with the JOIN one.
Code:
<?php
if(isset($_POST["action"]) && $_POST['action'] == "quit_group"){
// Empty check
if($gS == "" || $uS == ""){
exit();
}
// Make sure already member
$sql = "SELECT id FROM gmembers WHERE gname=? AND mname=? AND approved=? LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sss",$gS,$uS,$one);
$stmt->execute();
$stmt->store_result();
$stmt->fetch();
$numrows = $stmt->num_rows;
if($numrows < 1){
exit();
}
// Remove from the database
$sql = "DELETE FROM gmembers WHERE mname=? AND gname=? LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss",$uS,$gS);
$stmt->execute();
$stmt->close();
// If the group is empty remove from the database
$junk = array();
$sql = "SELECT * FROM gmembers WHERE approved=? AND admin=?";
$stmt = $conn->prepare($sql);
$stmt->bind_result($zero,$zero);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()){
array_push($junk, $row["gname"]);
}
$stmt->close();
for($i=0; $i<count($junk); $i++){
// Delete from gmembers
$groupa = $junk[$i];
$sql = "DELETE * FROM gmembers gm JOIN groups gr ON gm.gname = gr.name WHERE gm.gname=? AND gr.name=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss",$groupa,$groupa);
$stmt->execute();
$stmt->close();
}
echo "was_removed";
exit();
}
?>
Second One:
I'm also having problems with ajax.responseText. When a group has been created and there are no erros I want to header the user to that groups that he/she has just created. So when everything is fine I echo the name of the group ($name) and the was created title. Then with javascript I check for these and I header them to the group page. But at this point my code fails. It only echos group_created|example group in an alert box and window.location = "group.php?g="+sid; does not work.
PHP Code:
<?php
// Create new group
if(isset($_POST["action"]) && $_POST['action'] == "new_group"){
// GATHER THE POSTED DATA INTO LOCAL VARIABLES
$name = preg_replace('#[^a-z 0-9]#i', '', $_POST['name']);
$inv = preg_replace('#[^0-9.]#', '', $_POST['inv']);
// DUPLICATE DATA CHECKS FOR USERNAME AND EMAIL
if ($inv == "1"){
$inv = "0";
}
if ($inv == "2"){
$inv = "1";
}
$sql = "SELECT id FROM groups WHERE name=? LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s",$name);
$stmt->execute();
$stmt->store_result();
$stmt->fetch();
$n_check = $stmt->num_rows;
// FORM DATA ERROR HANDLING
if($name == "" || $inv == ""){
echo "The form submission is missing values.";
exit();
} else if ($n_check > 0){
echo "The group name you entered is alreay taken";
exit();
} else if (strlen($name) < 3 || strlen($name) > 50) {
echo "Group name must be between 3 and 50 characters";
exit();
} else if (is_numeric($name[0])) {
echo 'Group name cannot begin with a number';
exit();
} else {
$stmt->close();
// END FORM DATA ERROR HANDLING
// Begin Insertion of data into the database
// Add group to database
$gicon = "group_icon.png";
$sql = "INSERT INTO groups (name, creation, logo, invrule, creator)
VALUES(?,NOW(),?,?,?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ssss",$name,$gicon,$inv,$uS);
$stmt->execute();
$stmt->close();
// Add to group member to database
$sql = "INSERT INTO gmembers (gname, mname, approved, admin)
VALUES(?,?,?,?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ssss",$name,$uS,$one,$one);
$stmt->execute();
$stmt->close();
if (!file_exists("../groups")) {
mkdir("../groups", 0755);
}
// Create directory(folder) to hold each user's files(pics, MP3s, etc.)
if (!file_exists("../groups/$name")) {
mkdir("../groups/$name", 0755);
}
$gLogo = '../images/group_icon.png';
$gLogo2 = "../groups/$name/group_icon.png";
if (!copy($gLogo, $gLogo2)) {
echo "failed to create logo.";
}
echo "group_created|$name";
exit();
}
exit();
}
?>
The error handling, inserting, folder/file creating etc. works perfect except this line: echo "group_created|$name";
JS Code:
function createGroup(){
var name = _("gname").value;
var inv = _("invite").value;
if(name == "" || inv == ""){
alert("Fill in all fields");
return false;
}else{
status.innerHTML = 'please wait...';
var ajax = ajaxObj("POST", "php_parsers/group_parser.php");
ajax.onreadystatechange = function(){
if(ajaxReturn(ajax) == true){
var datArray = ajax.responseText.split("|");
if(datArray[0] == "group_created"){
var sid = datArray[1];
window.location = "group.php?g="+sid;
}else{
alert(ajax.responseText);
}
}
}
ajax.send("action=new_group&name="+name+"&inv="+inv);
}
}
Here I check for what ajax gives back and I split into two part the echo "group_created|$name"; but the window.location function does not work.
For the Second One
Use:
window.Location.assign("group.php?g="+sid);
Or:
window.Location.replace("group.php?g="+sid);

Want to Code Cases on alert on bodyload

I have Remind_Date option in my table and I want to compare Remind_Date with Current_Date. If both are equal then alert will pop up on body on load showing corresponding member name. and also I want to develop cases for the alert. Alert will pop up 2 days or 3 days before remind date.
$now=date("Y/m/d");
$sql = "select RemindDate from payment ";
$result = mysql_query($sql) or die(mysql_error());
while($rowval2 = mysql_fetch_array($result))
{
$RemindDate=$rowval2['RemindDate'];
}
$sql = "select MemName from payment where $RemindDate = '".$now."' ";
$result = mysql_query($sql) or die(mysql_error());
while($rowval2 = mysql_fetch_array($result))
{
$MemName=$rowval2['MemName'];
}
?>
</script>
<body onload= "alert('<?php echo $MemName ; ?>')">

Session-based login not working as expected

I have been developing a PHP and mysqli based social network as a side project. All has been going well up till this point. Everyone can register and I am using the crypt function to store passwords.
I am using an if and else statement with the password_verify function where I set $_SESSION variables and cookies in order to login. Again this works and once logged in the system redirects me to my user profile as it should.
However my site-top.php file does not work as it should; what should happen is that the dynamic login link buttons should change from the login and register buttons to the logout, profile and notification buttons.
Also the add as friend button and block button are disabled on my profile (as it should as I don't want to block or friend myself) but they are also disabled when I visit another's profile which it should not.
Here is the code for my site top for the time being. I have also got a check-login-status file should you wish me to post the code for that or any others:
<?php
// It is important for any file that includes this file, to have
// check_login_status.php included at its very top.
$envelope = '<img src="assets/note_dead.png" width="33" height="33" alt="Notes" title="This envelope is for logged in members">';
$loginLink = '<li><a class="tooltip-bottom" data-tooltip="Register an Account" href="signup.php">Register</a></li>
<li><a class="tooltip-bottom" data-tooltip="Login" href="login.php">Login</a></li>';
if($user_ok == true) {
$sql = "SELECT notescheck FROM users WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
$notescheck = $row[0];
$sql = "SELECT id FROM notifications WHERE username='$log_username' AND date_time > '$notescheck' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query);
if ($numrows == 0) {
$envelope = '<img src="assets/note_still.png" width="33" height="33" alt="Notes">';
} else {
$envelope = '<img src="assets/note_flash.gif" width="33" height="33" alt="Notes">';
}
$loginLink = '<li><a class="tooltip-bottom" data-tooltip="Logout" href="logout.php">Logout</a></li><li>'.$log_username.'</li>';
}
?>
OK this is my check-login-status.php script for all that wanted it...
<?php
session_start();
include_once("db_conx.php");
// Files that inculde this file at the very top would NOT require
// connection to database or session_start(), be careful.
// Initialize some vars
$user_ok = false;
$log_id = "";
$log_username = "";
$log_password = "";
// User Verify function
function evalLoggedUser($conx,$id,$u,$p){
$sql = "SELECT ip FROM users WHERE id='$id' AND username='$u' AND password='$p' AND activated='1' LIMIT 1";
$query = mysqli_query($conx, $sql);
$numrows = mysqli_num_rows($query);
if($numrows > 0){
return true;
}
}
if(isset($_SESSION["userid"]) && isset($_SESSION["username"]) && isset($_SESSION["password"])) {
$log_id = preg_replace('#[^0-9]#', '', $_SESSION['userid']);
$log_username = preg_replace('#[^a-z0-9]#i', '', $_SESSION['username']);
$log_password = preg_replace('#[^a-z0-9]#i', '', $_SESSION['password']);
// Verify the user
$user_ok = evalLoggedUser($db_conx,$log_id,$log_username,$log_password);
} else if(isset($_COOKIE["id"]) && isset($_COOKIE["user"]) && isset($_COOKIE["pass"])){
$_SESSION['userid'] = preg_replace('#[^0-9]#', '', $_COOKIE['id']);
$_SESSION['username'] = preg_replace('#[^a-z0-9]#i', '', $_COOKIE['user']);
$_SESSION['password'] = preg_replace('#[^a-z0-9]#i', '', $_COOKIE['pass']);
$log_id = $_SESSION['userid'];
$log_username = $_SESSION['username'];
$log_password = $_SESSION['password'];
// Verify the user
$user_ok = evalLoggedUser($db_conx,$log_id,$log_username,$log_password);
if($user_ok == true){
// Update their lastlogin datetime field
$sql = "UPDATE users SET lastlogin=now() WHERE id='$log_id' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
}
}
?>

Signup Verification

Every time I leave any textbox unfilled for the 1st time, it would be registered to the db same as if I leave all the textboxes empty but when you do it for the 2nd time (any of the two), that would be the time the alert box would pop-up... I don't what to do.
Help me please.
Here's my code:
<?php
ini_set('display_errors', 0);
$email= $_POST['email'];
$user= $_POST['user'];
$password= $_POST['password'];
$image =($_FILES['image']['name']);
$submit= $_POST['submit'];
if (empty($email) || empty($password) || empty($user) )
{
echo "<script type='text/javascript'>
alert('You did not complete all of the required fields');
window.location='blah2.php';
</script>";
}
if(isset($submit))
{
$con = mysqli_connect("localhost", "root", "", "top")
or die('error in connection'.mysqli_connect_error());
$q = "SELECT username , email FROM registries WHERE username = ? OR email = ?";
$stmt = mysqli_prepare ($con, $q);
mysqli_stmt_bind_param($stmt, 'ss', $user, $email);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $user , $email);
mysqli_stmt_store_result($stmt);
$result = mysqli_stmt_num_rows($stmt);
if($result > 0)
{
echo "<script type='text/javascript'>
alert('Email address or Username is already taken. Please pick another one.');
window.location='blah2.php';
</script>";
}
else
{
$q="INSERT INTO registries VALUES (?,?,?,?)";
$stmt = mysqli_prepare($con, $q);
move_uploaded_file($_FILES["image"]["tmp_name"],"uploads/" . $_FILES["image"]["name"]);
mysqli_stmt_bind_param($stmt, 'ssss', $email, $user, $password, $image);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
mysqli_stmt_close($stmt);
header('Location: blah.php');
}
}
with this
$submit= $_POST['submit'];
$submit is always set
maybe you could try
if (isset($_POST['Submit']))
and for debugging purpose you could try to var_dump $email, $password and $user and check if maybe they are really empty when you post your form once or twice
If I understand you right then just move
if(isset($submit)){
on top of your code right after
ini_set('display_errors', 0);

Categories

Resources