Skip to content
Advertisement

Parsing ajax JSON response in a loop

So I try to parse json response from ajax request with JSON.response, but it doesn’t work

the example of the json response from my api looks like this :

{"cn":"3335621215844","status":5,"proxy":"207.154.231.213:8080","error":"Received HTTP code 400 from proxy after CONNECT"}

here’s the error from the broswer debug :

Uncaught SyntaxError: Unexpected token o in JSON at position 1
    at JSON.parse (<anonymous>)

here is my code :

function cn_doCheck() {
    var proxy_counter = 0;
    var cn_list = $("#cn_input").val().split('n');
    var proxy_list = $("#proxy_input").val().split('n');
    var i=0;
    if (cn_list!="" && proxy_list!="") {
        $.each(cn_list, function(index, value){
                if (i>proxy_list.length) {
                    i=0;
                }
                $.ajax({
                    type : 'post',
                    data : {
                        cn: value,
                        proxy: proxy_list[i]
                    },
                    url : 'api_test.php',
                    async : true,
                    beforeSend: function(response){
                        $("#loader").empty();
                        $("#loader").append("Checking "+cn_list.length+" in total");
                    },
                    success: function(response){

                    },
                    complete: function(response){ 
                        var result = JSON.parse(response);                       
                        $("#cn_live").append(result.cn+"|"+value+"|"+proxy_list[i]+"n");
                        i++;
                    }
                });
            });
    }else{
        alert("Card/Proxy list can't be empty!");
    }
}

Advertisement

Answer

Seems like response is already a JavaScript object not a string, you do not need to parse that again.

Update: Ajax success() only gets called if your web server responds with a 200 OK HTTP header – basically when everything is fine. Where as, complete() will always get called no matter if the ajax call was successful or not – maybe it outputted errors and returned an error – complete() will still get called.

Please execute your code inside success call back to avoid unwanted scenario.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement