简体   繁体   中英

How do I use jquery to make a click on a link post to a php script with ajax?

I have a database of members which I need to be able to click on an alphabetical character link or button, pass that character to an ajax event and run a script with the character as an option, something like getResults?char=A on a regular submitted form.

<form>

<p>
<a href="#" name="char" class="switchChar" value="A" id="A">A</a>
<a href="#" name="char" class="switchChar" value="B" id="B">B</a>
</p>

<div id="Results">Results Div</div>

</form>

<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js' type='text/javascript'></script>


<script>
  $(document).ready(function() {
    // $(document).on('click','.switchChar',function()
    $('a.switchChar').click(function() {

      var DATA=$(this).val();
      var data=(DATA);
      var CHAR=$(this).attr('char');
      $("#Results").html( "" );
      var dataString = 'char='+ data;

      $.ajax({
        url: "getResults.php", /* Will add this later */
        type: "POST",
        data: dataString,
        cache: false,
        success: function(data)
        {
          $("#Results").html(data);
        }
      }
    });
  });
</script>

Do not use var DATA=$(this).val(); or var CHAR=$(this).attr('char'); and var data=(DATA);

use .attr('value'); its 'a' element not 'input'( .val() )

or use $(this).html(); for get letter inside <a></a>

$(document).ready(function() {

    $('a.switchChar').click(function() {
      var data=$(this).attr('value'); //this 'a' element (not 'input'), 'value' -> attribute
      $("#Results").html("");
      var dataString ='char='+ data ; 
     console.log(dataString)
      $.ajax({
           url: "getResults.php", /* Will add this later */
           type: "post",
           data: dataString,
           cache: false,
           success: function(data){
              $("#Results").html(data);
           }

      });
   });
  });

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