$_POST为空,使用Ajax发送表单值

时间:2023-02-08 13:19:41

HTML

HTML

<form action='insert.php' method='POST'>
    <p><b>Client:</b><input type='text' name='idclient'/> 
    <p><b>Total:</b><br /><input type='text' name='total'/> 

    <p><input type='submit' value='Save' id="btnSave"/>
    <input type='hidden' value='1' name='submitted' /> 
</form> 

PHP (insert.php)

PHP(insert.php)

<?php
    echo file_get_contents('php://input');
    include_once "connect.php"; 

    if ($db_found){
        if (isset($_POST['submitted'])) {
            foreach($_POST AS $key => $value) {
                 $_POST[$key] = mysql_real_escape_string($value);                
            } 

            $sql = "INSERT INTO `mytable` ( `idclient` ,  `total` ,  ) " . 
                       "VALUES(  {$_POST['idclient']} , {$_POST['total']}  ) ";
            mysql_query($sql) or die(mysql_error()); 
        }       
    }
    mysql_close($db_handle);
?>

This works OK, but when I try to call the insert using Ajax the $_POST function is empty and I cannot access the values from the form.

这是可行的,但是当我尝试使用Ajax调用insert时,$_POST函数是空的,我无法从表单中访问值。

This is the ajax code and the function call:

这是ajax代码和函数调用:

<form action="javascript:Save()" method='POST'>

Ajax

Ajax

function Save()
{                           
  xmlHttp = getXMLHttp(); // returns a new XMLHttpRequest or ActiveXObject
  xmlHttp.onreadystatechange = function(){

    if(xmlHttp.readyState == 4) { 
      document.getElementById("btnSave").value = "Saved";
      document.getElementById("result").innerHTML = xmlHttp.responseText;
    }
    else{
      document.getElementById("btnSave").value = "Saving...";
    }
  }

  xmlHttp.open("POST", "insert.php", true);     
  xmlHttp.send(null);  // Do I need to create and pass a parameter string here?             
}

Doing an echo file_get_contents('php://input'); indeed the $_POST is empty and the parameters values are not passed along.

做一个回声file_get_contents(“php:/ /输入”);实际上$_POST是空的,参数值不会传递。

I could concatenate the params value in the URL like this

我可以像这样连接URL中的params值

xmlHttp.open("POST", "insert.php?idclient=123&total=43", true);   

But, is there a way to use $_POST and take advantage of it?

但是,有什么方法可以使用$_POST并利用它吗?

4 个解决方案

#1


3  

You will need to set the content-type to application/x-www-form-urlencoded for the values to show up in $_POST.

您需要将content-type设置为application/x-www-form- urlencoding,以便在$_POST中显示值。

For example xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); (if using an XMLHttpRequest object).

例如xmlHttp。setRequestHeader(“内容类型”,“应用程序/ x-www-form-urlencoded”);(如果使用XMLHttpRequest对象)。

#2


1  

Based on the answers this is what I came up with:

根据这些答案,我得出了如下结论:

var xmlHttp = getXMLHttp(); // returns a new XMLHttpRequest or ActiveXObject

function Save() {
  if(xmlhttp) { 
    xmlhttp.open("POST","insert.php",true); 
    xmlhttp.onreadystatechange  = handleServerResponse;

    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');    
    xmlhttp.send("idclient=" + document.getElementById("idclient").value  
                + "&total=" + document.getElementById("total").value); 
  }
}

function handleServerResponse() {
   if (xmlhttp.readyState == 4) {
     if(xmlhttp.status == 200) {
        alert("responseText= " + xmlhttp.responseText);
        document.getElementById("btnSave").value = "Saved";
        document.getElementById("result").innerHTML = xmlhttp.responseText; 
     }
     else {
        alert("Error during AJAX call. Please try again");
     }
   }
   else{
    document.getElementById("btnSave").value = "Saving...";
   }
}

After a while of searching I found out that defining as separate this function (and not inline in onreadystatechange, as in the original question) would get it to work.

经过一段时间的搜索之后,我发现将这个函数定义为独立的(而不是在onreadystatechange中内联,就像在最初的问题中那样)将使它工作。

