表单自动提交而不刷新

时间:2015-08-05 13:08:37

标签: javascript php ajax forms

我在互联网上搜索了很多答案,但没有一个对我没有帮助。我也不太了解Ajax。 一切都必须在这一页上发生而不刷新(直到整个表格将被提交)。

<form id="service" action="" method="post">
    <select name="service" onchange="document.getElementById('service').submit();" name="select">
        <option value="1" <?php if($_POST['service']==1){ print ' selected'; }?>>Opcja1</option>
        <option value="2" <?php if($_POST['service']==2){ print ' selected'; }?>>Opcja2</option>
    </select>
    </form>
if($_POST['service']==1 | empty($_POST['service']) ){
    //other forms and options
    }
elseif($_POST['service']==2){
    //smth
    }

3 个答案:

答案 0 :(得分:2)

你需要截取表单提交并让ajax句柄在这些行上发布数据是一个好的开始:

$('#service select').on('change', function(e) {
    e.preventDefault();
    $.ajax({
      method: "POST",
      url: "site-to-post-to.php",
      data: $('#service').serialize(),
    }).done(function( msg ) {
      alert( "Data Saved: " + msg );
    });
})

这将序列化表单中的数据并通过ajax将其发送到您指定的任何URL。您需要从html中删除onchange。

答案 1 :(得分:0)

要清除一些javascript代码,请使用jquery,这使得ajax类更加简单:

$.ajax({
      method: "POST",
      url: "some.php",
      data: { name: "John", location: "Boston" }
    })
      .done(function( msg ) {
        alert( "Data Saved: " + msg );
      });

“一切都必须在这一页上发生而不刷新”我不知道你的意思是你试图说它只会提交用户许可的表格?只有表格完成后才能获得许可? 如果是这样你只需要在php文件中说ajax调用是指那个:

if $_GET['form'] == isSafeandCorrect
     echo json_encode('success');

然后在成功函数(){}

中的ajax调用中
.success(function(msh){
     if msg == success
          window.location.href = "yournewPage.php";
 })

请记住属性dataType,如果不正确,则不会显示错误 还有ajax调用避免调用同一页面,总是一个没有html的明确的php文件

答案 2 :(得分:0)

为了灵活性,我建议将url和方法写入表单,并从children元素触发提交事件 它给出了什么?
1.形式处理的一点 2.从任何子元素中调用触发器提交事件

这是代码:

&#13;
&#13;
$(function(){
  
  function handleForm(form, callback) {
    form.on('submit', function(e) {
      e.preventDefault();
    
      $.ajax({
        method: $(this).attr('method'),
        url: $(this).attr('action'),
        data: $(this).serializeArray(),
        beforeSend: function(xhr, settings) {
          console.log('sending '+settings.method+' to: '+settings.url);
        }
      })
      .always(callback);
    });
  }

  $('#service select[name="service"]').on('change', function() {
    $(this).parent().submit();
  });
  
  handleForm($('#service'), function(response){console.log(response);});
  
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form id="service" action="/some/uri" method="post">
    <select name="service">
        <option value="1">Opcja1</option>
        <option value="2">Opcja2</option>
    </select>
</form>
&#13;
&#13;
&#13;