简体   繁体   English

使用AJAX加载带有表单的页面,并从主页提交表单

[英]Load a page with a Form using AJAX, And submitting the form from the Main page

I have two pages in my folder, main page & secondary page and it contains the following. 我的文件夹中有两个页面, 主页辅助页面 ,它包含以下内容。

main page: 主页:

HTML HTML


<div id='show'></div>

AJAX AJAX


$(document).ready(function() {
   $.post('sec_page.php',{form: form}, function(form){
      $('#show').html(form);
   })
})

secondary page: 辅助页面:

HTML HTML


<form action='sec_page.php' method='post'>
    <input type='submit' id='submit' name='submit'>
</form>
<div id='vview'></div>

AJAX AJAX


$(document).ready(function() {
   $('#submit').submit(function(submit){
      submit.preventDefault();
      var Submission = $(this).serialize();
      var Action = $(this).attr('action');
      $.post('sec_page.php',{Submission : Submission}, function(vview){
            $('#vview').html(vview);
      })
   })
})

PHP PHP


if(isset($_POST['submit'])){
   echo "The form has been Submitted!";
}

The main page shows me everything inside the secondary page , Which is a form , If i clicked on the submit button from the main page , It redirects me into the secondary page , And i don't want that to happen, Since i want the form to be submitted from the main page and shows the echo in it too; 主页向我显示了辅助页面表单)中的所有内容 ,如果我单击主页上的“ 提交”按钮,它会将我重定向到辅助页面 ,并且我不希望这种情况发生,因为我想要从主页提交的表格,并在其中显示echo

So i tried to put the AJAX inside the secondary page and didn't solve the problem, Moved it to the main page instead, And didn't still the same problem; 因此,我尝试将AJAX放在辅助页面中 ,但没有解决问题,而是将其移到了主页 ,并且仍然没有同样的问题;

So in brief, How can i submit the form from the main page without refreshing it or redirecting to the secondary page . 简而言之,我如何从主页提交表单 ,而无需刷新表单或将其重定向到辅助页面

If not possible, I would like to know a better way to do that. 如果不可能的话,我想知道一种更好的方法。

.serialize() does not include submit buttons. .serialize()不包含提交按钮。
Only when you submit the form normally the button you used to submit the form will be sent. 仅当您正常提交表单时,才会发送用于提交表单的按钮。
For ajax you can manually put that value in the data or have a hidden input. 对于ajax,您可以将该值手动放入数据中或具有隐藏的输入。

<form action='sec_page.php' method='post'>
    <input type='hidden' name='submit_name' value="submit_value">
    <input type='submit' id='submit' name='submit'>
</form>

PHP PHP

if(isset($_POST['submit_name'])){
   echo "The form has been Submitted!";
}

also you pass the serialized data alone as the data parameter 你也单独传递序列化的数据作为数据参数

  var Submission = $(this).serialize();
  var Action = $(this).attr('action');
  $.post('sec_page.php', Submission, function(vview){
        $('#vview').html(vview);
  })

Also you have to attach the submit event handler to the form not the submit button 另外,您还必须将Submit事件处理程序附加到表单而不是Submit按钮上

$('form').submit(function(submit){

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM