Joe Santy
Joe Santy

Reputation: 31

$("#input").val() returning undefined while using $.post()

I feel silly not being able to solve this, but I keep having my post request coming up as undefined on the line $('#input').val(). Can someone help me solve this issue?

<html>
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
      let sr = $("#input").val();
      $(document).ready(function(){
        $("button").click(function(){
          $.post("http://localhost:8080/", {subreddit: sr}, function(data, status){
            alert("Data: " + data + "\nStatus: " + status);
          });
        });
      });
    </script>
  </head>
  <body>
    <div id='content' style="height:100%, width:100%">
        <input id='input' type="text" placeholder='enter subreddit'/>
        <button>Search</button>
      </form>
    </div>
  </body>
</html>

Upvotes: 2

Views: 142

Answers (3)

Joe Santy
Joe Santy

Reputation: 31

My issue was actually with the backend. It kept returning undefined because I didn't call the .toString() method. Thanks for the help guys.

Upvotes: 0

PitchBlackCat
PitchBlackCat

Reputation: 555

The let sr = $("#input").val(); part of your script should run when you click the button.

Move it inside the click handler like so:

$(document).ready(function() {
  $("button").click(function(){
    let sr = $("#input").val();
    $.post("http://localhost:8080/", {subreddit: sr}, function(data, status){
      alert("Data: " + data + "\nStatus: " + status);
    });
  });
});

Upvotes: 1

Jack Bashford
Jack Bashford

Reputation: 44145

It's because that part of your script is running before your DOM is loaded. Move it inside your $(document).ready():

$(document).ready(function() {
    let sr = $("#input").val();
    //Rest of your code
});

Upvotes: 1

Related Questions