简体   繁体   中英

How do I get my jquery post request to work with the variable stored from a function on a click?

I have been banging my head against the wall trying to pass a game's name through to my php function as soon as a user clicks a button. The idea is the user clicks a button, which has a value of its videogame name, then the php script checks that game's ranking and returns that ranking to the html. I have made post requests work before, and even here when I manually set the variable name to one of the Games to test it, it works. Please help!

<script>
$(document).ready(function(){
    //global n variable
    n = $();

        $('#target').click(function(){
            //set value of n to the game's name
                n = $(this).val();

        });

        //then send the name as term to my php function to deal with it and return 
        //the ranking
    $.post('getTotal.php', {term: n}, function(data){
        //been trying to see if anything comes through for debugging purposes
                alert(data);

        //commented this out for now, just puts it in the div I left open
        //$('#total').html(data);
    });

});

</script>

You should put the $.post into your click handler... so it will only run when you actually click the button... now your code sets up an n variable, its value is an empty jQuery object (why?). Then it attaches a click handler on the button. Then it runs a $.post request - n is still an empty jQuery object. Clicking the button happens much later...

Also, using globals should be avoided. The var keyword should be used when declaring variables.

simply when the user clicks the button. inside the click handler, obtain the value and perform an http post

$ajax or $POST

eg -

$(document).ready(function() {
      $('#target').click(function()
            $.ajax({  
              type: "POST",
              url: "url...",
              data: "n="+nVal+",
              success: function(html){
                alert( "Submitted");
              }
           });
      });
});

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