jerome
jerome

Reputation: 4997

jQuery AJAX json error

Here is my JSON object.

{
        "verbs" : [
        "process",
        "refine",
        "define"
        ],
        "adjectives" : [
        "process",
        "audio",
        "language"
        ],
        "subjects" : [
        "process",
        "development",
        "technique"    
            ]
}

Here is my attempt to access and process the data via the jQuery AJAX method.

jQuery.ajax({
    type : "POST",
    dataType : "json",
    url : "js/tsbtw-object.js",
    success : function(data, statusText){

        var verbArray = data.verbs;

        for(var i = 0; i<verbArray.length; i++){

            var verbTime = Math.floor(Math.random()*1000);

            jQuery("#verb-content").fadeOut(verbTime, function(){
                (this).text(verbArray[i]).fadeIn(verbTime);
            });
        }

    },
    error: function (xhr, ajaxOptions, thrownError){
        alert(xhr.statusText);
        alert(thrownError);
    }   
});

I am receiving two errors in the FireBug console.

invalid label "verbs" : [\n

this.text is not a function (this).text(verbArray[j]).fadeIn(verbTime);\n

I was up fairly late trying to puzzle this out, and thought I would kick it out the community for insight.

Thanks!

Upvotes: -1

Views: 21608

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039498

Try $(this).text instead of (this).text. Also note that as you are in an ajax callback this points to the options for the ajax request, so the text function might not be defined. Instead you could try with:

var _this = this;
jQuery.ajax({
    type : "POST",
    dataType : "json",
    url : "js/tsbtw-object.js",
    success : function(data, statusText){
        var verbArray = data.verbs;
        for(var i = 0; i<verbArray.length; i++){
            var verbTime = Math.floor(Math.random()*1000);
            jQuery("#verb-content").fadeOut(verbTime, function(){
                    $(_this).text(verbArray[i]).fadeIn(verbTime);
            });
        }
    },
    error: function (xhr, ajaxOptions, thrownError) {
        alert(xhr.statusText);
        alert(thrownError);
    }   
});

Upvotes: 2

Related Questions