Ajax code is not working [closed]

0

I'm starting in ajax and I've had trouble understanding the error you're experiencing in this example. I click 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><inputtype="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>

test.php:

  <?php
     if($_POST['action'] == 'call_this') {
        echo "YES";
     }
  ?>
    
asked by anonymous 07.09.2016 / 00:16

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><inputtype="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 test.php remains the same

    
07.09.2016 / 01:30
0

Unset% with% of your onclick="myAjax();" element, and start declaring events as follows:

Rewriting your action button a little bit:

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

Now, changing input :

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

In the above code snippet, at the javascript line beginning with 3 you ordered that the $("#um-teste") button, when clicked will trigger the function that is contained therein. You will then start executing your input , so you discard the use of the function assigned in the element itself.

    
07.09.2016 / 01:31
0

Hello, guys, do this, put the $ (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>
    
07.09.2016 / 01:44