使用ajax和php显示文本

I'm just trying to do a simple thing in ajax but it does not work. I just want to display a text when i click on the input button

ajax.js

jQuery(document).ready(function($) {
$('#insertForm').change(function(){
//on recupere la valeur de l'attribut value pour afficher tel ou tel resultat
var req=$('#insertForm').val();
//requête ajax, appel du fichier function.php
$.ajax({
  type: "POST",
  url: "lib/function.php",
  data: "insertForm="+req,
  dataType : "html",
  //affichage de l'erreur en cas de problème
  error: function(XMLHttpRequest, textStatus, errorThrown) {
          alert(XMLHttpRequest + '--' + textStatus + '--' + errorThrown);
      },
      //function s'il n'y a pas de probleme
  success:function(data){
    $('.coucou').empty();
    $('.coucou').prepend(data.coucou)
  }
});
});
}); 

html.php

<div class="coucou"></div>
<button type="button" class="btn btn-success btn-xs" name="insertForm" id="insertForm" style="margin-top: 5px;;">
    <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
</button>

function.php

if(isset($_POST['insertForm'])){
    echo "coucou";
}
jQuery(document).ready(function($) {
    $('#insertForm').click(function(){
    //on recupere la valeur de l'attribut value pour afficher tel ou tel resultat
        var req=$('#insertForm').val();
        //requête ajax, appel du fichier function.php
        $.ajax({
          type: "POST",
          url: "lib/function.php",
          data: "insertForm="+req,
          dataType : "html",
          //affichage de l'erreur en cas de problème
          error: function(XMLHttpRequest, textStatus, errorThrown) {
                  alert(XMLHttpRequest + '--' + textStatus + '--' + errorThrown);
              },
              //function s'il n'y a pas de probleme
          success:function(data){
            $('.coucou').empty();
            $('.coucou').text(data);
          }
        });
    });
}); 

You need to use .click() and not .change() and also, in the success, you receive only a string not an object so you just need to write data directly (with .text())

Copy my code because i have also add ; that you had forgotten. (It's work, I tested)

Another point you use .val() on #insertForm but there is no value attribute in your html. So var req is an empty string

You have a button element not input type button and button element does have text content, you can change to this:

var req=$('#insertForm').text();

but still i feel you don't have any text in the button then what do you want to post exactly.


Problems:

  1. button element has text content instead of value.
  2. datatype:"html" is expecting some html in the response.
  3. data.coucou in the success function is expecting json data.