I'm new in programming. Sorry if my codes are messy. I want to ask about passing value from JS variable to PHP variable.
I have 2 files.
First is ajaxvariable4.php that contains HTML and jQuery AJAX.
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<form>
<select name="target" id="target">
<option value="Ferrari">Car</option>
<option value="Wimcycle">Bicycle</option>
</select>
<script>
$( "#target" ).change(function() {
var vehicle=$('#target option:selected').val();
$.ajax({
type: "POST",
data: { 'vehicle': vehicle },
url: "passingajax.php",
success: function(json) {
$("#tb").val(vehicle);
}
});
});
</script>
<input type="text" id="tb">
</form>
</body>
</html>
Second is passingajax.php that contains PHP variable to save value from JS variable.
<?php
if( isset($_POST['vehicle']) )
{
$vehicle= $_POST['vehicle'];
echo $vehicle;
}else{
echo "Data doesn't exist";
}
?>
When I executed ajaxvariable4.php , the ajax call was success and the column with id=tb filled with value that selected in option. But when I executed passingajax.php the output was Data doesn't exist. So I assume that variable vehicle in passingajax.php didn't receive value from JS variable.
My question is if the ajax call was success, why the variable vehicle in passingajax.php didn't receive value from JS variable ?
Can you try below code:
$('#target').change(function () {
var vehicle = $("#target >option:selected").val();
}
Form:
<select name="target" id="target" onChange="test(this.value)">
<option value="Ferrari">Car</option>
<option value="Wimcycle">Bicycle</option>
</select>
JQuery:
function test(t){
console.log(t.value);
}