0

I have two javascripts function which use to pass two different variable.first javascript is to pass the area in the dropdown and the second one is to pass the name in second dropdown.Now i want to do it within one button submit.Below is my code,which is works partially.When i pass the value to php it's run thru two or three times to get results,and come out with wrong results.Does it any wrong with my ajax or sql query?

$(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>

PHP file to capture the value

   $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); 
Woon Hc
  • 57
  • 1
  • 8
  • 2
    Why don't you pass both parameters in one single Ajax call? Also, you're two async calls overwrite each others result... – patrick Jul 18 '17 at 04:43
  • as you wrote both ajax on form submit, and if i am not wrong your html having only one form, so bot ajax will called – RAUSHAN KUMAR Jul 18 '17 at 04:47
  • i'm worry that it would not function ,since it's actually get two different value in same time,when i call choose area,then only show the list of area,if call name only show the name only – Woon Hc Jul 18 '17 at 04:49
  • Yes it's only one form,so both ajax will be call when the button is click,but when pass to sql it become loop two or three times and get the results.the initial results was correct but after that ,it came two wrong results or get empty results – Woon Hc Jul 18 '17 at 04:51
  • The first js snippet has some serious code smell. – sitilge Jul 18 '17 at 05:40

2 Answers2

0

You can use following ajax but you have to rewrite your php and sql according to this.

$(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);    
            },
        });
    });
}); 

And your PHP code should be

<?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); 
}
?>
Ankit Singh
  • 1,477
  • 1
  • 13
  • 22
  • by using the the code you suggested.it's only able to capture one of the sql query.Only applicable for the name,by the way how should i modify my sql,i found nothing wrong with it.Can u suggest it anywhere? – Woon Hc Jul 18 '17 at 06:04
  • It's works fine when select the area part ,but when come to the name part .the result is combine together with the area one.Does it the sql problem ? (*by right area will get all 4 result,and the name will get 3 result *) but when select name it add up with the area result become 7 results display – Woon Hc Jul 18 '17 at 06:45
  • Which means when choose to staffname,the result wont be replace ,but continue after the result of area – Woon Hc Jul 18 '17 at 07:31
0

Here is my version. From what I understood from your explanations, the following principle should apply:

  • If no combobox value selected, then show alert: "Please choose a value".
  • ...else if only area is selected in combobox ".areas", then post only the selected area value.
  • else (e.g. if name selected in combobox ".names"), then post only the selected name value.

If you really meant something else, then please think about it and reedit your question with a better explanation.

Please read all codes carefully, because I applied names and ids which I found better. Also notice that I used return false in ajax, and no preventDefault() anymore. Also, your database code lacks of two essential elements:

See THIS for a full example of prepared statements + exception handling (using mysqli). You really don't want to continue programming without them ;-)

index.php (with the form):

<!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 (with the 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 (where the form values are processed):

<?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 :-(';
}
  • Thanks for the helping,but here the problem is it will sometime get the empty result which mean,sometime area get the result,the staffname will get error with no results,it will happens either area or results .And give me this error "odbc_fetch_array() [function.odbc-fetch-array]: No tuples available at this result index " – Woon Hc Jul 18 '17 at 06:30
  • Please make an effort and tell us exactly what you want to have in form, what you want to have in ajax and what you want to have in LeaveRecord1.php, because all your explanations are somehow confusing. Make it step by step. Like this: In form I want to select this or this, in ajax I want to send this or this. In php sql part I want this or this happen. Then you got our help. Otherwise we can't help you, even if we want to. –  Jul 18 '17 at 06:41
  • Tell me at least: is my form correct? Is my ajax correct? Is my LeaveRecord1.php correct? –  Jul 18 '17 at 06:44
  • The ajax is correct if correct so far,but the LeaveRecord1.php sql looks like will occur same problem like my previous work – Woon Hc Jul 18 '17 at 07:26
  • Which means sometime the result may come out in either area or staffname,Result would not come in both place,i'm not sure whether is that sql capture problem or any other possible reason. – Woon Hc Jul 18 '17 at 07:28
  • Question: you want ONLY one sql at a time, right? I mean: when you select a name, you want JUST the staffname to run, right? –  Jul 18 '17 at 07:30
  • And when you select an area, then you want JUST the area sql to run, right? –  Jul 18 '17 at 07:32
  • Yes pale,this is what i want for my form :) – Woon Hc Jul 18 '17 at 07:38
  • ok. So, my php part in LeaveRecord1.php until `$link = odbc_connect(...);` is correct, right? –  Jul 18 '17 at 07:42
  • i think shud be no problem with dat part,just not sure what is the problem in the sql part .i dint see any problem with $ link there since is same with my previous one – Woon Hc Jul 18 '17 at 07:59
  • I meant all until $link = ... is the correct way or not? –  Jul 18 '17 at 08:08
  • @WoonHc Ok, I reedited "LeaveRecord1.php" in my answer. So, I changed the fetching part. It says now: "_Iterate through returned records_" as comment in code. Try it. My start point were your error: "_odbc_fetch_array() [function.odbc-fetch-array]: No tuples available at this result index_" –  Jul 18 '17 at 08:12
  • i'm not so sure,but i think all is in correct way ,but just the $areacode does is the correct way to write like dat ? i tot is oni need to write like "$areacode" enough – Woon Hc Jul 18 '17 at 08:13
  • I don't understand "dat", "i tot is oni". I mean it :-) But I think you are referring yourself to the "[concatenation operator](http://php.net/manual/en/language.operators.string.php)". Use it, it's much better for code readability and other good stuff which you'll discover later. –  Jul 18 '17 at 08:18
  • @WoonHc I repeat: I reedited "LeaveRecord1.php" in my answer. So, I changed the fetching part. It does a `do-while` loop now. There, where it says: "Iterate through returned records" as comment in code. Try it. My start point were your error: "odbc_fetch_array() [function.odbc-fetch-array]: No tuples available at this result index" –  Jul 18 '17 at 08:19
  • @WoonHc ...and I changed also the printing results part: `if (count($poarr) > 0) {...`. –  Jul 18 '17 at 08:23
  • Yes pale i have try u code and i post a picture at above,the error message come out when i choose to the staffname,so sorry "tot" is thought actually,sorry for my broken english :( . – Woon Hc Jul 18 '17 at 08:24
  • No problem with broken english. It's just I can'understand it. But we'll manage to understand us somehow ;-) –  Jul 18 '17 at 08:27
  • @WoonHc So, when you only select the area code, the LeaveRecord1.php works perfect, right? And when you select staff name, it comes error, right? –  Jul 18 '17 at 08:36
  • @WoonHc Why is "LeaveRecord2.php" in your error image?? You are doing something different. Please show the complete codes. I can't stay too much anymore. –  Jul 18 '17 at 08:38
  • no i just copy a new file oni,i dint change anything,just change the path oni.is just the same thing,just copy one to do testing oni – Woon Hc Jul 18 '17 at 08:40
  • @WoonHc Ok. Then show me please the line 46 (which gives error) from php file. –  Jul 18 '17 at 08:41
  • yes just when select staffname is come out error.the code i have show u was actually completed one .other is just the content of the dropdown and design only – Woon Hc Jul 18 '17 at 08:42
  • "while ($row = odbc_fetch_array($res)) {" this the line which occur error – Woon Hc Jul 18 '17 at 08:43
  • line 45 was actually empty space no code there @aendeerei – Woon Hc Jul 18 '17 at 09:03
  • @WoonHc :-)) well, line 45 should have been the line `do {`, isn't it?... Anyway, I think I found the problem. See my LeaveRecord1.php now. I changed the fetching code again. The problem was `odbc_free_result($res)`, because was outside the loop earlier. So read the whole new fetching loop and try it. –  Jul 18 '17 at 09:07