Raylene
Raylene

Reputation: 296

Needing to submit form twice to post correctly using jQuery AJAX

I'm trying to submit a form using jQuery AJAX. I'm not so great with this code, so am not able to see

Issue - why I need to submit the form twice in order for it to post.

When I submit the form the textarea clear back to placeholder text and nothing happens. When I click it again, the post submits and displays. I have the following textarea and button

<textarea class="add-message-textarea" name="message_body" id="message_textarea" placeholder="Write message"></textarea>
<button class="post-button button" type="submit" name="post_message" id="message_submit">Post</button>

When I submit I have the following:

$body = '';
if(isset($_POST['post_message'])) {

    if(isset($_POST['message_body'])) {
        $body = $_POST['message_body'];
    }
}

Then AJAX call:

var userLoggedIn = '<?php echo $userLoggedIn; ?>';
var user_to      = '<?php echo $user_to; ?>';
var body         = '<?php echo $body; ?>'
// var body          = $("#message_textarea").val();

$(document).ready(function() {

    $("#message_submit").click(function(){

    //ajax request for send 'sending a new message' string to dB
    $.ajax({
        url: "includes/handlers/ajax_send_message.php",
        type: "POST",
        data: {'userLoggedIn':userLoggedIn, 'user_to':user_to, 'body':body},
        cache: true,

                success: function(response) {
                  console.log("message_sent");
                }

        }); 
    });
});

ajax_send_message.php looks like this simple:

global $con;
if(isset($_POST['userLoggedIn']) && isset($_POST['user_to']) && isset($_POST['body'])) {

    $userLoggedIn = $_POST['userLoggedIn'];
    $body = $_POST['body'];
    $user_to = $_POST['user_to'];
    $date = date("Y-m-d H:i:s");


        $message_obj = new Message($con, $userLoggedIn);
        $message_obj->sendMessage($user_to, $body, $date);
}

I'm able to get this to work no problem using PHP with the below but I don't want the page to reload.

if(isset($_POST['post_message'])) {

    if(isset($_POST['message_body'])) {
        $body = $_POST['message_body'];
        $date = date("Y-m-d H:i:s");
        $message_obj->sendMessage($user_to, $body, $date);
    }
}

Any help is appreciated.

Upvotes: 2

Views: 59

Answers (2)

Ali Sheikhpour
Ali Sheikhpour

Reputation: 11045

If you want to submit a form but prevent reloading the page, you just need to return false from clicking submit button:

$(document).ready(function() {

    $("#message_submit").click(function(){
   //ajax request for send 'sending a new message' string to dB
    $.ajax({
    url: "includes/handlers/ajax_send_message.php",
    type: "POST",
    data: {'userLoggedIn':userLoggedIn, 'user_to':user_to, 'body':body},
    cache: true,
    success: function(response) {
          console.log("message_sent");
         }

    });

    return false;

    });
});

Note: If you want to totally prevent a form to be submitted, attach the event listener to the form submission not on clicking the button. User may submit the form by pressing Enter or other unpredictable actions attached to the device keybord etc.

$(YOUR_FORM).on("submit",function(){
  //Ajax code here
  return false;
})

Upvotes: 2

user7847084
user7847084

Reputation:

I think the problem is that you don't prevent your form from submitting. You can do this by: e.preventDefault() in .submit(function(e){}) callback function

$("#reg").submit(function(e)
{
  e.preventDefault();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="reg">
  <input type="text" name="name" value="Rick">
  <input type="text" name="last_name" value="Astley">
  <input type="submit">
<form>

Upvotes: 1

Related Questions