2

Iam Working on a project using OO php and i want to display success message when submit is clicked I've searched all on the web but the solutions am getting are not working for me!!

I tried using both jquery and ajax but i keep on getting the same error

Here is my html

<form method="post" id="postForm" class="form-horizontal" action = "index.php">
  <div class="form-group">
    <label for="Title" class="control-label col-sm-3">Title</label>
    <div class="col-sm-9">
       <input type="text" class="form-control" name="title" id="title" placeholder="Enter Title of your Post"/>
    </div>
  </div>
  <div class="form-group">
    <label for="Title" class="control-label col-sm-3">Body</label>
    <div class="col-sm-9">
      <Textarea type="text" class="form-control" name="body" id="body" placeholder="Enter Body of your Post"></textarea>
    </div>
  </div>

  <button type="submit" class="btn btn-default" name="submit">submit</button><br/>
  <div class="text-center">
    <span id="success" class="text-success"></span>
    <span id="wanings" class="text-danger"></span>
   </div>
</form>

This is my jquery script file inserted into the same page index.php

<script>
        $(document).ready(function(){
            $('#postForm').submit(function(event){
                event.preventDefault();

            var $form = $(this),
            var title = $('#title').val();
            var body = $('#body').val();
            var url = $form.attr('action');
            var method = $form.attr('method');

                if(title == '' || body == ''){
                    $('#warnings').html('All Fields are Required');
                }else{
                    $('#warnings').html('');
                    $.ajax({
                        url: url,
                        method:method,
                        data:{title: title, body:body},
                        success:function(data){
                            $('#postForm').trigger('reset');
                            $('#success').fadeIn().html(data);
                            setTimeout(function function_name() {
                                $('#success').fadeOut('slow');
                            }, 3000);

                        }
                    });

                }

            });
        });
    </script>

And the Php is just above the Html also in the same page. Its supposed to get the post title and insert it into the database but echo the message that data has been successfully added if submit is clicked.

Here is the Snippet

<?php
        require 'classes/Database.php';

        $database = new Database;
        $post = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);

        if($post['submit']){
            $title = $post['title'];
            $body = $post['body'];

            $database->query('INSERT INTO posts (title, body) VALUES(:title, :body)');
            $database->bind(':title', $title);
            $database->bind(':body', $body);
            $database->execute();
            if($database->lastInsertId()){
               echo "<h1>Post added Successfully To the Database</h1>";         
            }
        }

    ?>

When i run the page in the browser, it displays the whole html in the div.

Reproduced html for the form

instead of a message set and then it throws the following error in the console.

Error Message in chrome console

Could any of you be knowing why it can't show the message? thanks

6
  • 2
    It is not a error, it is a warning. Seems that your jQuery is configured to make all Ajax request synchronously and this is deprecated. Commented Sep 13, 2018 at 11:51
  • changge input button type to button Commented Sep 13, 2018 at 11:51
  • 1
    tip: send json and respond with json not html, do the checks and rendering of the success/error in the javascript. Commented Sep 13, 2018 at 11:54
  • @Rp9 - Since there's a event.preventDefault(), that won't matter. Commented Sep 13, 2018 at 11:55
  • Your database class return its connection success message, check for this $_POST['submit'] not this if($post['submit']) Commented Sep 13, 2018 at 12:25

2 Answers 2

2

As you notice by the image, all the text is green, this is because you are rendering the response within that text-success span. Not ideal.

Instead of responding with HTML respond with JSON, and do your checks within the javascript to determine whether it was successful or a warning.

Some other issues:

  • You're not sending up submit so it will always skip passed the if statement.

So try something like:

$(document).ready(function() {
  $('#postForm').submit(function(event) {
    event.preventDefault();

    var $form = $(this);
    var title = $('#title').val();
    var body = $('#body').val();
    var url = $form.attr('action');
    var method = $form.attr('method');

    if (title == '' || body == '') {
      $('#warnings').html('All Fields are Required');
      if (title == '') {
        $('#title').closest('.form-group').find('.help-block').html('Title is a required field')
      }
      if (body == '') {
        $('#body').closest('.form-group').find('.help-block').html('Body is a required field')
      }
    } else {
      $('#warnings').html('');
      $form.find('.help-block').html('')

      $.ajax({
        url: url,
        method: method,
        data: {
          title: title,
          body: body
        },
        success: function(response) {
          // got errors from server
          if (response.status === 'error') {
            if (response.errors.title) {
              $('#title').closest('.form-group').find('.help-block').html(response.errors.title)
            }
            if (response.errors.body) {
              $('#body').closest('.form-group').find('.help-block').html(response.errors.body)
            }
            if (response.errors.global) {
              $('#warnings').html(response.errors.global)
            }
          }
          // all good, assign message to success
          else {
            $('#success').fadeIn().html(response.msg);
            setTimeout(function() {
              $('#success').fadeOut('slow');
            }, 3000);
            $('#postForm').trigger('reset');
          }
        }
      });
    }
  });
});
<form method="post" id="postForm" class="form-horizontal" action="index.php">
  <div class="form-group">
    <label for="title" class="control-label col-sm-3">Title</label>
    <div class="col-sm-9">
      <input type="text" class="form-control" name="title" id="title" placeholder="Enter Title of your Post" />
    </div>
    <span class="help-block"></span>
  </div>
  <div class="form-group">
    <label for="body" class="control-label col-sm-3">Body</label>
    <div class="col-sm-9">
      <textarea type="text" class="form-control" name="body" id="body" placeholder="Enter Body of your Post"></textarea>
    </div>
    <span class="help-block"></span>
  </div>

  <button type="submit" class="btn btn-default">submit</button><br/>
  <div class="text-center">
    <span id="success" class="text-success"></span>
    <span id="warnings" class="text-danger"></span>
  </div>
</form>

PHP code, basically validate and return as JSON.

<?php
require 'classes/Database.php';

$database = new Database;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $post = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);

    $response = [];
    $errors = [];

    // validate inputs
    if (empty($post['title'])) {
        $errors['title'] = 'Title is a required field';
    }
    if (empty($post['body'])) {
        $errors['body'] = 'Body is a required field';
    }

    // errors is empty so its all good
    if (empty($errors)) {
        //
        $database->query('INSERT INTO posts (title, body) VALUES(:title, :body)');
        $database->bind(':title', $post['title']);
        $database->bind(':body', $post['body']);
        $database->execute();

        if ($database->lastInsertId()) {
            $response = [
                'status' => 'success',
                'msg' => 'Post added successfully added'
            ];
        } else {
            $response = [
                'status' => 'error',
                'errors' => [
                    'global' => 'Failed to insert post, contact support'
                ]
            ];
        }
    } else {
        $response = [
            'status' => 'error',
            'errors' => $errors
        ];
    }

    exit(json_encode($response));
}

// guessing after this is your rendering of that form
Sign up to request clarification or add additional context in comments.

Comments

0

You need to check if($_POST) instead of if($post['submit']) because in your case its not going into if condition and echo out your result. Also after echo add "exit" statement so that form will not be printed in division.

1 Comment

this fixes the re-rendering of the html but still the "post Added Successfully" doesnt show up. The errors are showing fine but when submit is there is no errors, The "Post Added Successfully doesn't work" @LawrenceCherone

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.