vkGunasekaran
vkGunasekaran

Reputation: 6814

jsonp cross domain request response gives null while parsing

I tried to make a cross domain request using jquery. this is how client side will looks like,

<script src="js/jquery-1.6.2.min.js"></script>
<script type="text/javascript">
$(document).ready( function(){
    $.ajax({
        type: 'GET',
        url: "http://www.xserver.com/xdomainhandler.php",
        processData: true,
        data: {
            type:"gotohell"
        },
        dataType: "json",
        success: function (data) {
            myglob=data;
            var repo=JSON.parse(myglob);
            alert(repo.type);
        },
        error : function(XMLHttpRequest, textStatus, errorThrown){
            alert('ends up in error state');

        }
    });
});
</script>  

and the server page code which receives this request will look like this:

<?php
header('Access-Control-Allow-Origin: *');  
header('Expires: ' . gmdate('r', 0));
header('Content-type: application/json');
session_cache_limiter('nocache');

$arr = array ('response'=>'success','comment'=>'test comment here','type'=>$_GET['type']);
echo json_encode($arr);
?>

But when i completed the request/response process i got nothing in the 'repo' variable. i checked the response using firebug and it shows response like,

{"response":"success","comment":"test comment here","type":"gotohell"}

also i checked myglob variable in DOM panel of firebug it shows,

Object { response="success", comment="test comment here", type="gotohell"}

but when i parsed the myglob to repo, it shows nothing.. where i'm going wrong. can somebody help me. Thanks!

Upvotes: 2

Views: 646

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

Because you supplied dataType: 'json' jQuery will already have parsed the response - parsing it again will cause errors. Remove the following line:

var repo = JSON.parse(myglob);

Upvotes: 2

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76880

You don't need to parse it as jQuery parses it for yo so avoid

        var repo=JSON.parse(myglob);

and just call

  alert(data.type);

Upvotes: 3

Related Questions