0

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?

1
  • 2
    Would you mind posting the javascript client-side + api endpoint server-side code you have so far? Commented Sep 1, 2015 at 13:39

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This is a great answer, but I'm having some issues with one of the lines $('#navBarFirstName').text(data.results.person.firstName) is returning the following error: "Uncaught TypeError: Cannot read property 'firstName' of undefined"
Then the issue is within your JSON object. debug it using console.log() to see its structure and adapt the data.results.person.firstName in my code snippet to whatever is the right thing within your JSON object. My example was based on the JSON object your provided in the question and might not be 100% accurate for your actual code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.