将变量从“ PHP”下拉列表传递到Ajax

时间:2019-05-16 21:03:18

标签: php ajax

我有一个表单(id =“ my_form_id”),在表单中,我使用PHP填充了下拉列表,并从Mysql查询,此mysql查询选择名为grupo的列并填充了下拉列表,即mysql使用Java脚本函数“ showname”将名为nombregrupo的表字段放入名为nombregrupo的“输入文本”中并进行更新(onchange)。我有一个用于键入和更改字段nombregrupo的文本(名为“ nombregrupon”)。 我想将从下拉列表(字段grupo)中选择并输入文本(名为“ nombregrupon”)的信息发送给ajax jquery函数,此ajax函数调用php文件(postdata.php)来处理返回的数据到ajax。

我可以将在文本中输入的信息(名为“ nombregrupon”)传递给ajax函数,但是我无法将信息从下拉列表(grupo)传递给ajax函数,这就是整个代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>

<script type="text/JavaScript">
<!--
function MM_goToURL() { //v3.0
  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}

</script>

//Java script function for updating input text nombregrupo
<script language="JavaScript">
function showname(what)
{
  what.form.nombregrupo.value=what.options[what.selectedIndex].title
}

window.onload=function() {
  showname(document.form1.grupo)
}
</script>


//Ajax Jquery for send data variables grupo and nombregrupon to php
 <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
        <script>
            $(document).ready(function(){
                $('#my_form_id').on('submit', function(e){
                    //Stop the form from submitting itself to the server.
                    e.preventDefault();
                    var nombregrupon = $('#nombregrupon').val();
          var grupo= $('#grupo').val();
                    $.ajax({
                        type: "POST",
                        url: 'postdata.php',
            data: { grupo: grupo, nombregrupon: nombregrupon },
                        success: function(data){
                            //Send Alert
                            alert(data);
                            //Show data returne from php postdata file
                            $('#result').html(data);
                        }
                    });
                });
            });
        </script>



</head>

<body>
<form id="my_form_id" name="form1">
<?php

$con = mysql_connect("localhost","root","mysq1passw0rd");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("llamadas", $con);

//PHPMysql Query for fill dropdown list
$query1 = "SELECT * FROM grupostroncales ".
"WHERE grupo!='$grupox' ORDER BY grupo";
$result1 = mysql_query($query1) or die(mysql_error());

//On change call java script funtion for update Input text nombregrupo
echo "<select name=\"grupo\" onchange=\"showname(this)\">";

while($row1=mysql_fetch_array($result1)){
echo "<option value=\"$row1[grupo]\" title=\"$row1[nombregrupo]\">$row1[grupo]</option>";

}

echo "</select>";// Closing of list box 
?>
//Input Text for showing group Name
<input name="nombregrupo" type="text" id="nombregrupo"/>
//Input Text for entering new group Name
<input name="nombregrupon" type="text" id="nombregrupon" />  
<input name="submit" type="submit" id="submit" value="Acept" />
<div id="result"></div>
</form>

</body>
</html> 

4 个答案:

答案 0 :(得分:0)

您有几种选择:

您可以将ID添加到选择元素中,因为您忘记了

var grupo=$('#grupo').val()
echo "<select name=\"grupo\" onchange=\"showname(this)\">"; <-- no id
//----------------
echo "<select id=\"grupo\" name=\"grupo\" onchange=\"showname(this)\">"; 

或者您可以使用名称

var grupo=$('select[name="grupo"]').val()

或者您可以序列化整个表格

$.ajax({
 data : $('#my_form_id').serialize(),
 ...
});

我个人只是将表格序列化

答案 1 :(得分:0)

再次感谢,我修改了代码addind“ select id”并成功了。

请,现在,我正在尝试使用序列化传递整个表单变量,但是我不起作用,这是我的代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>

<script type="text/JavaScript">
<!--
function MM_goToURL() { //v3.0
  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}

