Codeigniter:使用ajax将响应从Google API传递到db时出错

I am getting data from Google API while loading a view. PHP code of my page to get data is under <body>. Now I want to pass this data from view to controller so that I can save it to database.


Getting response while loading the page. (this code is in view)

$req = new Google_HttpRequest("https://www.google.com/m8/feeds/contacts/default/full?max-results=500");
              $val = $client->getIo()->authenticatedRequest($req);
              $xml = simplexml_load_string($val->getResponseBody());
              $result = $xml->xpath('//gd:email');
foreach ($result as $title) {
                echo $title->attributes()->address . "<br>";
                array_push($gmailContacts, $title->attributes()->address);
              }

so if I do print "<pre>" .print_r($result,false). "</pre>"; I can print all the emails on the page.
AJAX call to save $gmailContacts to database.

<script type="text/javascript">
     var contacts = <?php echo json_encode($gmailContacts)?>;
     $(document).ready(function(){
        $.ajax({
            url:'saveGmailContacts',
            data:contacts,
            type:'POST',
            success: function(msg){

            }

        });
     });
    </script>

I am getting Severity: Notice --> Undefined variable: gmailContacts for the variable