2014-07-22 4 views
0

Je n'arrive pas à récupérer les données JSON d'un fichier PHP à l'aide de la méthode $ .post() de jQuery.

Je peux voir qu'une requête POST XHR a été enregistrée dans la console mais le message de réponse n'apparaît pas.

Quelqu'un pourrait-il expliquer pourquoi cela se produit?

forme

<form action="<?php echo htmlentities($_SERVER['SCRIPT_NAME']); ?>" method="post" id="gradeForm"> 
    <div class="form-group" id="currentGradeGroup"> 
     <label for="currentGrade">What is your current total grade?</label> 
     <input type="text" class="form-control" name="currentGrade"> 
     <span class="help-block" id="currentGrade"></span> 
    </div> 
    <div class="form-group" id="targetGradeGroup"> 
     <label for="targetGrade">What is your target grade?</label> 
     <input type="text" class="form-control" name="targetGrade"> 
     <span class="help-block" id="targetGrade"></span> 
    </div> 
    <div class="form-group" id="finalWorthGroup"> 
     <label for="finalWorth">What is your final exam worth?</label> 
     <input type="text" class="form-control" name="finalWorth"> 
     <span class="help-block" id="finalWorth"></span> 
    </div> 
    <button type="submit" class="btn btn-primary">Submit</button> 
</form> 
<div id="ajax"></div> 


**Server side code** 

<?php 


     $response = validate_form(); 

     if (!empty($response)) { 

      echo '<pre>'; 
      var_dump($response); 
      echo '</pre>'; 
      exit(json_encode($response)); 

     } else { 

      $response = success(); 

      echo '<pre>'; 
      var_dump($response); 
      echo '</pre>'; 
      exit(json_encode($response)); 

     } 

     // validate form input 

     function validate_form() { 

      $response = array(); 

      // currentGrade must be filled out and be a number. 

      if (! (filter_has_var(INPUT_POST, 'currentGrade') && (filter_input(INPUT_POST, 'currentGrade', FILTER_VALIDATE_INT)))) { 

       $currentGrade = array(); 
       $currentGrade['msg'] = "You need to enter a number for current grade"; 
       $response[] = $currentGrade; 
      } 

      // currentGrade must be 0 or greater 

      if ($_POST['currentGrade'] < 0) { 

       $currentGrade = array(); 
       $currentGrade['msg'] = "Current grade must be greater than or equal to zero"; 
       $response[] = $currentGrade; 

      } 

      // targetGrade must be filled out and be a number. 

      if (! (filter_has_var(INPUT_POST, 'targetGrade') && (filter_input(INPUT_POST, 'targetGrade', FILTER_VALIDATE_INT)))) { 

       $targetGrade = array(); 
       $targetGrade['msg'] = "You need to enter a number for target grade"; 
       $response[] = $targetGrade; 
      } 

      // finalWorth must be filled out and be a number. 

      if (! (filter_has_var(INPUT_POST, 'finalWorth') && (filter_input(INPUT_POST, 'finalWorth', FILTER_VALIDATE_INT)))) { 

       $finalWorth = array(); 
       $finalWorth['msg'] = "Your final exam worth needs to be a number."; 
       $response[] = $finalWorth; 
      } 

      $response['success'] = false; 
      return $response; 

     } 

     function success() { 

       $response = array(); 

       $currentGrade = $_POST['currentGrade']; 
       $targetGrade = $_POST['targetGrade']; 
       $finalWorth = $_POST['finalWorth']; 

       $possibleGradeSoFar = (100 - $finalWorth)/100; 
       $finalWorth = $finalWorth/100; 
       $b = $currentGrade * $possibleGradeSoFar; 
       $c = $targetGrade - $b; 
       $neededMark = $c/$finalWorth; 
       $neededMark = round($neededMark); 

       $response['msg'] = '<p id="response">You need to get ' . $neededMark . ' to get a final mark of ' . $targetGrade . '.</p><br>'; 

       if ($neededMark >= 50 && $neededMark <= 100) { 
        $response['header'] = '<h1>Better start studying...</h1><img class="img-responsive" src="img/Mike.gif" alt="Mike">'; 
       } elseif ($neededMark > 100) { 
        $response['header'] = '<h1>Just give up now.</h1><img class="img-responsive" src="img/Gustavo-fring.gif" alt="Gustavo Fring">'; 
       } elseif ($neededMark < 50) { 
        $response['header'] = '<h1>Time to party!</h1><img class="img-responsive" src="img/Yeah-science.gif" alt="Yeah Science!">'; 
       } 

       $response['success'] = true; 
       return $response; 

     } 

délivré en sortie à partir d'un JSON json_encode() dans un fichier séparé PHP

{ 
    "0": { 
     "msg": "You need to enter a number for current grade" 
    }, 
    "1": { 
     "msg": "You need to enter a number for target grade" 
    }, 
    "2": { 
     "msg": "Your final exam worth needs to be a number." 
    }, 
    "success": false 
} 

jQuery

jQuery(document).ready(function($) { 
    $('#gradeForm').submit(function(e) { 
     // stop form from submitting normally. 
     e.preventDefault(); 

     // get some values from the form. 
     var $form = $(this); 
     var url = $form.attr('action'); 
     var postData = $form.serialize(); 

     // use the jQuery post method to send the data. 
     var posting = $.post(url, postData, 'json'); 

     // If the request is successful append the response to the #ajax div. 
     posting.done(function(response) { 
      // output the appropriate message in the ajax div 
      $('#ajax').html(response[0].msg); 
     }) // end done(); 
     // otherwise log the HTTP request status to the console. 
     .fail(function(jqXHR) { 
      console.log(jqXHR.status); 
      console.log(jqXHR.statusText); 
     }); // end fail(); 
    }); // end submit(); 
}); // end ready(); 
+0

si le succès/échec des gestionnaires sont obtenir appelé –

+0

S'il vous plaît poster votre code de gestion côté serveur .. car il me semble que le format de réponse serait be response.0.msg –

+0

@KyleEmmanuel Je l'ai ajouté. – chap

Répondre

1

La réponse est:

{ 
    "0": { 
     "msg": "You need to enter a number for current grade" 
    }, 
    "1": { 
     "msg": "You need to enter a number for target grade" 
    }, 
    "2": { 
     "msg": "Your final exam worth needs to be a number." 
    }, 
    "success": false 
} 

Essayez response.0.msg ou plutôt ceci:

$.post(url, postData,function(data) 
{ 
    alert(data.0.msg); 
}, 
'json'); 

Ou vous pouvez modifier votre réponse à être:

$response = (array("results" => $result_array_with_msg, "success" => $success)); 
0

Si elle est objet JSON liez pas alors:

$('#ajax').html(response[0]); 

FIDDLE EXAMPLE

Questions connexes