//Fir
</script>
<script language="JavaScript">
function showname(what)
{
  what.form.nombregrupo.value=what.options[what.selectedIndex].title
}

window.onload=function() {
  showname(document.form1.grupo)
}
</script>

 <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
        <script>
            $(document).ready(function(){
              var Formvar = $('#my_form_id');
              $("#submit").click(function(){
                     $.ajax({
                        type: "POST",
                        url:Formvar.attr("action"),
                        //url: 'ActualizarGrupoTroncalb.php',
                        data:Formvar.serialize(),
                        success: function(data){
                            //Send Alert
                            alert(data);
                            //Show data from mysql query
                            $('#result').html(data);
                        }
                    });
                });
            });
        </script>



</head>

<body>
<form action="ActualizarGrupoTroncalb.php" id="my_form_id" name="form1">
<?php

$con = mysql_connect("localhost","root","mysq1passw0rd");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("llamadas", $con);

//Hago query1 selecciono el Departamento a buscar
$query1 = "SELECT * FROM grupostroncales ".
"WHERE grupo!='$grupox' ORDER BY grupo";
$result1 = mysql_query($query1) or die(mysql_error());

echo "<select id=\"grupo\" name=\"grupo\" onchange=\"showname(this)\">";

while($row1=mysql_fetch_array($result1)){//Array or records stored in $nt
echo "<option value=\"$row1[grupo]\" title=\"$row1[nombregrupo]\">$row1[grupo]</option>";

}

echo "</select>";// Closing of list box 
?>
<input name="nombregrupo" type="text" id="nombregrupo"/>
<input name="nombregrupon" type="text" id="nombregrupon" />  
<input name="submit" type="submit" id="submit" value="Acept" />
<div id="result"></div>
</form>

</body>
</html>

答案 2 :(得分:0)

@lexer,关于第二个问题,您可能希望尝试使用.serializeArray()而不是serialize()

.serialize()返回一串类似于查询字符串的格式的值,可能与您期望的值不同。

仅供参考-我会对此信息发表评论,但目前无法发表评论。

答案 3 :(得分:0)

我更改了代码,并且变量被序列化为php文件:ActualizarGrupoTroncalb.php并获得了php文件,因为我可以使用变量进行mysql查询,但是未从php返回数据到ajax:<div id="resp"></div>

这是我的代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>

<script type="text/JavaScript">
<!--
function MM_goToURL() { //v3.0
  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}


</script>
<script language="JavaScript">
function showname(what)
{
  what.form.nombregrupo.value=what.options[what.selectedIndex].title
}

window.onload=function() {
  showname(document.form1.grupo)
}
</script>

   <script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
    <script>
    $(document).on('ready',function(){

      $('#submit').click(function(){
        var url = "ActualizarGrupoTroncalb.php";                                     

        $.ajax({                        
           type: "POST",                 
           url: url,                    
           data: $("#formulario").serialize(),
           success: function(data)            
           {
             $('#resp').html(data);           
           }
         });
      });
    });
    </script>



</head>

<body>
<form method="post" id="formulario">
<?php

$con = mysql_connect("localhost","root","mysq1passw0rd");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("llamadas", $con);

//Hago query1 selecciono el Departamento a buscar
$query1 = "SELECT * FROM grupostroncales ".
"WHERE grupo!='$grupox' ORDER BY grupo";
$result1 = mysql_query($query1) or die(mysql_error());

echo "<select id=\"grupo\" name=\"grupo\" onchange=\"showname(this)\">";

while($row1=mysql_fetch_array($result1)){//Array or records stored in $nt
echo "<option value=\"$row1[grupo]\" title=\"$row1[nombregrupo]\">$row1[grupo]</option>";

}

echo "</select>";// Closing of list box 
?>
<input name="nombregrupo" type="text" id="nombregrupo"/>
<input name="nombregrupon" type="text" id="nombregrupon" />  
<input name="submit" type="submit" id="submit" value="Acept" />
</form>
<div id="resp"></div>
</body>
</html>