AJAX Unsubscribe not working

My AJAX is not working and I am tired of scratching my head.  I have an unsubscribe page that places the persons email in the url and i _GET it from there. For some reason it is not working.
It is a Wordpress site.
<html>
    <?php
        if (isset($_GET['unsubscribe'])) {
            $unsub = $_GET['unsubscribe'];
        } else {
            $unsub = "";
        }
        ?>
        <div class="unsub-cont">
            <div class="frown"><img class="alignnone size-full wp-image-102" src="https://www.rockintuit.com/wp-content/uploads/2017/09/frown_face-1.png" alt="frown_face" width="200" height="200" /></div>
            <div class="unsubscribe_right">

                We are sorry to see you go!<br />Please feel free to stay in touch with us if we can ever be of assistance.
                <br /><br />
                <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
                <script>
                    $(document).ready(function () {
                        $(".frown").show('slow');
                        $("#unjoin").on('submit', function (e) {
                            e.preventDefault();

                            var div = $(".frown");
                            div.animate({margin: '0 0 0 41%', padding: '0'}, "slow");
                            $(".unsubscribe_right").hide('slow');
                            div.animate({width: '400px', opacity: '0.8'}, "slow");

                            $.ajax({
                                url: '/includes/unsubscribe.php',
                                data: $("#unjoin").serialize(),
                                type: 'POST',
                                dataType: 'JSON',
                                success: function (response) {
                                    $("#unsubscribe_bye").html(response.success);
                                    console.log(response);
                                    $("#unjoin")[0].reset();
                                    $("#unsubscribe_bye").show('slow');
                                }
                            });
                        });
                    });
                </script>
                <form id="unjoin" method="post">
                    <input id="email" name="email" type="text" value="<?php echo $unsub; ?>" /><br />
                    <input type="submit" name="submit" id="submit" value="Click Here To Unsubscribe">
                </form>
            </div>
            <div id="unsubscribe_bye" class="unsubscribe_bye" style="display:none;">
                <b>BYE!</b><br /><br />Feel free to visit us in the future!
            </div>
        </div>

Open in new window



THE AJAX CALL PHP Page
<?php
header("Content-Type: application/json");
error_reporting(E_ALL);
ini_set('display_errors', '1');

// DATABASE CONNECTION AND SELECTION VARIABLES - GET THESE FROM YOUR HOSTING COMPANY
$db_host = "localhost"; // PROBABLY THIS IS OK
$db_name = "blahblahblah";
$db_user = "blahblahblah";
$db_word = "blahblahblah";

$dsn = "mysql:host=$db_host;dbname=$db_name";
try {
    $pdo = new PDO($dsn, $db_user, $db_word);
} catch (PDOException $exc) {
    trigger_error('NO PDO Connection', E_USER_ERROR);
}
// WARNING: AN UNCAUGHT CONNECT ERROR WILL BARK OUT THE DB CREDENTIALS!
// OPEN A CONNECTION TO THE DATA BASE SERVER AND SELECT THE DB
// SET PDO TO TELL US ABOUT WARNINGS OR TO THROW EXCEPTIONS
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

if(isset($_POST['email'])){
    var_dump($_POST['email']);
    die();
    $success = "";
$return = new stdClass;

$e = $_POST['email'];

$sql = "SELECT subscriber_id AS subscriber_id FROM pommo_subscribers WHERE email = :email";

$pdos = $pdo->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));

$pdos->bindParam(':email', $e, PDO::PARAM_STR);
var_dump($sql);
try {
    $pdos->execute();
    $rows = $pdos->fetch();
    $num = $pdos->rowCount();

    if ($num == 1) {

        foreach ($rows as $row) {
            $subscriber_id = $row['subscriber_id'];
            $status = '0';

            $q = "UPDATE pommo_subscribers SET status = :status WHERE subscriber_id = :subscriber_id";

            $pdos_b = $pdo->prepare($q, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));

            $pdos_b->bindParam(':status', $status, PDO::PARAM_STR);
            $pdos_b->bindParam(':subscriber_id', $subscriber_id, PDO::PARAM_STR);

            try {
                $pdos_b->execute();
                $num_b = $pdos_b->rowCount();
                if ($num_b == 1) {
                $return->success = '<h1>bye!</h1>' . error_get_last();
                }
            } catch (PDOException $exc) {
                var_dump($exc);
                trigger_error($exc->getMessage(), E_USER_ERROR);
            }
        }
    }
    return json_encode($return);
} catch (PDOException $exc) {
    var_dump($exc);
    trigger_error($exc->getMessage(), E_USER_ERROR);
}
}
?>

Open in new window

LVL 8
rgranlundAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Julian HansenCommented:
Let's take this one step at a time.

