PHP错误警报,不重定向但保持在同一页面上

I am trying to do some form validation before the form submits to the database. I would like the error message to display if all the fields don't have values but currently, when submitting, the form redirects to the same page and wipes everything from the form. Heres my code..

$error = '';
if (isset($_SESSION['logged_in'])) {
    if (isset($_POST['submit'])) {
        if (isset($_POST['title'], $_POST['content'], $_POST['short_desc'], $_POST['file'])) {
            $title = $_POST['title'];
            $content = $_POST['content'];
            $short_desc = $_POST['short_desc'];

            $targetDir = "../images/blog-images/";
        $fileName = basename($_FILES["file"]["name"]);
        $targetFilePath = $targetDir . $fileName;
        $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);

        $allowTypes = array('jpg','png','jpeg','gif','pdf');
            if(in_array($fileType, $allowTypes)){
                move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath);
            }

        //if (empty($title) or empty($content)) {
        //  $error = 'All fields are required!';
        //  echo "<script type='text/javascript'>alert('$error');</script>";
        //} else {
            $query = $pdo->prepare('INSERT INTO articles (article_title, article_content, article_timestamp, article_short_desc, article_image) VALUES (?,?,?,?,?)');

            $query->bindValue(1, $title);
            $query->bindValue(2, $content);
            $query->bindValue(3, time());
            $query->bindValue(4, $short_desc);
            $query->bindValue(5, $fileName);

            $query->execute();
            header('Location: add-new-post.php');
        }else {

        $error = 'All fields are required!';
        echo "<script type='text/javascript'>alert('$error');</script>";
    }

    } 

Is there a way to do this without AJAX as I am not too familiar with it..

Thanks in advance!

Since your PHP script is on the same page as the HTML form it seems, you can do something like:

<input type="text" name="someField" value="<?php echo isset($_POST['someField']) 
? $_POST['someField'] : '' ?>" required />

The required flag at the end will prevent the form to be submitted on the front end part if its unfilled. The value field will re-fill the input with the last variable that was passed through POST.

In your case you could use one or the other.