jQuery XMLHttpRequest调用外部PHP表单不提交

时间:2014-02-27 04:07:38

标签: javascript php jquery ajax xmlhttprequest

我最近有一个专门从事梯形逻辑而不是网络编程的朋友,来找我向她的雇主请求项目帮助。虽然我使用更传统的编码语言,但我自己远不是jquery和php的专家。我们遇到的问题是,通过XMLHttpRequest将jquery / html表单插入父页面的php页面没有从父页面执行其“post”操作。使这个问题更加困难的是,当页面在父页面之外自己运行(直接加载到浏览器中)时,它会很好地执行“post”操作。此时我已经做了很多个小时的搜索和反复试验,但我很难过,现在来找你帮忙。以下是相关的代码位。我们非常感激您提供的任何帮助,因为当通过XMLHttpRequest插入表单时执行表单提交时,我们所尝试的任何内容似乎都无效。

从父页面插入外部表单的Javascript代码:

function showUser(str)
{
if (str=="")
  {
  document.getElementById("insertUserHere").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp2=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp2.onreadystatechange=function()
  {
  if (xmlhttp2.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("insertUserHere").innerHTML=xmlhttp2.responseText;
    }
  }

xmlhttp2.open("GET","ajax-userForm.php?q="+str,true);
xmlhttp2.send();
}

外部PHP页面代码由xhmlhttprequest(ajax-userForm.php)插入:                                                   

    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
    <script type="text/javascript">

    // JQUERY: Plugin "autoSubmit"
    (function($) {
        $.fn.autoSubmit = function(options) {
            return $.each(this, function() {
                // VARIABLES: Input-specific
                var input = $(this);
                var column = input.attr('name');

                // VARIABLES: Form-specific
                var form = input.parents('form');
                var method = form.attr('method');
                var action = form.attr('action');

                // VARIABLES: Where to update in database
                var where_val = form.find('#where').val();
                var where_col = form.find('#where').attr('name');


                // ONBLUR: Dynamic value send through Ajax
                input.bind('blur', function(event) {



                        // Get latest value
                    var value = input.val();

                    if (input.attr('type') == "checkbox")
                        {

                            if (input.attr('checked') )
                            {
                            value = 1;
                            }
                            else
                            {
                            value = 0;
                            }

                        }


                        // AJAX: Send values
                    $.ajax({
                        url: action,
                        type: method,
                        data: {
                            val: value,
                            col: column,
                            w_col: where_col,
                            w_val: where_val                    

                        },
                        cache: false,
                        timeout: 10000,
                        success: function(data) {
                            // Alert if update failed
                            if (data) {
                                alert(data);
                            }
                            // Load output into a P
                            else {
                                $('#notice').text('Updated');
                                $('#notice').fadeOut().fadeIn();
                            }
                        }
                    });
                    // Prevent normal submission of form
                    return false;
                })
            });

        }
    })(jQuery);
    // JQUERY: Run .autoSubmit() on all INPUT fields within form
    $(function(){
        $('#ajax-userForm INPUT').autoSubmit();
    });

    </script>
    <!-- STYLE -->
    <style type="text/css">
        INPUT { margin-right: 1em }
    </style>


</head>
<body>

<!-- CONTENT -->
<?php
$q = intval($_GET['q']);
/*
 * DATABASE CONNECTION
 */

// DATABASE: Connection variables
$db_host        = "localhost";
$db_name        = "DBNAME";
$db_username    = "root";
$db_password    = "DBPWD";

// DATABASE: Try to connect
if (!$db_connect = mysql_connect($db_host, $db_username, $db_password))
    die('Unable to connect to MySQL from ajax-form.');
if (!$db_select = mysql_select_db($db_name, $db_connect))
    die('Unable to select database');

/*
 * DATABASE QUERY
 */

// DATABASE: Get current row
//$result = mysql_query("SELECT * FROM user");
$result = mysql_query("SELECT * FROM user where Project_ID = '".$q."' ");
$row = mysql_fetch_assoc($result);



?>
<form id="ajax-userForm" class="autosubmit" method="post" action="ajax-updateUser.php">
    <fieldset>
        <legend>Update user information</legend>

        <label>First Name:</label>
            <input name="FirstName" value="<?php echo $row['FirstName'] ?>" />

        <label>Last Name:</label>
            <input name="LastName" value="<?php echo $row['LastName'] ?>" />

        <label>Hometown</label>
            <input name="Hometown" value="<?php echo $row['Hometown'] ?>" />

        <label>Married</label>        
            <input type = "checkbox" id = "chkMarried" name="Married" <?php echo $row['Married'] == 1 ? 'checked':'unchecked' ?>/>

        <label>Employed</label>        
            <input type = "checkbox" id = "chkEmployed" name="Employed" <?php echo $row['Employed'] == 1 ? 'checked':'unchecked' ?>  />

        <input id="where" type="hidden" name="Project_ID" value="<?php echo $row['Project_ID'] ?>" />
    </fieldset>
</form>

<p id="notice"></p>


</body>
</html>

页面代码(ajax-updateUser.php)由上面代码中的“post”操作调用(ajax-userForm.php):     

/*
 * DATABASE CONNECTION
 */

// DATABASE: Connection variables
$db_host        = "localhost";
$db_name        = "DBNAME";
$db_username    = "root";
$db_password    = "DBPWD";

// DATABASE: Try to connect
if (!$db_connect = mysql_connect($db_host, $db_username, $db_password))
    die('Unable to connect to MySQL from ajax-update.');
if (!$db_select = mysql_select_db($db_name, $db_connect))
    die('Unable to select database');
$message = "Connection Successful";
//echo "<script type='text/javascript'>alert('$message');</script>";
// DATABASE: Clean data before use
function clean($value)
{
    return mysql_real_escape_string($value);
}

/*
 * FORM PARSING
 */

// FORM: Variables were posted
if (count($_POST) > 0)
{
    $message = count($_POST);
    //echo "<script type='text/javascript'>alert('$message');</script>";
    // Prepare form variables for database
    foreach($_POST as $column => $value)
        ${$column} = clean($value);

    // Perform MySQL UPDATE
    $result = mysql_query("UPDATE user SET ".$col."='".$val."'
        WHERE ".$w_col."='".$w_val."'")
        or die ('Unable to update row.');
}
else
{
    $message = "Nothing in Post";
    echo "<script type='text/javascript'>alert('$message');</script>";
}
?>

1 个答案:

答案 0 :(得分:0)

夫妻俩:

在您的

上遗漏了近距离报价
DBPWD

您对状态200的检查使用:

xmlhttp // whereas the rest is xmlhttp2

我的理论,没有更多背景 - 在声明:

时,您没有使用var关键字
xmlhttp2=new XMLHttpRequest();

这意味着请求附加到窗口上,如下所示:window.xmlhttp2 = ... - 您是否可能在“父”页面的其他位置意外修改了相同的标识符?这可以解释共享状态错误以及它为什么只能在隔离中工作(你没有其他代码隐式修改window.xmlhttp2)

你也可能做坏事:

xmlhttp2.open("GET","ajax-userForm.php?q="+str,true);

因为我不知道这条路是什么意思。

另一个可能是,您是否为来自外部域的请求设置了CORS标头?

干杯,
安德鲁