Home > Net >  ajax JavaScript how to find if phone number already exist?
ajax JavaScript how to find if phone number already exist?

Time:02-21

I am getting input from user. If any user input his phone number then I want to know does this phone number already exist in my json dictionary. If phone number exist then I want to automatically render his name. Here is my code:

<input type="text" name="patient_number"  placeholder=" 44****" id="patient_number">
<!- if phone number exist then I want to automatically render his name->
<input type="text" name="patient_name"  id="patient_name" >  


<script> 
document.getElementById('patient_number').addEventListener('change', function() {
const phone_number =  this.value;
$.ajax({
           type: 'GET',
           url: "{%url 'hospital:appoinment-json'  %}",
           number: number,
           success: function(response){
                for (key in response.data){
                var patient_name = (response.data[key].patient_name)
                var patient_phone_number = (response.data[key].phone)   
                        
                }},
           error: function(error){
               console.log(error)
           }})});
 
</script>   

here is my json object:

{"data": [{"patient_name": "Jhone", "phone": "1234", "id": 2}, {"patient_name": "Mike Hartho", "phone": "454", "id": 1}]}

CodePudding user response:

Once you get the json data with list of patient details, parse through the object array and check if there's any object containing the same phone number. If you find the object, get the id of the object and access that object using the id to display the user details.

Let's assume that the variable userDetails has the json containing user data and phoneNumber has the phone number entered by the user.

userDetails.map((user) => {
  if (user.phone === phoneNumber) {
    console.log(`User: ${user.id}`);
    console.log(user);
  }
});
  • Related