使用post方法将数据从表单发送到php文件

时间:2013-07-14 06:24:01

标签: php ajax

我正在尝试将form.php中的sent和id值发送到test.php。没有ajax使用它工作正常。我正在学习ajax,这是我的代码:

<html>
<head>
<script>
function showUser(str)
{
    if (str=="")
    {
        document.getElementById("txtHint").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("txtHint").innerHTML=xmlhttp.responseText;
        }
    }

    xmlhttp.open("POST","ajax_test.php?q="+str,true);
    xmlhttp.send(sent&id);
}
</script>
</head>
<body>
<form>
    Enter the sentence: <input type="text" name="sent"/><br/>
    <input type="submit" name="insert" onclick="showUser(this.value)"/>
</form>
</br>
UPDATE </br>
<form action="ajax_test.php" method="post"/>
    <pre>
        Enter the ID : <input type="text" name="id"/><br/>
        Enter the sentence: <input type="text" name="sent"/><br/>
    </pre>
    <input type="submit" name="update"/>
</form>
</br>
<form>
    <input type="submit" onclick="showUser(this.value)"/>
</form>
<br>
<div id="txtHint">
    <b>Person info will be listed here.</b>
</div>
</body>
</html>

ajax_test.php就在这里:

<html> <body > 
<?php
$q = $_GET["q"];
if (!empty($_POST['insert']))
{
    echo "Operation: Insert";
    echo "<br/>";

    $s    = $_POST['sent'];
    $flag = 0;

    echo "Entered sentence : $s";

    if (preg_match_all('/[^=]*=([^;@]*)/', 
        shell_exec("/home/technoworld/Videos/LinSocket/client '$s'"),
        $matches)) //Values stored in ma.
    {
        $x = (int) $matches[1][0]; //optionally cast to int
        $y = (int) $matches[1][1];
    }

    echo "<br/>";
    echo "Positive count :$x";
    echo "<br/>";
    echo "Negative count :$y";
    echo "<br/>";

    //---------------DB stuff --------------------
    $con = mysqli_connect('127.0.0.1:3306', 'root', 'root', 'test');
    if (mysqli_connect_errno()) {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    $sql1 = "INSERT INTO table2 
             (id,sent,pcount,ncount,flag)
             VALUES
             ('','$_POST[sent]','" . $x . "','" . $y . "','" . $flag . "')";
    if (!mysqli_query($con, $sql1)) {
        die('Error: ' . mysqli_error($con));
    }

    echo "1 record added";
    mysqli_close($con);
}

// -------------------------------UPDATE --------------------------
if (!empty($_POST['update']))
{
    echo "Operation: update";
    echo "<br/>";

    $s    = $_POST['sent'];
    $flag = 1;

    echo "Entered sentence : $s";

    if (preg_match_all('/[^=]*=([^;@]*)/', 
        shell_exec("/home/technoworld/Videos/LinSocket/client '$s'"),
        $matches)) //Values stored in ma.
    {
        $x = (int) $matches[1][0]; //optionally cast to int
        $y = (int) $matches[1][1];
    }

    echo "<br/>";
    echo "Positive count :$x";
    echo "<br/>";
    echo "Negative count :$y";
    echo "<br/>";

    //---------------DB stuff --------------------
    $con = mysqli_connect('127.0.0.1:3306', 'root', 'root', 'test');
    if (mysqli_connect_errno()) {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    $sql1 = "INSERT INTO table2 
             (id,sent,pcount,ncount,flag)
             VALUES
             ('$_POST[id]','$_POST[sent]','" . $x . "','" . $y . "','" . $flag . "')";
    if (!mysqli_query($con, $sql1)) {
        die('Error: ' . mysqli_error($con));
    }

    echo "1 record added";
    mysqli_close($con);
}
?>
</html > </body >

当我点击按钮时,它什么也没显示。我如何发送id和发送值,以便我可以在我正在使用的ajax_test.php上使用它?

2 个答案:

答案 0 :(得分:3)

ajax方法为post,这是无效的

xmlhttp.open("POST","ajax_test.php?q="+str,true);

而应该是

xmlhttp.open("POST","ajax_test.php",true);
xmlhttp.send('q='+str);

除非您使用GET方法

,否则不应将请求字符串放在网址中

要阻止表单在点击时发送和转到操作页面,您需要在javascript中使用preventDefault()这样的函数,并且还应该初始化顶部的var xmlhttp功能

function showUser(str, e){
  e.preventDefault();
  var xmlhttp;

并在html onclick="showUser(this.value, event)"

下面是对此解决方案的短期修复,但我强烈建议您阅读有关javascript,html和php语法的更多内容,只要最佳做法

<script>
function showUser(form, e) {
 e.preventDefault();
 var xmlhttp;
 var submit = form.getElementsByClassName('submit')[0];
 var sent = form.getElementsByName('sent')[0].value || '';
 var id = form.getElementsByName('id')[0].value || '';


if (sent==""){
    document.getElementById("txtHint").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(e) {
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
        document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
}
xmlhttp.open(form.method, form.action, true);
xmlhttp.send('sent='+sent+'&id='+id+'&'+submit.name+'='+submit.value);
}
</script>
<form action="ajax_test.php" method="POST" onsubmit="showUser(this, event)">
Enter the sentence: <input type="text" name="sent"><br>
<input type="submit" class="submit" name="insert" value="submit" >
</form>
<br>UPDATE <br>
 <form action="ajax_test.php" method="POST" onsubmit="showUser(this, event)">
<pre>
    Enter the ID : <input type="text" name="id"><br>
    Enter the sentence: <input type="text" name="sent"><br>
</pre>
 <input type="submit" class="submit" value="submit" name="update">
</form> <br>
<div id="txtHint">
 <b>Person info will be listed here.</b>
 </div>

除非您使用像xhtml这样的严格标记,否则无需向<br> br或<input>输入标记添加结束斜杠。

在您的ajax_test.php文档中

删除<html><body>标记,以便ajax可以正确处理它。不要担心如果在没有调用ajax的情况下调用页面,它将不会影响页面的呈现方式,浏览器会自动将这些标记放入页面,除非它已经存在。

更改ajax_test.php

<?php
// $q = $_POST["q"];
// you never process the $q var so i commented it
if (isset($_POST['insert']) && $_POST['insert'] !== '') {
echo "Operation: Insert","<br>";

$s = $_POST['sent'];
$flag = 0;

echo "Entered sentence : $s";

if (preg_match_all('/[^=]*=([^;@]*)/', 
    shell_exec("/home/technoworld/Videos/LinSocket/client '$s'"),
    $matches)){ //Values stored in ma. 
    $x = (int) $matches[1][0]; //optionally cast to int
    $y = (int) $matches[1][1];
}

echo "<br>",
     "Positive count :$x",
     "<br>",
     "Negative count :$y",
     "<br>";

//---------------DB stuff --------------------
$con = mysqli_connect('127.0.0.1:3306', 'root', 'root', 'test');
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql1 = "INSERT INTO table2 
         (id,sent,pcount,ncount,flag)
         VALUES
         ('".$_POST['id']."','".$_POST['sent']."',' $x ','$y','$flag')";
if (mysqli_query($con, $sql1)) {
   echo "1 record added";
} else {
   die('Error: ' . mysqli_error($con));
}


mysqli_close($con);
}

// -------------------------------UPDATE --------------------------
 if (isset($_POST['update']) && $_POST['update'] !== '') {
echo "Operation: update", "<br>";
 // you say update but you are actually inserting below

$s    = $_POST['sent'];
$flag = 1;

echo "Entered sentence : $s";

if (preg_match_all('/[^=]*=([^;@]*)/', 
    shell_exec("/home/technoworld/Videos/LinSocket/client '$s'"),
    $matches)) //Values stored in ma.
{
    $x = (int) $matches[1][0]; //optionally cast to int
    $y = (int) $matches[1][1];
}

echo "<br>",
     "Positive count :$x",
     "<br>",
     "Negative count :$y",
     "<br>";

//---------------DB stuff --------------------
$con = mysqli_connect('127.0.0.1:3306', 'root', 'root', 'test');
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql1 = "INSERT INTO table2 
         (id,sent,pcount,ncount,flag)
         VALUES
         ('".$_POST['id']."','".$_POST['sent']."',' $x ','$y','$flag')"; // error here again $_POST[id] should be $_POST['id'] with quotes
if (mysqli_query($con, $sql1)) {
  echo "1 record added";
} else { 
  die('Error: ' . mysqli_error($con));
}

 mysqli_close($con);
}
?>

这里有很多错误,我试图纠正它们,但我无法测试它,就像我说你应该阅读最佳实践,因为你的代码和语法非常糟糕,不要苛刻。< / p>

修改

preventDefault的进一步说明:

我们使用此功能来阻止默认表单提交操作,即通过将浏览器重定位到操作页面action="ajax_test.php"并在后台设置参数或在网址中设置GET方法来发送表单

然后在那之后你仍然想要发送表格和那些ajax进来的地方;   我们使用ajax异步发送表单而不需要浏览器重定位。我们可以在ajax调用中加载页面,并处理来自javascript xmlhttp.responseText内部调用的页面的响应。

答案 1 :(得分:1)

这是代码: Context-type遗失了,还有其他一些变化!

<html>
<head>
    <meta content="text/html;charset=utf-8" http-equiv="Content-Type" />
    <meta content="utf-8" http-equiv="encoding" />
    <script type="text/javascript">
    function showUser(form, e) {
        e.preventDefault();
        e.returnValue=false;
        var xmlhttp;
        var submit = form.getElementsByClassName('submit')[0];
        var sent = form.elements['sent'].value;
    var id = form.elements['id'].value;

        if (window.XMLHttpRequest) {
            xmlhttp=new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }

        xmlhttp.onreadystatechange = function(e) {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
                document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open(form.method, form.action, true);
        xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); 
        xmlhttp.send('sent=' + sent + '&id=' + id + '&' + submit.name + '=' + submit.value);
    }
    </script>
</head>
<body>
    <h4>INSERT</h4>
    <form action="ajax_test.php" method="POST" onsubmit="showUser(this, event)">
        <pre>
             <label>Enter the sentence: <input type="text" name="sent"></label><br/>
        </pre>
                <input type="submit" class="submit" name="insert" value="submit"/>
        <input type="" name="id" style="display: none"/>
    </form>

    <h4>UPDATE</h4>
    <form action="ajax_test.php" method="POST" onsubmit="showUser(this, event)">
        <pre>
            <label>Enter the ID:        </label><input type="text" name="id"><br>
            <label>Enter the sentence:  <input type="text" name="sent"></label><br />
        </pre>
        <input type="submit" class="submit" value="submit" name="update"/>
    </form>

    <br />
    <div id="txtHint">
        <b>Person info will be listed here.</b>
    </div>
</body>
</html>