0

I have created an 'add to favourites' button successfully and am now having difficulty with 'remove from favourites' part.

I'm not sure of the correct way to handle multiple ajax actions in the PHP file. My code so far looks like this:

HTML

<div class="favourite-links">
  <a href="inc/functions?action=remove&..." id="remove">
Remove From Favourites
</a>
  <a href="inc/functions.php?action=add&..." id="add">
Add to Favourites
</a>
</div>

JQUERY

$(document).ready(function() {

  $('#add').click(function(event) {
    event.preventDefault();

    var courseData = {...}

    $.ajax({
      url: "inc/functions.php",
      type: "POST",
      data: courseData,
      success: function() {
        $('#add').css('display', 'none');
        $('#remove').css('display', 'inline');
        alert('successful');
      }
    });
    return false;
  });
});

PHP

<?php require("../../Common2.php"); 
$sessionID = $_COOKIE['PHPSESSID'];
$student = $_POST['userid'];
$courseID = $_POST['courseID'];
$courseName = $_POST['courseName'];


$query = "INSERT IGNORE INTO course_tag_fetch
    (sessionID, courseID, courseName, userid)
    VALUES
    ('$sessionID', '$courseID', '$courseName', '$student')";

    $query_run = mysql_query($query);

    if ($query_run) {
        echo 'Success';
    } else {
        echo 'Failed';

    }

?>

I want the remove action to DELETE from the database. Is the best way to put the actions in if statements? E.g.

if (action == "add") {
--- INSERT query --- }

if (action == "remove) {
--- DELETE query ---}

Or is there a more appropriate way to do this? Any help much appreciated.

sol
  • 20,947
  • 5
  • 36
  • 56
  • You could add `async: false` to the jQuery calls so that the delete call won't be called before the add call if you click multiple times. – Bart Bergmans Dec 01 '16 at 14:57
  • NEVER use a link to update a database. Just one visit by google will add and delete and possibly add, add, add just by crawling your pages – mplungjan Dec 01 '16 at 15:01
  • @mplungjan Thanks, can I just change it to a different element, like a button? – sol Dec 01 '16 at 15:03
  • @BartBergmans Thanks, I'll add that – sol Dec 01 '16 at 15:04
  • Just do not have it in an href of a link. You can have it in a data-attribute so it is not followed and have the script read the attribute instead of the href – mplungjan Dec 01 '16 at 15:04
  • @mplungjan Ok thanks, good point. I'll change that! – sol Dec 01 '16 at 15:07
  • @Bart Bergmans: Never recommend `async: false`. It has been deprecated for good reason. Best to work the way browsers work (e.g. asynchronously). Use the ajax promises etc. – Gone Coding Dec 01 '16 at 15:08
  • @GoneCoding Didn't know that. Thanks! – Bart Bergmans Dec 01 '16 at 15:09

1 Answers1

0

In your PHP code

$action = trim($_REQUEST['action']);
switch($action){
case 'add':
// insert query here
break;
case 'remove':
// delete query here
break;
}

Do not user mysql user PDO instead

geeksalah
  • 51
  • 6