Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught TypeError: Cannot use 'in' operator to search for '0' in (jQuery)

I feel like this has to do with the AJAX call. Not really sure what is going on. The error is technically being thrown within the jQuery file at line 584 which defines the isArraylike(obj) function.

jQuery(document).ready(function(){
  var width_of_grams = $(window).width();
  var new_pic_height = (width_of_grams /7);
  $("img.gram_photo").css('height', (width_of_grams) / 7);
  $("#instafeed").css('height', 2*new_pic_height);

  $(window).resize(function() {  
    var width_of_grams = $(window).width();
    var new_pic_height = (width_of_grams /7);
    $("img.gram_photo").css('height', (width_of_grams) / 7);
    $("#instafeed").css('height', 2*new_pic_height);
  });


  $("#school_application_fls_center_name").change(function(){
    var center_name = document.getElementById("school_application_fls_center_name").value;
    var formdata = {center: center_name}; 
    $.ajax({
        url: "/application/get_programs_for_center",
        type: "POST",
        data: formdata,
        success: function(response){
          var options = $("#school_application_program_name"); 
          console.log(response);
          $.each(response, function(i,item) {
            options.append($("<option />").val(response[i].id).text(response[i].name)); 
          });
        }
    });
  });
});

Here is the jQuery library code that throws the error:

function isArraylike( obj ) {
  var length = obj.length,
    type = jQuery.type( obj );

    if ( type === "function" || jQuery.isWindow( obj ) ) {
        return false;
    } 

    if ( obj.nodeType === 1 && length ) {
        return true;
    }

    return type === "array" || length === 0 ||
        typeof length === "number" && length > 0 && ( length - 1 ) in obj; //THIS LINE THROWS ERROR
}

N.B. When I remove all of the callback function in the success part of the AJAX request, and just put a console.log to confirm I am making it to the callback successfully it prints my log message and does not throw the error.

like image 211
Thalatta Avatar asked Aug 04 '14 16:08

Thalatta


1 Answers

I think your response is a JSON string. Try passing

dataType: 'json'

in your ajax parameters, or explicitly deserialise it with:

response = JSON.parse(response)

before you call $.each.

Browser session:

// Create some JSON:
json = '["foo", "bar"]'
"["foo", "bar"]"

// Try parsing it, to check it is indeed JSON:
JSON.parse(json)
["foo", "bar"]

// But without parsing it, call $.each on it - we get your error:
$.each(json, function(idx, thing) {console.log(thing)})
TypeError: Cannot use 'in' operator to search for '13' in ["foo", "bar"]

// Now try $.each and JSON.parse - success!
$.each(JSON.parse(json), function(idx, thing) {console.log(thing)})
foo VM410:2
bar VM410:2
["foo", "bar"]
like image 75
sifriday Avatar answered Nov 15 '22 00:11

sifriday