0

This is my sample JSON response:

[{"id":11137,"name":"Agra"},{"id":11138,"name":"Albizzate"}]

and i need to iterate each array object and print id and name:

        $.ajax({
            url: '{{ path('ajax_provinces') }}',
            type: 'POST',
            dataType: 'json',
            data: {region_id: this.value},
            success: function(provinces) {},
            error: function() { alert("error"); },
            complete: function(provinces) {
                $('select#regions ~ span > img').fadeOut('slow');
                $.each(provinces, function(key, val) {
                    alert(key + ": " + val);
                });
            }
        });

The problem is i'm gettig strange results: function names, function bodies and other internal stuff from jQuery. It seems like it's iterating through jQuery library functions! Any clue what's going on?

2 Answers 2

2

The problem is that the complete callback doesn't get passed the returned data as an argument:

complete(jqXHR, textStatus)

A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror").

(from the docs)

Presumably the weird key/values you're seeing are the attributes of the jqXHR object.

You need to handle the returned data in success, not complete. My understanding is that complete is generally used for actions that should happen regardless of whether the AJAX request successfully returned data (e.g. hiding a loading animation).

0

You need to handle the returned data in success, not complete. Complete is used when you need to trigger a function after AJAX call is complete. On success you will get the data sent from server as

success:function(data){

/// data is JSON object. Now iterate it here 

var i;
    for(i in data){
        alert('the Id ='+data['id']+' the name '+data['name']);

      }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.