Javascript 如何将AJAX添加到工作的PHP表单中

Javascript 如何将AJAX添加到工作的PHP表单中,javascript,php,jquery,ajax,forms,Javascript,Php,Jquery,Ajax,Forms,我构建了一个小应用程序,它在服务器端验证表单提交的数据,然后根据用户输入显示结果。这一切都很完美,但我希望在不修改现有PHP代码(至少不太多)的情况下改善用户体验并合并AJAX 应用程序的基本逻辑是,如果服务器请求是GET,那么它将显示表单(请参见index GET.php),而如果是POST(即表单已提交),那么它将验证表单。如果有错误,它将重新显示带有错误消息的表单,否则它将处理表单(index post.php) 我使用jQuery的ajax()方法(请参见标题为“grade calula

我构建了一个小应用程序,它在服务器端验证表单提交的数据,然后根据用户输入显示结果。这一切都很完美,但我希望在不修改现有PHP代码(至少不太多)的情况下改善用户体验并合并AJAX

应用程序的基本逻辑是,如果服务器请求是GET,那么它将显示表单(请参见index GET.php),而如果是POST(即表单已提交),那么它将验证表单。如果有错误,它将重新显示带有错误消息的表单,否则它将处理表单(index post.php)

我使用jQuery的ajax()方法(请参见标题为“grade calulator.js”的块)来执行此操作,但是它没有验证输入,只是从“index post.php”返回这一行:

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

我不会尝试重新写你所拥有的,但我会给你一个想法,如何做你想要的

index.php//这是您的表单和其他html所在的位置:)


jQuery(文档).ready(函数($){
$(“#我的表格”)。关于('submit',函数(e){
e、 preventDefault();//这将阻止表单刷新页面(发布到自身)
//我们将使用$.post方法。。。
变量形式=$(此);
var postData=form.serialize();
$.post($)http://website.com/handler.php,postData,函数(resp){
如果(分别成功){
//一切按预期进行!删除表单并显示消息。。
form.remove();
$('#msgs').html(resp.msg);
}否则{
//我们遇到一个错误…请留下表单,显示消息
//在这里,您可以将错误类添加到消息框等。。
$('#msgs').html(resp.msg);
}
},'json');//我们希望handler.php提供json响应
});
});
handler.php//这就是处理ajax提交的人

<?php
//make sure to secure this better, a common way is to make sure it was submitted using an http request...
if(isset($_POST['hello_ajax'])){
  if($_POST['hello_ajax'] == ''){
    //this is required so we'll return an error..in JSON..
    $resp['success'] = false;
    $resp['msg'] = 'Hello Ajax is required!';
    //we output, NOT return the response..
    exit(json_encode($resp));
  }else{
    //looks good save it or whatever...
    /** Saving/Calculating code here... **/
    //output a positive response
    $resp['success'] = true;
    $resp['msg'] = 'Hello Ajax was saved!!';
    exit(json_encode($resp));
    //that's it...
  }
}
?>


这会让你找到正确的方向!!干杯

为什么ppl在没有解释的情况下进行向下投票?所以你正在读取数据库中的内容,将其移动到用户,让用户“更新”它,然后存储最终值……对吗?@TimSPQR不,它没有被发送到数据库。表单数据在index-post.php中处理。实际上,此应用程序没有数据库。
<form action="<?php echo htmlentities($_SERVER['SCRIPT_NAME']) ?>" method="post" id="gradeForm">
            <div class="form-group <?php if (isset($errors['currentGrade'])) { echo 'has-error'; } ?>">
                <label for="currentGrade">What is your current total grade?</label>
                <input type="text" class="form-control" name="currentGrade" value="<?php echo htmlentities($defaults['currentGrade'])?>">
                <?php if (isset($errors['currentGrade'])) { ?>
                    <span class="help-block"><?php echo htmlentities($errors['currentGrade'])?></span>
                <?php } ?>
            </div>
            <div class="form-group <?php if (isset($errors['targetGrade'])) { echo 'has-error'; } ?>">
                <label for="targetGrade">What is your target grade?</label>
                <input type="text" class="form-control" name="targetGrade" value="<?php echo htmlentities($defaults['targetGrade'])?>">
                <?php if (isset($errors['targetGrade'])) { ?>
                    <span class="help-block"><?php echo htmlentities($errors['targetGrade'])?></span>
                <?php } ?>
            </div>
            <div class="form-group <?php if (isset($errors['finalWorth'])) { echo 'has-error'; } ?>">
                <label for="finalWorth">What is your final exam worth?</label>
                <input type="text" class="form-control" name="finalWorth" value="<?php echo htmlentities($defaults['finalWorth'])?>">
                <?php if (isset($errors['finalWorth'])) { ?>
                    <span class="help-block"><?php echo htmlentities($errors['finalWorth'])?></span>
                <?php } ?>
            </div>
            <button type="submit" class="btn btn-primary">Submit</button>
        </form>
<?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 >= 50 && $neededMark <= 100) {
            echo '<h1>Better start studying...</h1>';
            echo '<img class="img-responsive" src="img/Mike.gif" alt="Mike">';
        } elseif ($neededMark > 100) {
            echo '<h1>Just give up now.</h1>';
            echo '<img class="img-responsive" src="img/Gustavo-fring.gif" alt="Gustavo Fring">';
        } elseif ($neededMark < 50) {
            echo '<h1>Time to party!</h1>';
            echo '<img class="img-responsive" src="img/Yeah-science.gif" alt="Yeah Science!">';
        }

    } 

    echo '<p id="response">You need to get ' . $neededMark . ' to get a final mark of ' . $targetGrade . '.</p><br>';
//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');
        }
    });

}); 
<div id="msgs"></div>
<!-- we don't need a value for action as the ajax function will define where the form data is being posted -->
<form id="my-form" action="" method="post">
  <input type="text" name="hello_ajax" />
  <input type="submit" value="Save" />
</form>
<!-- make sure jQuery is included in the header or somewhere before this!! -->
<script type="text/javascript">
  jQuery(document).ready(function($){
    $('#my-form').on('submit',function(e){
      e.preventDefault(); // this will prevent the form from refreshing the page (POSTing to itself)
      //we'll use the $.post method...
      var form = $(this);
      var postData = form.serialize();
      $.post('http://website.com/handler.php',postData,function(resp){
        if(resp.success){
          //everything went as expected! remove the form and display the message..
          form.remove();
          $('#msgs').html(resp.msg);
        }else{
          //we encountered an error...leave the form, display the message
          //here you could add an error class to the message box etc..
          $('#msgs').html(resp.msg);
        }
      },'json'); //we expect a json response from handler.php
    });
  });
</script>
<?php
//make sure to secure this better, a common way is to make sure it was submitted using an http request...
if(isset($_POST['hello_ajax'])){
  if($_POST['hello_ajax'] == ''){
    //this is required so we'll return an error..in JSON..
    $resp['success'] = false;
    $resp['msg'] = 'Hello Ajax is required!';
    //we output, NOT return the response..
    exit(json_encode($resp));
  }else{
    //looks good save it or whatever...
    /** Saving/Calculating code here... **/
    //output a positive response
    $resp['success'] = true;
    $resp['msg'] = 'Hello Ajax was saved!!';
    exit(json_encode($resp));
    //that's it...
  }
}
?>