-1

I am working on PHP to display a modal when I click on a hyperlink. I have got a problem with post the ID in ajax, because it will not fetch the id from the hyperlink to post it in ajax so I don't know why.

I have tried this but it didnt work:

var id = $(this).attr('autoid');

$.ajax({
    type: 'POST',
    url: "sendtest.php",
    data: {autoid : id},

    success: function(resultData)
    {
        alert(resultData)
    }

here is the code:

<span style="font-size: 15px; color: #ccd5d9; float: left; margin-top: -1px"><a href="#contactModal" role="button" data-toggle="modal">Send a test</a> | <a name="autoid" id="autoid" href="/delete_id.php?id=<?php echo $autoid ?>"> Delete </a> | Copy to Draft | Settings</span>

<div id="contactModal" class="modal fade" style="margin-top: 12%;" tabindex="-1" role="dialog">
    <div class="modal-dialog">
        <!-- Modal content-->
        <div class="modal-content" style="height: 250px;">
            <div class="modal-header" style="margin-bottom: 10px;">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h3 class="modal-title">Send A Test Email</h3>
            </div>
            <div class="modal-body" style="height: 65%;">
               <form action="" method="post">
                    <label class="label-control" value="">Send test message to email address:</label>
                    <?php
                        $html = '<select name="emails" id="emails" value="" style="width: 400px; margin-top: 10px; margin-bottom: 18px; margin-left: 60px;">';
                        $values = array('unknown', $_SESSION["email"]);

                        foreach($values as $v)
                        {
                            $selected = '';
                            if($v == 'unknown')
                            {
                                $title = '';
                            }else{
                                $title = $v;
                            }

                            if($v == $_SESSION["from"])
                            {
                                $selected = "selected";
                            }
                            $html .= "<option $selected value='$v'>$title</option>";
                        }
                        $html .= "
                        </select><br>";
                        echo $html;
                    ?>

                    <button name="send_email" id="send_email" type="submit" class="btn btn-primary" style="margin-left: 36%;">Send Test</button>
                </form>
            </div>
        </div>
    </div>
</div>


<script type="text/javascript">

$('#send_email').click(function(){
    document.getElementById("send_email").innerHTML = "<span><i class=\'fa fa-spinner fa-spin\'></i> Sending...</span>";
    document.getElementById('send_email').disabled = true;
    var id = $(this).attr('autoid');
    alert( $(this).attr('autoid'));


    $.ajax({
        type: 'POST',
        url: "sendtest.php",
        data: {autoid : id},

        success: function(resultData)
        {
            alert(resultData)
            $('#contactModal').modal('hide');
            document.getElementById("send_email").innerHTML = "Send Test";
            document.getElementById('send_email').disabled = false;
        }
        });
    });
</script>

in sendtest.php:

<?php
// Initialize the session
session_start();

// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
    header("location: login.php");
    exit;

}
else if(isset($_POST))
{
    $param_username = $_SESSION['username'];
    $param_campaign = $_SESSION['campaign'];
    $id = $_POST['autocampaign'];
    echo "hello your id is...";
    echo $id;
} 
?>

I'm sorry if it have been posted very similar in the past, but this is a difficult situation I have been going through so I would like to get some help with this.

So what I am trying to do is when I click on a button to display on a modal and select a value, I click on a button again to get the ID autoid to post it via ajax and display the alert with the ID.

Can you please show me an example what is the correct way I could use to fetch the ID from the HTML tag called autoid so I can post it in ajax to display the ID in the alert?

Thank you.

EDIT: It didn't work when I try this:

<form action="" method="post">
    <span style="font-size: 15px; color: #ccd5d9; float: left; margin-top: -1px"><a name="autoid" id="autoid" href="#contactModal" role="button" data-toggle="modal">Send a test</a> | <a name="autoid" id="autoid" href="/delete_id.php?id=<?php echo $autoid ?>"> Delete </a> | Copy to Draft | Settings</span>
</form>

in sendtest.php:

<?php
// Initialize the session
session_start();

// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
    header("location: login.php");
    exit;

}
else if(isset($_POST))
{
    $param_username = $_SESSION['username'];
    $param_campaign = $_SESSION['campaign'];
    $id = $_POST['autoid'];
    echo "hello your id is...";
    echo $id;
}
?>

At all I get is hello your id is... in the alert.

UPDATE: Here is the full code:

<?php
// Initialize the session
session_start();

// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
    header("location: login.php");
    exit;
}
else
{
    $link = mysqli_connect('localhost', 'mydbusername', 'mydbpassword', 'mydbname');
    $param_username = $_SESSION['username'];
    $autocampaign = $_SESSION["campaign"];
    $auto_sql = "SELECT id, subject, day_cycle, enabled, delaysend FROM autore WHERE campaign ='$autocampaign' AND username ='$param_username'";

        $results = mysqli_query($link, $auto_sql);

         if (mysqli_num_rows($results) > 0) 
         { 
            while ($row = mysqli_fetch_array($results))
            {
                $autoid = $row["id"];
                $autosubject = $row["subject"];
                $autodaycycle = $row["day_cycle"];
                $autoenabled = $row["enabled"];
                $autodelay = $row["delaysend"];
            }
         }
?>

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>





<style type="text/css">


.calendar-content {
    float: left;
    width: 100%;
    min-height: 112px;
    border: 1px solid #ccc;
    position: relative;
    margin-top: -1px;
}


</style>

<div class="calendar-content">
  <div style="margin-left: 40px;margin-top: 20px; height: 40px;">
    <span id="autosubject" style="font-size: 25px;color: #0c7ac0;float: left;">Subject: <?php echo $autosubject ?> </span><br>
    <div style="margin-left: 35px; margin-top: 15px; height: 40px;">
      <form action="" method="post">
        <span style="font-size: 15px; color: #ccd5d9; float: left; margin-top: -1px"><a name="autoid" id="autoid" href="#contactModal" role="button" data-toggle="modal">Send a test</a> | <a name="deleteid" id="deleteid" href="/delete_id.php?id=<?php echo $autoid; ?>"> Delete </a> | Copy to Draft | Settings</span>
      </form>
    </div>
  </div><br>

  <!-- email Modal -->
  <div id="contactModal" class="modal fade" style="margin-top: 12%;" tabindex="-1" role="dialog">
    <div class="modal-dialog">
      <!-- Modal content-->
      <div class="modal-content" style="height: 250px;">
        <div class="modal-header" style="margin-bottom: 10px;">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h3 class="modal-title">Send A Test Email</h3>
        </div>
        <div class="modal-body" style="height: 65%;">
          <form action="" method="post">
            <label class="label-control" value="">Send test message to email address:</label>
            <select name="emails" id="emails" value="" style="width: 400px; margin-top: 10px; margin-bottom: 18px; margin-left: 60px;">
              <option selected="selected" value='title'>Title</option>";
            </select><br>
            <button name="send_email" id="send_email" type="submit" class="btn btn-primary" style="margin-left: 36%;" data-auto-id="<?php echo $autoid; ?>">Send Test</button>
          </form>
        </div>
      </div>
    </div>
  </div>
<?php
}
?>

