Imesh Chandrasiri
Imesh Chandrasiri

Reputation: 5699

Jquery .ajax not working as expected

I've got the following code to call a json web service in a separate functions.js file.

function getMajorGroups(){

var element = $(".item-group-button");

$.ajax({
    type:"GET",
    url:"localhost:6458/posApplication/getAllMajorGroups",
    data:"{}",
    contentType:"application/json; charset=utf-8",
    dataType:"json",
    done:successResult(majorGroups),
    fail:errorResult(error)
});
}

function successResult(majorGroups){
    var mGroups = response.d;
    $("#item-groups").empty();

    $.each(majorGroups ,function(){
        var h3 = $('h3').append(majorGroups.code);
        element.append(h3);
        $("#item-groups").prepend(element);
    });
}

function errorResult(error){
    alert("error");
}

When I run the web page and I use firebug to trace the steps I can see the script is executed. But it does not execute the success or failure code inside the ajax call. Am I doing anything wrong here?

Below is an example of the string which the service return.

{"majorGroups":[{"update":"false","hasMore":"false","status":"A","description":"Beverage","majorGroupId":"48","code":"Beverage"},{"update":"false","hasMore":"false","status":"A","description":"Laundry","majorGroupId":"51","code":"Laundry"},{"update":"false","hasMore":"false","status":"A","description":"Cigarette","majorGroupId":"50","code":"Cigarette"},{"update":"false","hasMore":"false","status":"A","description":"Food","majorGroupId":"47","code":"Food"},{"update":"false","hasMore":"false","status":"A","description":"Health Center","majorGroupId":"52","code":"Health Center"}],"failure":"false"}

Upvotes: 2

Views: 154

Answers (1)

Marek
Marek

Reputation: 1878

$.ajax has no property named failoure. error should be used so it looks like error: errorResult

Besides that check that request is made via Network tab in Chrome dev tools or some similar tool. Check what is in the the raw response and make sure that is what you wanted. If request failed you will see way or at least have error code.

If everything is fine so far then make sure your adding DOM elements when DOM is ready so wrap your stuff with $(function(){ /* your stuff here */ })

Edit:

That's not the way done and fail should be used. jQuery ajax call returns promise.

$.ajax({
  url : "..."
  /* omitted */
}).done(successCallback).fail(failCallback)

where successCallback can be either function name like your defined succes function or just anonymous function like

.done(function(response){
  // do stuff with response
} 

I think you should carefully read jQuery documentation.

Also your $.each call is kinda broken - you skipped parameter in function provided to $.each

Upvotes: 2

Related Questions