In my project, I added some JavaScript to avoid users clicking the same button many times. There is one page where it fetches data from the registration page. Each data row I put add an unfriend button (disabled). Once the user clicks add, the prompt box appears to ask the user to enter a subject and click ok. After clicking ok, the unfriend button will be clickable.
Here is my problem: once clicking the add button, the prompt appears and after clicking ok, the data does not insert into the database.
If I click the unfriend button it inserts into the database. I want the data submitted whenever the user clicks the add button. I think it's because this form has two submit buttons but I don't know how to distinguish between them.
Here is the code:
<?php
session_start();
$mysqli = new MySQLi('127.0.0.1','root','','learning_malaysia');
$sql = "SELECT * FROM tutor_register INNER JOIN tutorskill ON tutor_register.register_ID = tutorskill.register_ID";
$result = mysqli_query($mysqli,$sql);
?>
<html>
<script>
function myFunction(form){
var subject = prompt("Please enter Subject that want to study");
if (subject != null){
form['subject'].value = subject;
form['btn'].disabled = false;
form['add'].disabled = true;
form['add'].value = "request sent";
form['add'].submit();
return false;
}
form['add'].disabled = false;
form['btn'].disabled = true;
form['add'].value = "Add friend";
return true;
}
</script>
<body>
<?php
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_array($result))
{
$register_ID = $row["register_ID"];
$username = $row['username'];
?>
<form method="post" id="form" enctype="multipart/form-data" autocomplete="off">
<td><input type="submit" value="unfriend" id="btn" disabled />
<input type="hidden" name="id" value="<?php echo $row['register_ID'];?>" />
<input type="hidden" id="subject" name="subject" data-uid=<?php echo $_SESSION['sid'] ;?>/>
<input type="submit" onclick="return myFunction(this.form);" name="addfriend" data-type='addfriend' id="add" class="btn" value="add" />
</td>
</form>
<?php
}
}
?>
<?php
if(isset($_POST['subject']) and $_POST['id']) {
$user_id = $_SESSION['sid'];
$friend_id = $_POST['id'];
$status = "yes";
$subject = $_POST['subject'];
$sql = "INSERT INTO friends(user_id,status,subject,friend_id)" ."VALUES('$user_id','yes','$subject','$friend_id') ";
if($mysqli->query($sql) === true) {
$_SESSION['status'] = "yes";
$_SESSION['friend_id'] = $friend_id;
$_SESSION['user_id'] = $user_id;
} else {
}
}
?>
</body>
</html>