Ajax - 在表单提交jquery / php / mysql / html之后立即更新强制url

时间:2013-03-13 21:39:17

标签: javascript ajax jquery

如何通过表单将数据正确插入数据库后,强制all_contacts(从用户中选择*)立即显示。必须通过ajax无页面刷新方法完成。在表单2中,all_contacts值执行(select * from users)并使用基于字符串q的url /php/group_list.php?q=all_contacts,如果有帮助的话。

表单1

   <form method="post" name="form">       
    <label>First Name:</label><input id="First_Name" name="First_Name" type="text" />
    <br /> 
    <label>Last Name:</label><input id="Last_Name" name="Last_Name" type="text" />
    <br /> 
    <label>Email Address:</label><input id="Email_Address" name="Email_Address" type="text" />
    <br /> 
    <label>Telephone Number:</label><input id="Telephone_Number" name="Telephone_Number" type="text" />
    <br /> 
    <label>Postal Address:</label><input id="Postal_Address" name="Postal_Address" type="text" />

    <select id="Contact_Group" name="Contact_Group">
    <option value="">Select Group</option>
    <option value="Ungrouped">Ungrouped</option>
    <option value="Friends">Friends</option>
    <option value="Family">Family</option>
    <option value="Colleagues">Colleagues</option>
    </select>
    </li></ul>
    <div >
    <input type="submit" value="Submit" class="contact"/>
    <span class="error" style="display:none"> Please Enter Valid Data</span>
    <span class="success" style="display:none"> Registration Successfully</span>
    </div></form>

表格2

<form>
<select name="users" id="users" onChange="showContact(this.value)">
<option value="">Select Group</option>
<option value="all_contacts">All Contacts</option>
<option value="friends">Friends</option>
<option value="family">Family</option>
<option value="colleagues">Colleagues</option>
<option value="ungrouped">Ungrouped</option>
</select>
</form>

JS

//Displays the user contact summmary
    function showContact(str)
    {
    if (str=="")
      {
      document.getElementById("txtSummary").innerHTML="";
      return;
      }
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        document.getElementById("txtSummary").innerHTML=xmlhttp.responseText;
        }
      }
    xmlhttp.open("GET","php/group_list.php?q="+str,true);
    xmlhttp.send();
    }

    //Displays the detailed user contact description 
    function showContactDetail(str)
    {
    if (str=="")
      {
      document.getElementById("txtSummaryDetails").innerHTML="";
      return;
      }
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        document.getElementById("txtSummaryDetails").innerHTML=xmlhttp.responseText;
        }
      }
    xmlhttp.open("GET","php/contact_details.php?q="+str,true);
    xmlhttp.send();
    }

    // Checkbox select and delete with loop
    jQuery(function($) {
        $("form input[id='check_all']").click(function() { // triggred check

            var inputs = $("form input[type='checkbox']"); // get the checkbox

            for(var i = 0; i < inputs.length; i++) { // count input tag in the form 
                var type = inputs[i].getAttribute("type"); //  get the type attribute
                    if(type == "checkbox") {
                        if(this.checked) {
                            inputs[i].checked = true; // checked
                        } else {
                            inputs[i].checked = false; // unchecked

                         }
                    } 
            }
        });

        $("form input[id='submit']").click(function() {  // triggred submit

            var count_checked = $("[name='data[]']:checked").length; // count the checked
            if(count_checked == 0) {
                alert("Please select a product(s) to delete.");
                return false;
            } 
            if(count_checked == 1) {
                return confirm("Are you sure you want to delete these product?");   
            } else {
                return confirm("Are you sure you want to delete these products?");  
              }     
        });
    }); // jquery end

    //Submit form
    $(function() {
    $(".contact").click(function() {
    var First_Name = $("#First_Name").val();
    var Last_Name = $("#Last_Name").val();
    var Email_Address = $("#Email_Address").val();
    var Telephone_Number = $("#Telephone_Number").val();
    var Postal_Address = $("#Postal_Address").val();
    var Contact_Group = $("#Contact_Group").val();

    var dataString = 'First_Name='+ First_Name + '&Last_Name=' + Last_Name + '&Email_Address=' + Email_Address + '&Telephone_Number=' + Telephone_Number + '&Postal_Address=' + Postal_Address + '&Contact_Group=' + Contact_Group;

    if(First_Name=='' || Last_Name=='' || Email_Address=='' || Telephone_Number=='' || Postal_Address=='' || Contact_Group=='')
    {
    $('.success').fadeOut(200).hide();
    $('.error').fadeOut(200).show();
    }
    else
    {
    $.ajax({
    type: "POST",
    url: "php/new_contact.php",
    data: dataString,
    success: function(){
    $('.success').fadeIn(200).show();
    $('.error').fadeOut(200).hide();

    //Newly added
    $('#First_Name').val('');
    $('#Last_Name').val('');
    $('#Email_Address').val('');
    $('#Telephone_Number').val('');
    $('#Postal_Address').val('');
    $('#Contact_Group').val('');

    }
    });
    }
    return false;
    });
    });

