title: How to add AJAX to a working PHP form
body: <p>I have built a little application that validates the data submitted from a form on the server side and then displays a result depending on user input. It is all working perfectly but I would like to improve user experience and incorporate AJAX without modifying the existing PHP code (at least not too much). </p>
  
  <p>The basic logic of the application is that if the server request is GET it displays the form (see index-get.php), while if it is POST (i.e. the form has been submitted) then it validates the form. If there are errors it redisplays the form with error messages, otherwise it processes the form (index-post.php). </p>
  
  <p>I'm using jQuery's ajax() method (see the block with the header 'grade-calulator.js' to do this however it is not validating the input and just returns this line from 'index-post.php' :</p>
  
  <pre><code>echo '&lt;p id="response"&gt;You need to get ' . $neededMark . ' to get a final mark of ' . $targetGrade . '.&lt;/p&gt;&lt;br&gt;';
  </code></pre>
  
  <p><strong>index.php</strong></p>
  
  
  
  <pre><code>&lt;div class="container"&gt;
  
    &lt;div class="starter-template col-sm-6 col-sm-offset-3"&gt;
  
      &lt;?php 
  
      //Set up empty defaults when nothing is chosen
  
      $defaults = array(
  
      'currentGrade' =&gt; '',
      'targetGrade'=&gt; '',
      'finalWorth' =&gt; '');
  
      if ($_SERVER['REQUEST_METHOD'] == 'GET') { 
  
      $errors = array();
  
      include __DIR__ . '/index-get.php';
  
      } else {
  
      $errors = validate_form(); 
  
      if (count($errors)) {
  
      //if there were errors, redisplay form with the errors, preserving defaults. Otherwise process the form.
  
      if (isset($_POST['currentGrade'])) { $defaults['currentGrade'] = $_POST['currentGrade']; }
      if (isset($_POST['targetGrade'])) { $defaults['targetGrade'] = $_POST['targetGrade']; }
      if (isset($_POST['finalWorth'])) { $defaults['finalWorth'] = $_POST['finalWorth']; }
  
      include __DIR__ . '/index-get.php';
  
      } else {
  
          include __DIR__ . '/index-post.php';
      }
  
  }
  
      function validate_form() {
  
          //start out with no errors
  
          $errors = array();
  
          // currentGrade must be filled out and be a number.
  
           if (! filter_has_var(INPUT_POST, 'currentGrade') === false &amp;&amp; filter_input(INPUT_POST, 'currentGrade', FILTER_VALIDATE_INT) === false) {
  
              $errors['currentGrade'] = "You need to enter a number for current grade";
          }
  
          if ($_POST['currentGrade'] &lt; 0) {
  
              $errors['currentGrade'] = "Current grade must be greater than zero";
          } 
  
          // targetGrade must be filled out and be a number.
  
          if (! filter_has_var(INPUT_POST, 'targetGrade') === false &amp;&amp; filter_input(INPUT_POST, 'targetGrade', FILTER_VALIDATE_INT) === false) {
  
              $errors['targetGrade'] = "You need to enter a number for target grade";
          }
  
          // finalWorth must be filled out and be a number.
  
          if (! filter_has_var(INPUT_POST, 'finalWorth') === false &amp;&amp; filter_input(INPUT_POST, 'finalWorth', FILTER_VALIDATE_INT) === false) {
  
              $errors['finalWorth'] = "Your final exam worth needs to be a number.";
          }
  
          return $errors;
  
          }
  
  
   ?&gt; 
  
    &lt;/div&gt; 
  
  &lt;/div&gt;&lt;!-- /.container --&gt;
  </code></pre>
  
  
  
  <p><strong>index-get.php</strong></p>
  
  <pre><code>&lt;form action="&lt;?php echo htmlentities($_SERVER['SCRIPT_NAME']) ?&gt;" method="post" id="gradeForm"&gt;
              &lt;div class="form-group &lt;?php if (isset($errors['currentGrade'])) { echo 'has-error'; } ?&gt;"&gt;
                  &lt;label for="currentGrade"&gt;What is your current total grade?&lt;/label&gt;
                  &lt;input type="text" class="form-control" name="currentGrade" value="&lt;?php echo htmlentities($defaults['currentGrade'])?&gt;"&gt;
                  &lt;?php if (isset($errors['currentGrade'])) { ?&gt;
                      &lt;span class="help-block"&gt;&lt;?php echo htmlentities($errors['currentGrade'])?&gt;&lt;/span&gt;
                  &lt;?php } ?&gt;
              &lt;/div&gt;
              &lt;div class="form-group &lt;?php if (isset($errors['targetGrade'])) { echo 'has-error'; } ?&gt;"&gt;
                  &lt;label for="targetGrade"&gt;What is your target grade?&lt;/label&gt;
                  &lt;input type="text" class="form-control" name="targetGrade" value="&lt;?php echo htmlentities($defaults['targetGrade'])?&gt;"&gt;
                  &lt;?php if (isset($errors['targetGrade'])) { ?&gt;
                      &lt;span class="help-block"&gt;&lt;?php echo htmlentities($errors['targetGrade'])?&gt;&lt;/span&gt;
                  &lt;?php } ?&gt;
              &lt;/div&gt;
              &lt;div class="form-group &lt;?php if (isset($errors['finalWorth'])) { echo 'has-error'; } ?&gt;"&gt;
                  &lt;label for="finalWorth"&gt;What is your final exam worth?&lt;/label&gt;
                  &lt;input type="text" class="form-control" name="finalWorth" value="&lt;?php echo htmlentities($defaults['finalWorth'])?&gt;"&gt;
                  &lt;?php if (isset($errors['finalWorth'])) { ?&gt;
                      &lt;span class="help-block"&gt;&lt;?php echo htmlentities($errors['finalWorth'])?&gt;&lt;/span&gt;
                  &lt;?php } ?&gt;
              &lt;/div&gt;
              &lt;button type="submit" class="btn btn-primary"&gt;Submit&lt;/button&gt;
          &lt;/form&gt;
  </code></pre>
  
  <p><strong>index-post.php</strong></p>
  
  <pre><code>&lt;?php  
  
       $currentGrade = $_POST['currentGrade'];
       $targetGrade = $_POST['targetGrade'];
       $finalWorth = $_POST['finalWorth'];
  
       echo $currentGrade . " " . $targetGrade . " " . $finalWorth;
  
       if (isset($currentGrade, $targetGrade, $finalWorth)) {
  
          $possibleGradeSoFar = (100 - $finalWorth) / 100;
          $finalWorth = $finalWorth / 100;
          $b = $currentGrade * $possibleGradeSoFar;
          $c = $targetGrade - $b;
          $neededMark = $c / $finalWorth;
          $neededMark = round($neededMark);
  
          if ($neededMark &gt;= 50 &amp;&amp; $neededMark &lt;= 100) {
              echo '&lt;h1&gt;Better start studying...&lt;/h1&gt;';
              echo '&lt;img class="img-responsive" src="img/Mike.gif" alt="Mike"&gt;';
          } elseif ($neededMark &gt; 100) {
              echo '&lt;h1&gt;Just give up now.&lt;/h1&gt;';
              echo '&lt;img class="img-responsive" src="img/Gustavo-fring.gif" alt="Gustavo Fring"&gt;';
          } elseif ($neededMark &lt; 50) {
              echo '&lt;h1&gt;Time to party!&lt;/h1&gt;';
              echo '&lt;img class="img-responsive" src="img/Yeah-science.gif" alt="Yeah Science!"&gt;';
          }
  
      } 
  
      echo '&lt;p id="response"&gt;You need to get ' . $neededMark . ' to get a final mark of ' . $targetGrade . '.&lt;/p&gt;&lt;br&gt;';
  </code></pre>
  
  <p><strong>grade-calculator.js</strong></p>
  
  <pre><code>//ajax for the form
  $('form').submit(function(evt) {
      evt.preventDefault();
      var url = $(this).attr("action");
      var formData = $(this).serialize();
      console.log(formData);
      $.ajax(url, {
          data: formData,
          type: "POST",
          success: function(response) {
              $('#gradeForm').load('index-post.php');
          }
      });
  
  }); 
  </code></pre>