xmlhttp.onreadystatechange  = handleServerResponse;

However, @Daren made a good point on "special" input values. For example, passing an '&' character in a string field will get incomplete values.

但是,@Daren在“特殊”输入值上做了一个很好的说明。例如,在字符串字段中传递'&'字符将得到不完整的值。

#3


0  

var params = "idclient=" + document.forms[0][0].value + "&total=" + document.forms[0][1].value;
xmlHttp.send(params);

And you should use a function such as encodeURI()

你应该使用一个函数,比如encodeURI()

#4


0  

Try this for your form:

试一下你的表格:

<form action="javascript:Save();return false;" method='POST'>
    <p><b>Client:</b><input id='client' type='text' name='idclient'/> 
    <p><b>Total:</b><br /><input id='total' type='text' name='total'/> 

    <p><input type='submit' value='Save' id="btnSave"/>
    <input type='hidden' value='1' name='submitted' /> 
</form> 

And then make your call like so:

然后这样打电话:

    xmlHttp.open("POST", "insert.php", true);
    var postStr = "idclient=" + document.getElementById("client").value + "&total=" + document.getElementById("total").value;
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
      xmlHttp.send(postStr);

#1


3  

You will need to set the content-type to application/x-www-form-urlencoded for the values to show up in $_POST.

您需要将content-type设置为application/x-www-form- urlencoding,以便在$_POST中显示值。

For example xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); (if using an XMLHttpRequest object).

例如xmlHttp。setRequestHeader(“内容类型”,“应用程序/ x-www-form-urlencoded”);(如果使用XMLHttpRequest对象)。

#2


1  

Based on the answers this is what I came up with:

根据这些答案,我得出了如下结论:

var xmlHttp = getXMLHttp(); // returns a new XMLHttpRequest or ActiveXObject

function Save() {
  if(xmlhttp) { 
    xmlhttp.open("POST","insert.php",true); 
    xmlhttp.onreadystatechange  = handleServerResponse;

    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');    
    xmlhttp.send("idclient=" + document.getElementById("idclient").value  
                + "&total=" + document.getElementById("total").value); 
  }
}

function handleServerResponse() {
   if (xmlhttp.readyState == 4) {
     if(xmlhttp.status == 200) {
        alert("responseText= " + xmlhttp.responseText);
        document.getElementById("btnSave").value = "Saved";
        document.getElementById("result").innerHTML = xmlhttp.responseText; 
     }
     else {
        alert("Error during AJAX call. Please try again");
     }
   }
   else{
    document.getElementById("btnSave").value = "Saving...";
   }
}

After a while of searching I found out that defining as separate this function (and not inline in onreadystatechange, as in the original question) would get it to work.

经过一段时间的搜索之后,我发现将这个函数定义为独立的(而不是在onreadystatechange中内联,就像在最初的问题中那样)将使它工作。

xmlhttp.onreadystatechange  = handleServerResponse;

However, @Daren made a good point on "special" input values. For example, passing an '&' character in a string field will get incomplete values.

但是,@Daren在“特殊”输入值上做了一个很好的说明。例如,在字符串字段中传递'&'字符将得到不完整的值。

#3


0  

var params = "idclient=" + document.forms[0][0].value + "&total=" + document.forms[0][1].value;
xmlHttp.send(params);

And you should use a function such as encodeURI()

你应该使用一个函数,比如encodeURI()

#4


0  

Try this for your form:

试一下你的表格:

<form action="javascript:Save();return false;" method='POST'>
    <p><b>Client:</b><input id='client' type='text' name='idclient'/> 
    <p><b>Total:</b><br /><input id='total' type='text' name='total'/> 

    <p><input type='submit' value='Save' id="btnSave"/>
    <input type='hidden' value='1' name='submitted' /> 
</form> 

And then make your call like so:

然后这样打电话:

    xmlHttp.open("POST", "insert.php", true);
    var postStr = "idclient=" + document.getElementById("client").value + "&total=" + document.getElementById("total").value;
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
      xmlHttp.send(postStr);