Jump to content
Gilbert

passing variables in jQuery

Recommended Posts

trying to learn .post method in jQuery - is there a way to pass a variable to the code to use in the 'data' argument of the function.  The 'try it yourself' example from w3schools has the data hard-coded in, but I would like to use a variable that I got from a form, or something to do the post.  I tried a few things but to no avail.  Here is the code from the example:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $.post("demo_test_post.asp",
        {
          name: "Donald Duck",
          city: "Duckburg"
        },
        function(data,status){
            alert("Data: " + data + "\nStatus: " + status);
        });
    });
});
</script>
</head>
<body>

<button>Send an HTTP POST request to a page and get the result back</button>

</body>
</html>

I tried this but it didn't work.  I tried with and without the braces.   How can you pass a variable to a jQuery method?  should I use a global variable.  please be explicit.  Thanx

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
    	var myName = "Donald Duck";
        var myCity = "Duckburg";
        var myData = "{name:" + myName + ", city:" + myCity + "}";
        $.post("demo_test_post.asp", myData, function(data,status){
            alert("Data: " + data + "\nStatus: " + status);
        });
    });
});
</script>
</head>
<body>

<button>Send an HTTP POST request to a page and get the result back</button>

</body>
</html>

 

Share this post


Link to post
Share on other sites

I think I just figured it out - I searched further and the example they give in the 'jQuery AJAX' methods section gives a better example than in the "tutorial".  They use a variable there and I understand how to use it now.   Be careful - I've got a variable and I know how to use it!!  I hope this post will help someone else if they have the same question.

  • Thanks 1

Share this post


Link to post
Share on other sites
Quote

I've got a variable and I know how to use it!!!

Bravo!  I like it!

Roddy

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×