Why does my Jquery Ajax call fail with error 0?

I am trying to send an ajax request using the below code but I keep getting an Error 0 message. I am pretty sure the url is valid but I just wondered if the code is ok as I am trying this for the first time, altering a template provided by a tutor. Any advice gratefully received.

     $('#submitOne').click(function() {

       $.ajax({
         url: "http://localhost/alistairJenkins/task/php/getCountryCode.php",
         type: 'POST',
         dataType: 'json',
         data: {
             lat: $('#latOne').val(),
             lng: $('#lngOne').val()
         }})
        .done(function(result) {

             console.log(result);

             if (result.status.name == "ok") {
                 $('#txtResult').html(result['data']);
             }
         })
        .fail(function(jqXHR, textStatus, errorThrown) {
                 var errorMsg = jqXHR.status + ' : ' + textStatus + errorThrown;
                 alert("Error - " + errorMsg);
         })
      })

1 answer

  • answered 2021-10-12 16:31 Carsten Massmann

    Here is a working snippet that demonstrates the use of $.ajax() with a public JSON resource:

    $('#submitOne').click(function() {
    
           $.ajax({
             // url: "http://localhost/alistairJenkins/task/php/getCountryCode.php",
             url: "https://jsonplaceholder.typicode.com/users",
             type: 'POST',
             dataType: 'json',
             data: {
                 lat: $('#latOne').val(),
                 lng: $('#lngOne').val()
             }}) 
            .done(function(result, textStatus, xhr) {
    
                 console.log(result);
    
                 if (xhr.status===201) $('#txtResult').text(result.id);
             })
            .fail(function(jqXHR, textStatus, errorThrown) {
                     var errorMsg = jqXHR.status + ' : ' + textStatus + errorThrown;
                     alert("Error - " + errorMsg);
             }) 
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input id="latOne" value="52.373920">  <input id="lngOne" value="9.735603"> 
    <button id="submitOne">go</button><br>
    <div id="txtResult"></div>

    The .status property can be found in the xhr object (the third argument of the callback function in the .done() event handler). The value 201 signals success.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum