iBobb iBobb - 6 months ago 15
Javascript Question

PHP Post after Ajax returns values

For some reason a

POST
variable from my
form
is always empty. Here's my code...
I have a bootstrap select which returns information which I display upon selecting a new item from the dropdown (select).

Code:

$(function() {


$("#shiftsDD").change(function(){
var selectedItemId = $('#shiftsDD option:selected').val();

$.post('/step/services/shiftInfo.php', { shiftID : selectedItemId }, function(res){
$("#shiftCard").show();
var jsonRes = $.parseJSON(res);
$("#address").html(jsonRes[0]);
$("#duties").html(jsonRes[1]);
$("#employer").html(jsonRes[4]);
$("#payRate").html(jsonRes[5]);
$("#theShiftID").html(jsonRes[6]);
console.log(res);

});
});

});


All of those values from the jsonRes array are assigned in here:

<form role="form" name="cardForm" method="POST">
<div class="card" id="shiftCard">
Employer:
<h3 id="employer">Test Employer</h3><br>
Address:
<h3 id="address">Test Address</h3><br>
Duties include:
<h3 id="duties">Test duties</h3><br>
Pay rate:
<h3 id="payRate">Test PayRate</h3><br>
<h5 id="theShiftID" name="myShiftID"></h5>
<br>
<button type="submit" class="btn btn-lg btn-green-solid" name="shiftsBtn">Accept work</button>
</div>
</form>


I've tried lots of things but I am new to ajax and not a pro in PHP so I don't know why:

if (isset($_POST['shiftsBtn'])) {

$theId = $_POST['myShiftID'];
...


myShiftID
is always empty

ShiftsDD select code:

<select name="shiftsDD" id="shiftsDD" class="form-control form-control-45">
<option value="0">Select a shift</option>
<?php
$theQuery = "
SELECT DATE_FORMAT(StartTime, '%d/%b/%Y' ) AS ShiftDate, ShiftID,ShiftTitle,TIMESTAMPDIFF(MINUTE, StartTime, EndTime) AS ShiftDuration, ROUND(PayRate,2) as PayRate FROM Shifts;
";
$result = $DBH->query($theQuery);
$result->execute();

while($r = $result->fetch()) {
$theDuration = $r['ShiftDuration'] / 60;

echo "<option value='" . $r['ShiftID'] ."'>[". $r['ShiftDate'] . "] " . $r['ShiftTitle'] . " (Hours: " . $theDuration . ")</option>";
}

?>
</select>

Answer

Ok so you need to change the form to match below. Have removed the elements you don't need to change. Note changing the h5 to an input.

<form role="form" name="cardForm" method="POST">
<div class="card" id="shiftCard">
<input id="theShiftID" name="myShiftID" value="" /><br />
<button type="submit" class="btn btn-lg btn-green-solid" name="shiftsBtn">Accept work</button>
</div>
</form>  

Then once you've made the form changes, you need to change your js from .html() to .val()

$(function() {
    $("#shiftsDD").on('change', function(){
        var selectedItemId = $(this).val();  

        $.post('/step/services/shiftInfo.php', { shiftID : $(this).val() }, function(res){
          $("#shiftCard").show();
          var jsonRes = $.parseJSON(res);
          $("#theShiftID").val(jsonRes[6]);    
        });
    });

});
Comments