Does your PHP script work if you post to it directly?
<form action="/includes/unsubscribe.php" method="post">
  <input type="text" name="email" />
  <input type="submit" />
</form>

Open in new window


If that works as expected then
Are there any errors in your console (F12)?
In the console => Network if you examine the AJAX request
a) Is the email parameter present and correct
b) Are there any errors in the response.

Let's start there
0
rgranlundAuthor Commented:
@Julian,
It is working but I had to change two things.  I had fetch and it needed to be fetchAll.  I also had return json_encode($return); and I changed the to echo.

It removes the email as it should so that part is 100% ok.  However, it is not returning anything to the Console or returning as success.

<?php>
try {
    $pdos->execute();
    $rows = $pdos->fetchAll();
    $num = $pdos->rowCount();

    if ($num == 1) {

        foreach ($rows as $row) {
            $subscriber_id = $row["subscriber_id"];
            $status = '0';

            $q = "UPDATE pommo_subscribers SET status = :status WHERE subscriber_id = :subscriber_id";

            $pdos_b = $pdo->prepare($q, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));

            $pdos_b->bindParam(':status', $status, PDO::PARAM_STR);
            $pdos_b->bindParam(':subscriber_id', $subscriber_id, PDO::PARAM_STR);

            try {
                $pdos_b->execute();
                $num_b = $pdos_b->rowCount();
                if ($num_b == 1) {
                $return->success = '<h1>bye!</h1>' . error_get_last();

                }
            } catch (PDOException $exc) {
                var_dump($exc);
                trigger_error($exc->getMessage(), E_USER_ERROR);
            }
        }
    }
    echo json_encode($return);
} catch (PDOException $exc) {
    var_dump($exc);
    trigger_error($exc->getMessage(), E_USER_ERROR);
}
}

Open in new window


So Success : function (response) is not doing anything.
<script>
  <script>
                    $(document).ready(function () {
                        $(".frown").show('slow');
                        $("#unjoin").on('submit', function (e) {
                            e.preventDefault();

                            var div = $(".frown");
                            div.animate({margin: '0 0 0 41%', padding: '0'}, "slow");
                            $(".unsubscribe_right").hide('slow');
                            div.animate({width: '400px', opacity: '0.8'}, "slow");

                            $.ajax({
                                url: '/engine_room/includes/unsubscribe.php',
                                data: $("#unjoin").serialize(),
                                type: 'POST',
                                dataType: 'JSON',
                                success: function (response) {
                                    $("#unsubscribe_bye").html(response.success);
                                    console.log(response);
                                    $("#unjoin")[0].reset();
                                    $("#unsubscribe_bye").show('slow');
                                }
                            });
                        });
                    });
                </script>

Open in new window

0
Miguel OzSoftware EngineerCommented:
Code above fails because the unjoin event ($("#unjoin").on('submit', function (e)) is triggering a submit page, thus your JS code and page is no longer there to receive the ajax response.
Two solutions:
1) Convert your page to submit, no need to do ajax call.
2) Change event to click:
$("#unjoin").on('click', function (e))
Basically when your user clicks the link the ajax call will return and execute the success callback. Also it is a good idea to add the error function
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Why Diversity in Tech Matters

Kesha Williams, certified professional and software developer, explores the imbalance of diversity in the world of technology -- especially when it comes to hiring women. She showcases ways she's making a difference ithrough the Colors of STEM program.

Julian HansenCommented:
I don't understand the previous response
($("#unjoin").on('submit', function (e))

Open in new window

Does not trigger anything - it is an event handler handling a submit event on a form and is perfectly correct as it is.

@rgranlund
Your $return is only setting a value if the request is successful. It is a good idea to set defaults so you can see what is going on.

The first question - when you call the PHP page directly as described in my earlier email - what output are you getting?

Then, change your $return to this

$return = new stdClass;
$return->success = "failed";
// rest of code as normal

Open in new window


Also check your console to check what is happening with the request - look at the Network tab and click on the POST request to see parameters and return.

What do you see?
0
Miguel OzSoftware EngineerCommented:
Just to clarify my point the question is about why the ajax success response does not work and it does not work because we are doing a submit that removes the page context that ajax call response has nowhere to return.
No need to do extra troubleshooting but rgranlund has to decide which alternative (see my previous post ) suits his business needs better.
0
rgranlundAuthor Commented:
Oh Geez!  I had a var_dump at the top to see what was going on and that was stopping any response.
0
Julian HansenCommented:
it does not work because we are doing a submit that removes the page context that ajax call response has nowhere to return.
Where is the AJAX call returning anything? I am sorry but I don't see anything wrong with the AJAX call.

I had a var_dump at the top to see what was going on and that was stopping any response.
This will kill the JSON response but you will still be able to see it in the Console in the Response section of the POST.
0
rgranlundAuthor Commented:
Thanks for your help!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.