Ajax code is not working

Asked

Viewed 85 times

0

I am starting in ajax and I have had difficulty understanding the error you are giving in this example. I click on the button and no action is taken.

HTML:

   <html>

      <head>
         <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
         <title></title>
      </head>

      <body>
         <input type="button" value="Testar" onclick="myAjax();"></input>
      </body>

   </html>

   <script>
       function myAjax() {
          $(document).ready(function()
          {
             $.ajax({
             type: "POST",
             url: 'teste.php',
             data:{action:'call_this'},           
             success:function(html) {
                alert(html);
             }
          });
          return false;                
        }
      </script>

php test.:

  <?php
     if($_POST['action'] == 'call_this') {
        echo "YES";
     }
  ?>
  • What error occurs? Any message appears?

  • He says nothing, just gives no answer to the code @Guilhermenascimento

3 answers

0


Test like this

<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <title></title>
</head>
<body>
<input type="button" value="Testar" id="myAjax"></input>
</body>
</html>
<script>
 $(document).ready(function(){
  $("#myAjax").click(function(){
    $.post( "test.php", { action: "call_this" })
    .done(function( data ) {
      alert( data );
    });
  });

 });
</script>

your.php test remains the same

  • It worked man... thanks

0

Remove the onclick="myAjax();" of its element input, and start declaring events as follows:

Rewriting your action button a little bit:

<input type="button" id="um-teste" value="testar" />

Now by changing the javascript:

<script>
$(function(){
    $("#um-teste").click(function(){
        $.ajax({
        type: "POST",
        url: 'teste.php',
        data:{action:'call_this'},           
        success:function(html)
        {
            alert(html);
        }
        });
    });
});
</script>

In the code snippet above, on the line 3 that begins with $("#um-teste") you ordered that the button input, to be clicked will trigger the function that is contained in there. Then, you will start executing your ajax, with this you discard the use of the function assigned in the element itself.

0

Hello, dude do so, put $(Document).ready... at the beginning of the script, and dps create the function only with ajax!

   <script>
 $(document).ready(function(){

  $("#myAjax").click(function(){

    $.ajax(
      url: "test.php", 
      data: { action: "call_this" },
      .success(function( data ) {
      alert( data );
    });

  });

 });
</script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.