Hello, In some links I have <a href="#" onclick="delete('5415');">Delete?</a> PHP: I need a PHP code that can use that to delete post from table "post" were id = 5415. I know javascript is client side and PHP is needed to use the database, I need a javascript file to access a php file and delete the article, but i want to to pop up an alert to confirm that i want it deleted. Thanks
You can so: JS Function: function delete(id){ var conf = confirm('Are you sure to do this process?'); if(conf){ $.ajax({ type: "GET", url: "delete.php", data: "deleteid="+id+", success: function(msg){ alert(msg); } }); } } Code (markup): delete.php: <?php header('Content-type: text/plain; charset=utf-8'); if(is_numeric($_GET['id'])){ your codes... } ?> PHP:
Correct me if I'm wrong but the first part seems to be written with jQuery in mind and not simple JS. Also for the second part you need to use $_GET['deleteid'] (according to the JS you provided). Finally you can use the following PHP code to do the actual deleting with the assumption that you're using a MySQL database: <?php if(is_numeric($_GET['deleteid'])){ /* connect to database */ $mysqli = new mysqli("localhost", "my_user", "my_password", "my_db"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } /* Delete row */ if ($mysqli->query("DELETE FROM TABLE WHERE id=".$_GET['deleteid']) === TRUE) { printf("Deleted successfully."); } $mysqli->close(); } ?> PHP: keep in mind you need to change the parameters in $mysqli = new mysqli(...) to match your database's info. also change TABLE to your table name in $mysqli->query(...).
you can also use POST instead of get function delete(id){ var conf = confirm('Are you sure to do this process?'); if(conf){ $.ajax({ type: "POST", url: "delete.php", data: "deleteid="+id, success: function(msg){ alert(msg); } }); } } delete.php <?php if(isset($_POST['deleteid'])){ /* connect to database */ $mysqli = new mysqli("localhost", "my_user", "my_password", "my_db"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } /* Delete row */ if ($mysqli->query("DELETE FROM TABLE WHERE id=".$_POST['deleteid']) === TRUE) { printf("Deleted successfully."); } $mysqli->close(); } ?>