methuselah
methuselah

Reputation: 13206

AJAX post not working, data does not seem to be passing through

My AJAX post form doesn't seem to be working. It seems as if no data is being passed through. Any idea why?

Form

<label for="title">Please give your idea a title</label>
<br />
<input type="text" id="title" name="title" />
</p>
<p>
    <label for="message">Please provide details of your idea</label>
    <br>
    <input type="text" id="message" name="message" />
</p>
<input type="button" id="sendmessage" value="Post"></input>

jQuery

  $.post("assets/post.php", {
      title: $("#title").val(),
      message: $("#message").val()
  }, function (data) {
      alert(data);
      $chat.prepend('<span class="idea"><strong style="color: #0081C5">' + $messageTitle.val() + '</strong>' + '&nbsp;-&nbsp;' + $messageBox.val() + '&nbsp;' + '<a class="delete" href="#">[Delete]</a>' + '</span>')
      $messageTitle.val('');
      $messageBox.val('');
      $('#post_confirm').show().html('<br><span class="confirm_msg">Message posted successfully</span>');
      $('#chat').height($(window).height() - $('.header').height() - $('.user').height());
      setTimeout(function () {
          $('#post_confirm').fadeOut('slow');
          $('#chat').height($chatHeight_user);
      }, 1000);
  });

post.php

<?php include("config.php"); 
$title = $_POST["title"];
$message = $_POST["message"];

$sql = "INSERT INTO idea (title,message) VALUES (:title,:message)";
$q = $pdo->prepare($sql);
$q->execute(array(':title'=>$title,':message'=>$message));
?>

I get the following error message:

enter image description here

Upvotes: 1

Views: 103

Answers (1)

Gerben
Gerben

Reputation: 111

You lack any trigger to start this post action.

$('#sendmessage').on('click', function(event)
{
  event.preventDefault();
  $.ajax(
    {
      url: "demo_test.txt",
      data: yourdatahere,
      success:function(result)
      {
        successevents here
      }
    });
});

It now listens to the ID of sendmessage for clicks. If its clicked it disables the default button behavior and processes your AJAX call instead.

Upvotes: 2

Related Questions