更正了更新的Ajax版本

//Displays the user contact summmary
function showContact(str)
{
if (str=="")
  {
  document.getElementById("txtSummary").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtSummary").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","php/group_list.php?q="+str,true);
xmlhttp.send();
}

//Displays the detailed user contact description 
function showContactDetail(str)
{
if (str=="")
  {
  document.getElementById("txtSummaryDetails").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtSummaryDetails").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","php/contact_details.php?q="+str,true);
xmlhttp.send();
}

// Checkbox select and delete with loop
jQuery(function($) {
    $("form input[id='check_all']").click(function() { // triggred check

        var inputs = $("form input[type='checkbox']"); // get the checkbox

        for(var i = 0; i < inputs.length; i++) { // count input tag in the form 
            var type = inputs[i].getAttribute("type"); //  get the type attribute
                if(type == "checkbox") {
                    if(this.checked) {
                        inputs[i].checked = true; // checked
                    } else {
                        inputs[i].checked = false; // unchecked

                     }
                } 
        }
    });

    $("form input[id='submit']").click(function() {  // triggred submit

        var count_checked = $("[name='data[]']:checked").length; // count the checked
        if(count_checked == 0) {
            alert("Please select a product(s) to delete.");
            return false;
        } 
        if(count_checked == 1) {
            return confirm("Are you sure you want to delete these product?");   
        } else {
            return confirm("Are you sure you want to delete these products?");  
          }     
    });
}); // jquery end

//Submit form
$(function() {
$(".contact").click(function() {
var First_Name = $("#First_Name").val();
var Last_Name = $("#Last_Name").val();
var Email_Address = $("#Email_Address").val();
var Telephone_Number = $("#Telephone_Number").val();
var Postal_Address = $("#Postal_Address").val();
var Contact_Group = $("#Contact_Group").val();

var dataString = 'First_Name='+ First_Name + '&Last_Name=' + Last_Name + '&Email_Address=' + Email_Address + '&Telephone_Number=' + Telephone_Number + '&Postal_Address=' + Postal_Address + '&Contact_Group=' + Contact_Group;

if(First_Name=='' || Last_Name=='' || Email_Address=='' || Telephone_Number=='' || Postal_Address=='' || Contact_Group=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "php/new_contact.php",
data: dataString,

success: function(){

$(document).ready(function() {
    $("#formSearch").submit(function() {
        var options = {
            /* target:"#divResult", */

            success: function(html) {
                $("#txtSummary").replaceWith($('#txtSummary', $(html)));
            },

            url: "http://localhost/example/comp333assn1/php/group_list.php?q=all_contacts"
        }

        $(this).ajax(options);
        return false;

    });
});

$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();

//Newly added
$('#First_Name').val('');
$('#Last_Name').val('');
$('#Email_Address').val('');
$('#Telephone_Number').val('');
$('#Postal_Address').val('');
$('#Contact_Group').val('');

}



});
}
return false;
});
});

2 个答案:

答案 0 :(得分:0)

没有直接解决方案或具体解决方案。只需要你使用JavaScript。

检查一下:

Ajax - How refresh after submit

答案 1 :(得分:0)

我的建议是使用jQuery.form插件,它将您的表单转换为Ajax表单,只需很少的工作和代码。它会使你的代码变得如此简单。

jQuery Form Plugin下载.js文件,只需将此行添加到您的代码中:

<script src="jquery.form.3.10.js"></script>

删除除表单之外的所有内容(但添加'id'和'action'参数),然后添加:

<script type="text/javascript">
    $(document).ready(function() {
        $('#yourform').ajaxForm({
                beforeSubmit: checkForm, 
                type: 'post', 
            dataType:  'json', 
                cache: false,
                beforeSend: function() {
                    $("#formstatus").addClass( "ui-autocomplete-loading" );
                },
                success: function(data, status, xhr, myForm) {
                    if ( data.usersfound !== undefined ) {
                        $('#output').html( 'ok' );
                        // ### todo: do something with data
                    }
                    if ( data.erroruser !== undefined ) {
                        $('#output').html( 'error: ' + data.erroruser.msg );
                        // ### your code returned an error
                    }
                },
                error: function(xhr ,status ,error ) {
                    $('#output').html( xhr.responseText ); 
                    // ### status != 200
                    },
                complete: function() {
                    $("#formstatus").removeClass("ui-autocomplete-loading");
                }


        }); 
    });
    function checkForm() {
        // ### todo: check the input of the form; return(false) if something is wrong, else return(true)
    }
</script>

注意:
- ui-autocomplete-loading是一个来自jQuery UI的类,它显示了“做一些加载”动画。这当然是可选的 - 保存数据的结果应该返回json数据。这可能是(usersfound:[{“id”:“1”,“name”:“john”}])或(erroruser:{“msg”:“bla”})

更多示例可以在jQuery Form Plugin页面找到!