Search code examples
javascriptalertconfirm

Adding JavaScript to a php script


I have written a php script to act as a live search of database tables, so it requires that the HTML is written as a part of the php script. I need to add some JavaScript so that when I want to delete a certain element from a database table it prompts me to confirm the deletion.

This is what I am going for, however when I run the script it gives me an unexpected string error:

while ($row = mysqli_fetch_assoc($result)) {
$output .= '<tbody>   
    <tr> 
        <td>'.$row['first_name'].' '.$row['last_name'].'</td>
        <td>'.$row['email'].'</td>
        <td>'.$row['phone'].'</td>
        <td>'.$row['address'].'</td>
        <td>'.$row['id_num'].'</td>
        <td>
            <a class="edittablebtn" href="employees_database_page.php?edit_employee='.$row['id'].'"><i class="fa fa-cog" style="padding:5px;"></i></a>     
            <a class="edittablebtn"><i class="fa fa-envelope" style="padding:5px;"></i></a>                 
            <a class="deltablebtn" onclick="return confirm('You are about to remove this analysis from client ordering selection.\nAre you sure you want to continue?');" href="employees_database_page.php?del_employee='.$row['id'].'"><i class="fa fa-user-times" style="padding:5px;"></i></a>       
        </td> 
    </tr>    
</tbody>';          
}

echo $output;

The JavaScript is added inline at the deltablebtn class. The JavaScript code is as follows:

onclick="return confirm('You are about to remove this analysis from client ordering selection.\nAre you sure you want to continue?');" 

Solution

  • You need to escape quotes in your JavaScript expression. So change this line:

    onclick="return confirm('You are about to remove this analysis from client ordering selection.\nAre you sure you want to continue?');"
    

    to:

    onclick="return confirm(\'You are about to remove this analysis from client ordering selection.\nAre you sure you want to continue?\');"