简体   繁体   中英

Comparing form input to JSON object

I have a popup modal that displays on page load that has the following form in it:

<form class="enterForm">
    <label class="modalFields" id="userName" style="display: none;">
        <span>user Number :</span>
        <input type="text" name="userNum" placeholder="User Number" required/>
    </label>
</form>

<label>
    <span>&nbsp;</span>  
    <input type="submit" value="Submit" class="submitButton">
    <input type="hidden" id="hiddenInput">
</label> 

And on user submission of the form, I want to hit a certain API via an AJAX call, which returns a JSON that looks like:

{  
   "results":[  
      {  
         "person":{  
            "firstName":"John",
            "lastName":"Smith"
         },
         "userNumber":"12345"
      }
   ]
}

If the userNumber matches the value that the user submitted, I then want to update the nav bar to say the person's first name. In terms of process flow I want it to go: user types in user number -> submits form -> AJAX call hits API -> checks to see if user input matches userNumber value in JSON --> if match, selects the firstName value and updates it in the nav bar. How could I go about achieving this?

Considering you know how to do AJAX calls and you're using an API, integrating jQuery to facilitate the thing shouldn't be too hard (if it is, I included additional information after the solution).

Solution

JavaScript

//On form submit
$('#enterForm').submit(function(){
  var userNum = $('[name="userNum"]').val();

  //AJAX call to your API
  $.ajax({
    url: 'myAPICall.php',
    /* data: {userNumber: userNum}, //If necessary */
    success: function(data) {
        // Note: this code is only executed when the AJAX call is successful.
        if(data.results.userNumber == userNum){
            $('#navBarFirstName').text(data.results.person.firstName);
        }
    },
    error: function (err) {
      //If the AJAX call fails, this will be executed.
      console.error(err); 
    }
    dataType: 'JSON'
  });

  return false; //Prevents the page refresh if an action is already set on the form.
});

Explanation

You use jQuery to bind a function (event listener) to the submit event of your form.

When the submit event is triggered, the function runs:

  • It gets the value of your DOMElement with the name attribute " userNum "
  • It makes an AJAX call to your API (with/without the userNum value, you choose if you want to check that on the server side or not)
  • On success, (when the call is done successfully), it updates the navbar content using .text() with the firstName attribute of your JSON response.

Including jQuery

You can integrate jQuery by including the script within your HTML page. You can either download it or use a CDN :

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js">
/* Don't put your code in here it won't be parsed */
</script>

<!-- the following tag could also be <script src="link/to/your/script.js"></script> -->
<script>
 /* Your actual script */
</script>

Make sure to put this line before your actual javascript file containing the script written above, otherwise jQuery won't be initialized and the script won't work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM