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.