0

On the user's profile page he can subscribe to or unsubscribe from a newsletter. I want this to be handled with ajax calls so the site doesn't have to be reloaded.

PHP part (to get the email address):

    $email = $_SESSION['userId'][0]['email'];
    $nls = new \Models\NewsletterModel();
    $userIsSubscribed = $nls->getNewsletterEmail($email);
    if ($userIsSubscribed[0]['newsletter_verified'] == 0) {
         $f3->set('subscribed', false);
    elseif ($userIsSubscribed[0]['newsletter_verified'] == 1)
         $f3->set('subscribed', true);

HTML part (to show right text in button):

            <check if="{{ @subscribed }}">
                <true>
                    <a href="#" class="newsletter item btn btn-primary subscribed">Unsubscribe From Newsletter</a>
                </true>
                <false>
                    <a href="#" class="newsletter item btn btn-primary unsubscribed">Subscribe To Newsletter</a>
                </false>
            </check>

JS part with the ajax call:

    var userEmail = $.ajax({
     url: "/getUserEmail",
     success: function (email) {
      var userEmail = email;

$.when(userEmail).done(function (email) {
  if ($(".newsletter").hasClass("unsubscribed")) {
    $(".unsubscribed").click(function () {
      $.ajax({
        type: "POST",
        url: "/newsletter/activate",
        data: { json: JSON.stringify(userEmail) },
        dataType: "json",
        success: function (data) {
          $(".newsletter").html("Unsubscribe From Newsletter");
          $(".newsletter")
            .removeClass("unsubscribed")
            .addClass("subscribed");
        },
      })
        .done(function (data) {})
        .fail(function (data) {});
    });
  } else if ($(".newsletter").hasClass("subscribed")) {
    $(".subscribed").click(function () {
      console.log(userEmail);
      $.ajax({
        type: "POST",
        url: "/newsletter/deactivate",
        data: { json: JSON.stringify(userEmail) },
        dataType: "json",
        success: function (data) {
          $(".newsletter").html("Subscribe To Newsletter");
          $(".newsletter")
            .removeClass("subscribed")
            .addClass("unsubscribed");
        },
      })
        .done(function (data) {})
        .fail(function (data) {});
    });
  }
});
 },
});

Desired outcome: The ajax call for subscribing works fine. The ajax call for unsubscribing works fine aswell, but only if the page got reloaded or the used clicked another route and comes back to the profile page.

I don't understand why I cannot "toggle" between subscribe and unsubscribe.

Wondarar
  • 123
  • 1
  • 2
  • 11
  • 2
    It's because when the page first loads the `.unsubscribed` element does not exist. You need to use a delegated event handler for them both. See the duplicate for more information – Rory McCrossan Jul 27 '20 at 21:18
  • 1
    That `check` and `true` and `false` tags are processed server-side, and simply removing the class has no effect here; to change the visibility of the buttons after an ajax call, you need to a) output both b) hide one of them c) toggle both buttons' visibility after the ajax call (one way to do c) is via adding/removing a class, but you can also use jQuery's `show()` / `hide()` for instance) ((you should also add those click handlers to both buttons no matter what)) – Chris G Jul 27 '20 at 21:20
  • Thanks for the link/hint, and your quick answers. @ChrisG, I couldn't completely understand what you mean so I used .text() --- so: I added "if ($(this).text() == "Subscribe To Newsletter") .... then ajax call, and vice versa. Works fine. – Wondarar Jul 29 '20 at 18:17

0 Answers0