javascriptphpajax

how to display output using php ajax in jquery


Can you please tell me what is wrong with this code? It's not giving me any output after clicking submit.

$('#btnRun').click(function() {
  $.ajax({
    url: "libs/php/getCountryCode.php",
    type: 'POST',
    dataType: 'json',
    data: {
      lat: $('#lat1').val(),
      lng: $('#long1').val()
    },
    success: function(result) {
      console.log(JSON.stringify(result));

      if (result.status.name == "ok") {
        $('try').html(result.data.countryCode);
      }
    },
    error: function(jqXHR, textStatus, errorThrown) {
      // your error code
    }
  });
});

The result is obtained is this format:

{
  "languages": "de-AT,hr,hu,sl",
  "distance": "0",
  "countryCode": "AT",
  "countryName": "Austria"
}

Solution

  • Try replacing your code with this and see if there are any logs

    <form method="post">
      <label for="lat1">Latitude: </label>
      <input type="text" id="lat1">
      <label for="long1">Longitude: </label>
      <input type="text" id="long1">
      <br><br>
      <button id="btnRun" type="button">Submit</button>
    </form>
    
    $('#btnRun').click(function(event) {
      event.preventDefault();
    
      $.ajax({
        url: "libs/php/getCountryCode.php",
        type: 'POST',
        dataType: 'json',
        data: {
          lat: $('#lat1').val(),
          lng: $('#long1').val()
        },
        success: function(result) {
          console.log(JSON.stringify(result));
    
          if (result.status.name === "ok") {
            $('#try').html(result.data.countryCode);
          }
        },
        error: function(jqXHR, textStatus, errorThrown) {
          console.error("Error: " + textStatus, errorThrown);
        }
      });
    });