简体   繁体   中英

Comparing user input value with JSON object via ajax to ultimately update page content

On page load for my current project, I have a modal overlay appear that prompts the user to enter a 5 digit long value. From that value, I want to have an AJAX call hit an API to see if that value exists/matches and from there, update the nav bar to say, "Hello, [user]" ([user] being another key value pair from the JSON object that the 5 digit long value is referencing. I'm still new to AJAX, so I'm wondering what the best way to go about doing this. I know the following is completely wrong, but I imagine this is the basic framework for starting out something like this.

$("#inputForm").submit(function(){
    $.ajax({
        url: "/my/api/url/",
        type: "POST",
        data: postData
        success: function(postData){
            //if 5-digit value matches value in the API, update the navbar with name key value pair in the JSON object
        }
    });
});
$("#inputForm").submit(function(evt){
    $.ajax({
        url: "/my/api/url/",
        type: "POST",
        data: postData
        success: function(returnData){
          var data = JSON.parse(returnData);
          // check data and update nav bar
        }
        error: function() {
          evt.preventDefault();
          // show error
        }
    });
});

Try utilizing change event prompt

 $(function() { var check = function(vals, data) { if (vals.length === 5 && vals.split("").every(Number)) { if (vals in data) { // do `$.ajax()` stuff here /* $.ajax({ url: "/my/api/url/", type: "POST", data: vals success: function(returnData) { var data = JSON.parse(returnData); // check data and update nav bar $("#navbar").html("Hi, " + data) } error: function() { evt.preventDefault(); // show error } }); */ $("#navbar").html("Hi, " + data[vals]) } } }; var data = { 12345: "abc" }; var vals = prompt("enter 5 digits"); if (vals !== null) check(vals, data); $("input").change(function(e) { check(this.value, data) }) }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="navbar"></div> <input type="text" placeholder="enter 12345" /> 

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