How to Fetch results from server using JQuery AJAX? on the basis of Drop-down Condition
-
25-02-2021 - |
Question
I have two conditions, if two conditions are matching the given value should display. I am using input value as Drop down. If the value of two drop-downs matched i need to display my value on same page. For Example: dropDown1 selection -> KM : 10(Dropdown), dropDown1 selection -> Fueal : 2 Lit(Dropdown)
Output: Happy Jorney On the same page and below the drop-down List.
Solution
For that you have two files basically, look the code your will get clear understanding for request flow also it will not change user selction:
your html file will be testing.html
<html>
<head>
<title> Upgrade Cost</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
</head>
<form method='POST' action='home.php'>
Name : <input type="text" name="name"/><br/><br/>
Email Id : <input type="text" name="email_id"/><br/><br/>
Contact Number : <input type="text" name="contact_number"/><br/><br/>
I have :
<select id="old">
<option value = "select_option">Select Option</option>
<option value = "one">One</option>
<option value = "two">Two</option>
<option value = "three">Three</option>
<option value = "four">Four</option>
<option value = "five">Five</option>
</select><br/><br/>
I want :
<select id="new">
<option value = "select_option">Select Option</option>
<option value = "one">One</option>
<option value = "two">Two</option>
<option value = "three">Three</option>
<option value = "four">Four</option>
<option value = "five">Five</option>
</select>
</form>
<!-- <button id="btn_check_value">Check for value</button> -->
<div id="result"></div>
<script>
$(document).ready(function(){
$('#new').on('change',function(){
var old_val = $("#old option:selected").val();
var new_val = $("#new option:selected").val();
$.ajax({
type: "POST",
url: "home.php",
dataType: "text",
data: { old: old_val, new: new_val },
success: function(data) {
// Check the output of ajax call on firebug console
//console.log(data);
$('#result').html(data);
}
});
});
});
</script>
</html>
you ajax file will be:
<?php
if(isset($_POST['old']) && isset($_POST['new'])){
$old = $_POST['old'];
$new = $_POST['new'];
if($old=='one'&&$new=='two'){
// echo json_encode(array('Cost 10$'));
echo "Upgrade Code : 10$";
}
elseif($old=='one'&&$new=='three')
{
echo "Upgrade Code : 20$";
}
elseif($old=='one'&&$new=='four')
{
echo "Upgrade Code : 30$";
}
elseif($old=='one'&&$new=='five')
{
echo "Upgrade Code : 40$";
}
else{
echo "Choose Valid Options";;
}
}
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange