Armen Babakanian
Armen Babakanian

Reputation: 2305

jQuery Ajax call seems to be failing but file exist

I have the following jQuery code which does an AJAX call to this specific file '/errorData/errorMessage.json' in my server and then never calls the .done function.

The file exist and I double checked the URL, I basically typed the URL: localhost/../errorData/errorMessage.json and it shows the content of this json file.

I even checked the apache2 log file and the error doesn’t file file doesnt exist and I also checked the firefox debugger window it doesn’t say GET failed.

This code worked when I ran it from a different server but since I moved it to a different server, it doesn’t work any more.

function getErrorMessage()
{
    $.ajax({
        url: "../errorData/errorMessage.json",
        cache: false
    })
    .done(function( data ) 
    {
        if(isEmpty(data) || isBlank(data)) {    
            $('.panel-danger').hide("fast")
            //audio.stop();
        }
        else {
            $('.panel-body').html(data);
            $('.panel-danger').show("fast")
            //audio.play();
        }   
    });
}

$(document).ready(function(){

    setInterval(getErrorMessage,2000);
    getErrorMessage();
}); 

Upvotes: 1

Views: 265

Answers (3)

jsist
jsist

Reputation: 5253

You need to specify data type as JSON. According to jQuery docs, You can either use $.getJSON or

$.ajax({
  dataType: "json",
  url: url,
  data: data,
  success: success
});

to load JSON.

Hope it helps

Upvotes: 2

Armen Babakanian
Armen Babakanian

Reputation: 2305

I found the issue. When using $.ajax it doesn’t work if the file has .json extension. It works with .html extension though.

Upvotes: 0

Jmh2013
Jmh2013

Reputation: 2777

You cannot use ../ in a url. It does not work like you expect. You need to either have the full absolute url or starting at the root begin with a / and include the remaining path. For example

http://www.example.com/path/to/my/file.json

Or starting at the root:

/path/to/my/file.json

Upvotes: 0

Related Questions