3

When i am trying each loop under Ajax call, i am getting error as:

TypeError: invalid 'in' operand e

Below is my Ajax call code

    $.ajax({
        type: "POST",
        url: "/admin/counselormanagement/centername",
        data: 'groupId='+valueSelected,
        async: true,
        success: function(arrCenter) {
            $.each(arrCenter, function( intValue, arrValue ) {
                console.log('<option value="' + arrValue['ID'] + '">'+ arrValue['CenterName'] +'</option>');
            });
        }
    });

Response which i am getting back from server is :

Array (
[0] => Array
    (
        [ID] => 4
        [CenterName] => test2
        [ParentName] => 2
        [Parent] => 3
        [GroupName] => test
        [Type] => 1
    )

[1] => Array
    (
        [ID] => 8
        [CenterName] => test21
        [ParentName] => 2
        [Parent] => 3
        [GroupName] => test
        [Type] => 1
    )
 )

I am using PHP as backend, whose code is :

$arrCenterName   = array();
$objCenterMapper = new Application_Model_CentersMapper();
$arrCenter = $objCenterMapper->seekCenters($_POST['groupId']);
print_r($arrCenter[0]);
die();
7
  • 2
    Did you try to parse you data as json instead of print_r on php ? Commented Dec 15, 2015 at 16:28
  • This code looks fine. can you do a console.log(arrCenter)? Commented Dec 15, 2015 at 16:30
  • console.log(JSON.stringify(arrCenter)) check. Please attach what type of json you are getting. Commented Dec 15, 2015 at 16:30
  • It is a php object. You need a javascript object instead Commented Dec 15, 2015 at 16:31
  • 2
    yes use dataType: "json" Commented Dec 15, 2015 at 16:33

2 Answers 2

1

Use json_encode() in PHP to return response. And your JS code should be like:

PHP:

$arrCenterName   = array();
$objCenterMapper = new Application_Model_CentersMapper();
$arrCenter = $objCenterMapper->seekCenters($_POST['groupId']);
echo json_encode($arrCenter[0]);
die();

JQuery:

$.ajax({
    type: "POST",
    url: "/admin/counselormanagement/centername",
    data: 'groupId='+valueSelected, 
    dataType: 'json', 
    async: true,
    success: function(arrCenter) {
        $.each(arrCenter, function( intValue, arrValue ) {
            console.log('<option value="' + arrValue.ID + '">'+ arrValue.CenterName +'</option>');
        });
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0

Try to echo out your object using json_encode instead:

<?php
$arrCenterName   = array();
$objCenterMapper = new Application_Model_CentersMapper();
$arrCenter = $objCenterMapper->seekCenters($_POST['groupId']);
echo json_encode($arrCenter[0]);
die();

Comments

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.