<script type="text/javascript">
  $(function() {
  $('#send_email').click(function(e) {
    $(this)
      .html("<span><i class='fa fa-spinner fa-spin'></i> Sending...</span>")
      .prop("disabled", true);
    var id = $(this).data('deleteid');

    $.ajax({
      type: 'POST',
      url: "sendtest.php",
      data: {
        deleteid: id
      },
      success: function(resultData) {
        alert(resultData)
        $('#contactModal').modal('hide');
        $("#send_email")
          .html("Send Test")
          .prop("disabled", false);
      }
    });
  });
});
</script>
</body>
</html>
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Robert Jones
  • 390
  • 3
  • 18
  • If you're sending the `id` via `autoid` in the Post data, then in PHP you need to call it using that index: `$_POST['autoid']`. You're calling: `$id = $_POST['autocampaign'];` and that's not going to work. – Twisty Dec 21 '18 at 23:20
  • @Twisty Thank you, so do I need to use `$_POST['autoid']` in ajax or in sendtest.php? – Robert Jones Dec 21 '18 at 23:22
  • You will want to use `$_POST['autoid']` in `sendtest.php` when you want to access that Posted data. – Twisty Dec 21 '18 at 23:25
  • 1
    The other problem is that your send email button doesn't have an attribute called autoid. – ADyson Dec 21 '18 at 23:31
  • @RobertJones `var id = $(this).attr('autoid');` will fail since `$(this)` is a refernce to the Button Object and not the form. The ` – Twisty Dec 21 '18 at 23:41
  • @Twisty oh right, so do I need to change from `send_email` to `autoid` in the button? I want to fetch the id from the hyperlink. – Robert Jones Dec 21 '18 at 23:44
  • `?id` is a GET request, not POST. Plus, what's the value of `$autoid`? and where and how is it set? – Funk Forty Niner Dec 22 '18 at 00:02
  • @RobertJones it's possible your SQL Query is returning more than 1 result or no result for `id`. What do you see in the resulting HTML for the Delete link? `?id=` what? – Twisty Dec 22 '18 at 01:14
  • I see a few errors in your (full) code. I'd start by enabling error reporting and error handling on the mysql part too. I posted [a comment](https://stackoverflow.com/questions/53891733/post-the-id-in-ajax#comment94630816_53891733) earlier but didn't get a response. I only saw the edit because I still had this tabbed question open in my browser, which I might add won't be keeping it open after I posted this comment. So, debug your code with all methods, this including looking at your developer console; good luck. Btw, I added a few tags which I found to be relevant. – Funk Forty Niner Dec 22 '18 at 01:14
  • 1
    2 more debugging tools: [`var_dump()`](http://php.net/manual/en/function.var-dump.php) and viewing your HTML source. Yes, the latter is also a (debugging) "tool". Btw, (Lord as my witness) can't say I didn't (try to) help. Debugging isn't our job, it's yours; so please remember that and it is an essential part of being a (learning) coder. Once you've figured that out, you'll see how relatively easy it will be for you to fix your own code later on. I only came back here because @Twisty replied to my comment under their answer, I'd of liked to have received the same courtesy from you Robert. – Funk Forty Niner Dec 22 '18 at 02:46

1 Answers1

2

In your sendtest.php you will want to change:

$id = $_POST['autocampaign'];

To the following:

$id = $_POST['autoid'];

Hope that helps.

Updated

var id = $(this).attr('autoid'); will fail since $(this) is a refernce to the Button Object and not the form. The <button> also does not have an attribute called autoid. Therefore, id will be null or undefined.

Where should id get it's value from?

$(function() {
  $('#send_email').click(function(e) {
    $(this)
      .html("<span><i class='fa fa-spinner fa-spin'></i> Sending...</span>")
      .prop("disabled", true);
    var id = $(this).data('auto-id');

    $.ajax({
      type: 'POST',
      url: "sendtest.php",
      data: {
        autoid: id
      },
      success: function(resultData) {
        alert(resultData)
        $('#contactModal').modal('hide');
        $("#send_email")
          .html("Send Test")
          .prop("disabled", false);
      }
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="calendar-content">
  <div style="margin-left: 40px;margin-top: 20px; height: 40px;">
    <span id="autosubject" style="font-size: 25px;color: #0c7ac0;float: left;">Subject: <?php echo $autosubject ?> </span><br>
    <div style="margin-left: 35px; margin-top: 15px; height: 40px;">
      <form action="" method="post">
        <span style="font-size: 15px; color: #ccd5d9; float: left; margin-top: -1px"><a name="autoid" id="autoid" href="#contactModal" role="button" data-toggle="modal">Send a test</a> | <a name="autoid" id="autoid" href="/autoresponder/delete_autoresponder.php?id=<?php echo $autoid; ?>"> Delete </a> | Copy to Draft | Settings</span>
      </form>
    </div>
  </div><br>

  <!-- email Modal -->
  <div id="contactModal" class="modal fade" style="margin-top: 12%;" tabindex="-1" role="dialog">
    <div class="modal-dialog">
      <!-- Modal content-->
      <div class="modal-content" style="height: 250px;">
        <div class="modal-header" style="margin-bottom: 10px;">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h3 class="modal-title">Send A Test Email</h3>
        </div>
        <div class="modal-body" style="height: 65%;">
          <form action="" method="post">
            <label class="label-control" value="">Send test message to email address:</label>
            <select name="emails" id="emails" value="" style="width: 400px; margin-top: 10px; margin-bottom: 18px; margin-left: 60px;">
              <option selected="selected" value='title'>Title</option>";
            </select><br>
            <button name="send_email" id="send_email" type="submit" class="btn btn-primary" style="margin-left: 36%;" data-auto-id="<?php echo $autoid; ?>">Send Test</button>
          </form>
        </div>
      </div>
    </div>
  </div>

The following code is cleaned up. First, I added the data-auto-id attribute that contains the autoid from PHP. This can then be read and passed into the AJAX.

Also switched into all jQuery for consistency.

Twisty
  • 30,304
  • 2
  • 26
  • 45
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/185637/discussion-on-answer-by-twisty-post-the-id-in-ajax). – Samuel Liew Dec 22 '18 at 04:33