如何使用一个按钮处理两个ajax函数以将变量传递给php表单

时间:2017-07-18 04:42:00

标签: javascript php sql ajax

我有两个javascripts函数,用于传递两个不同的变量。第一个javascript是传递下拉区域,第二个是在第二个下拉列表中传递名称。现在我想在一个按钮提交中执行。下面是我的代码,它是部分工作的。当我将值传递给php时,它会运行两到三次以获得结果,并得出错误的结果。我的ajax或sql查询有问题吗?



$(function() { 
	 $('#form').submit(function(e) { 
            e.preventDefault();
		var id=$(".area").val();
		var dataString = 'id='+ id;

            $.ajax({
                type        : 'POST',
                url         : 'LeaveRecord1.php',
                data        : dataString,
                
            })
            .done(function(data) {
                $('.results').html(data);    
            })
        });
    }); 
$(function() { 
	 $('#form').submit(function(e) { 
        e.preventDefault();
	  	var idd=$(".slct2").val();
		var dataStringg = 'idd='+ idd;
    
            $.ajax({
                type        : 'POST',
                url         : 'LeaveRecord1.php',
                data        : dataStringg,
                
            })
            .done(function(data) {
                $('.results').html(data);    
            })
     });
    }); 

<td><input type="submit"   name="report" class="report" id="report" onClick=" myFunction();"></td>
&#13;
&#13;
&#13;

用于捕获值的PHP文件

   $poarr =Array();
if (isset($_POST['id'])) {
    $sarea=$_POST['id'];
    $sql = "SELECT tblLeaveHeader.RefNo, tblLeaveHeader.StaffId, tblLeaveHeader.Branch, tblLeaveHeader.Remark, tblLeaveHeader.Createby, tblLeaveHeader.Approvedd, tblLeaveHeader.Approveby, tblLeaveHeader.AreaCode
     FROM tblLeaveHeader INNER JOIN tblStaff ON tblLeaveHeader.AreaCode = tblStaff.AreaCode AND tblLeaveHeader.StaffId = tblStaff.StaffId WHERE (tblLeaveHeader.AreaCode = '$sarea')";
};


if (isset($_POST['idd'])) {
$suser=strtoupper($_POST['idd']);
$sql = "SELECT tblLeaveHeader.RefNo, tblLeaveHeader.StaffId, tblLeaveHeader.Branch, tblLeaveHeader.AreaCode, tblLeaveHeader.Remark, tblLeaveHeader.Createdd, tblLeaveHeader.Createby, 
tblStaff.StaffName FROM tblLeaveHeader INNER JOIN tblStaff ON tblLeaveHeader.StaffId = tblStaff.StaffId AND tblLeaveHeader.AreaCode = tblStaff.AreaCode WHERE (tblStaff.StaffName = '$suser')";
 };
$link = odbc_connect(DB_HSATTEND, DB_USER, DB_PASS);
$res = odbc_exec($link,$sql); 
while ($row = odbc_fetch_array($res)) {
           $poarr[] = $row;
   } 

 odbc_free_result($res);
 odbc_close($link); 

2 个答案:

答案 0 :(得分:0)

你可以使用以下ajax,但你必须根据这个重写你的php和sql。

$(function() { 
 $('#form').submit(function(e) { 
    e.preventDefault();
    var id=$(".area").val();
    var idd=$(".slct2").val();
    var dataString = 'id='+ id+'&idd='+idd;
        $.ajax({
            type    : 'POST',
            url     : 'LeaveRecord1.php',
            data    :  dataString,
            success : function(data) {
                $('.results').html(data);    
            },
        });
    });
}); 

您的PHP代码应为

<?php
$poarr =Array();
$empty = false;
if (isset($_POST['id'])) {
  $sarea=$_POST['id'];
  $sql = "SELECT tblLeaveHeader.RefNo, tblLeaveHeader.StaffId, tblLeaveHeader.Branch, tblLeaveHeader.Remark, tblLeaveHeader.Createby, tblLeaveHeader.Approvedd, tblLeaveHeader.Approveby, tblLeaveHeader.AreaCode
FROM tblLeaveHeader INNER JOIN tblStaff ON tblLeaveHeader.AreaCode = tblStaff.AreaCode AND tblLeaveHeader.StaffId = tblStaff.StaffId WHERE (tblLeaveHeader.AreaCode = '$sarea')";
  $link = odbc_connect(DB_HSATTEND, DB_USER, DB_PASS);
  $res = odbc_exec($link,$sql); 
  while ($row = odbc_fetch_array($res)) {
      $poarr[] = $row;
      $empty = true;
  } 
  odbc_free_result($res);
  if($empty){
        if (isset($_POST['idd'])) {
            $suser=strtoupper($_POST['idd']);
            $sql = "SELECT tblLeaveHeader.RefNo, tblLeaveHeader.StaffId, tblLeaveHeader.Branch, tblLeaveHeader.AreaCode, tblLeaveHeader.Remark, tblLeaveHeader.Createdd, tblLeaveHeader.Createby, tblStaff.StaffName FROM tblLeaveHeader INNER JOIN tblStaff ON tblLeaveHeader.StaffId = tblStaff.StaffId AND tblLeaveHeader.AreaCode = tblStaff.AreaCode WHERE (tblStaff.StaffName = '$suser')";
            $res = odbc_exec($link,$sql); 
            while ($row = odbc_fetch_array($res)) {
                $poarr[] = $row;
            } 
            odbc_free_result($res);
        }
    }
    odbc_close($link); 
}
?>

答案 1 :(得分:0)

这是我的版本。根据我的解释,我应该遵循以下原则:

  • 如果未选择组合框值,则显示警告:&#34;请选择一个值&#34;。
  • ...如果仅在组合框&#34; .areas&#34;中选择了区域,则仅发布所选区域值。
  • else(例如,如果在组合框中选择名称&#34; .names&#34;),则仅发布所选名称值。

如果你真的想要别的东西,请考虑一下,并以更好的解释重新编写你的问题。

请仔细阅读所有代码,因为我应用了我发现更好的名称和ID。另请注意,我在ajax中使用了return false,而不再使用preventDefault()。此外,您的数据库代码缺少两个基本要素:

有关预准备语句+异常处理(使用mysqli)的完整示例,请参阅THIS。你真的不想在没有它们的情况下继续编程; - )

index.php(带表格):

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Test</title>

        <script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
        <script src="index.js" type="text/javascript"></script>
    </head>
    <body>

        <form id="form" name="form" action="" method="post">
            <select id="area" name="area" class="area">
                <option value="">- Select area -</option>
                <option value="123">Area 1</option>
                <option value="456">Area 2</option>
                <option value="789">Area 3</option>
            </select>
            <select id="slct2" name="slct2" class="slct2">
                <option value="">- Select name -</option>
                <option value="John">John</option>
                <option value="Smith">Smith</option>
                <option value="Mikaela">Mikaela</option>
            </select>
            <input type="submit" name="report" class="report" id="report">
        </form>
        <br/><br/>
        <div class="results">
            Here comes the results...
        </div>

    </body>
</html>

index.js(使用ajax):

$(document).ready(function () {
    $('#form').submit(function (e) {
        var areaCode = $(".area").val();
        var staffName = $(".slct2").val();
        var data = {};

        if (areaCode === '' && staffName === '') {
            alert('Please choose a value from selects!');
            return false;
        } else if (areaCode !== '' && staffName === '') {
            data.areaCode = areaCode;
        } else {
            data.staffName = staffName;
        }

        var ajax = $.ajax({
            method: 'post',
            dataType: 'html',
            url: 'LeaveRecord1.php',
            data: data
        });
        ajax.done(function (response, textStatus, jqXHR) {
            $('.results').html(response);
        });
        ajax.fail(function (jqXHR, textStatus, errorThrown) {
            $('.results').html(textStatus + '<br />' + errorThrown);
        });
        ajax.always(function (response, textStatus, jqXHR) {
            //...
        });

        return false;
    });
});

LeaveRecord1.php(处理表单值的地方):

<?php

$poarr = array();

if (isset($_POST['areaCode'])) {
    $areaCode = $_POST['areaCode'];
    $sql = "SELECT 
                tblLeaveHeader.RefNo,
                tblLeaveHeader.StaffId,
                tblLeaveHeader.Branch,
                tblLeaveHeader.Remark,
                tblLeaveHeader.Createby,
                tblLeaveHeader.Approvedd,
                tblLeaveHeader.Approveby,
                tblLeaveHeader.AreaCode 
            FROM tblLeaveHeader 
            INNER JOIN tblStaff ON 
               tblLeaveHeader.AreaCode = tblStaff.AreaCode 
               AND tblLeaveHeader.StaffId = tblStaff.StaffId 
           WHERE tblLeaveHeader.AreaCode = '" . $areaCode . "'";
} elseif (isset($_POST['staffName'])) {
    $staffName = strtoupper($_POST['staffName']);
    $sql = "SELECT 
                tblLeaveHeader.RefNo,
                tblLeaveHeader.StaffId,
                tblLeaveHeader.Branch,
                tblLeaveHeader.AreaCode,
                tblLeaveHeader.Remark,
                tblLeaveHeader.Createdd,
                tblLeaveHeader.Createby,
                tblStaff.StaffName 
            FROM tblLeaveHeader 
            INNER JOIN tblStaff ON 
                tblLeaveHeader.StaffId = tblStaff.StaffId 
                AND tblLeaveHeader.AreaCode = tblStaff.AreaCode 
            WHERE tblStaff.StaffName = '" . $staffName . "'";
}

$link = odbc_connect(DB_HSATTEND, MYSQL_USERNAME, MYSQL_PASSWORD);

while ($res = odbc_exec($link, $sql)) {
    do {
        while ($row = odbc_fetch_array($res)) {
            $poarr[] = $row;
        }
        odbc_free_result($res);
    } while (odbc_next_result($res));
}

odbc_close($link);

if (count($poarr) > 0) {
    echo '<pre>' . print_r($poarr, TRUE) . '</pre>';
} else {
    echo 'There are some errors somewhere :-(';
}