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

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...