views:

179

answers:

3

I am using jQuery-1.4.2 with CakePHP and a few days ago I had this working fine but now it isn't. I don't remember changing anything. I am taking the URL generated from the javascript and putting that directly into the browser and I am able to see the results in my browser however javascript is just getting a return value of null. Anyone have ides?

<script type="text/javascript">
    $(document).ready(function() {
        var url = "http://mysite.com/vote/";

        $.get(url + "view/" + $(".votediv").attr("id")  +".json" ,
                function(data,textStatus, XMLHttpRequest) {
                    console.log(data);
                    console.log(textStatus);
                    console.log(XMLHttpRequest);
                    if(data.Votes.votecast != undefined) {

                        $(".vote."+data.Votes.votecast).addClass("current");
                    }
                },"json");
        $('.vote').click(function () {
            if ($(this).hasClass("current")) {
                alert("You have already voted for this option!");
            } else {

                var error = false;

                if ($(this).hasClass("up")) {

                    $.post(url + "edit/" + $(".votediv").attr("id")  +".json", {'vote': 'up'},
                        function(data) {
                            console.log(data);
                        }, "json");
                    //alert("Voted Up!");
                }
                else if($(this).hasClass("down")) {
                    $.post(url + "edit/" + $(".votediv").attr("id")  +".json", {'vote': 'down'},
                        function(data) {
                            console.log(data);
                        }, "json");
                    //alert("Voted Down!");
                }
                //removes all the votes
                $(this).parent().children().removeClass("current");

                if(!error) {
                    $(this).addClass("current");
                } else {
                    alert("There was an error");
                }
            }
            return false;
        });
    });
</script>

Output from debug console in browser is

null
success

XMLHttpRequest
    abort: function () {x&&h.call(x);
    onabort: null
    onerror: null
    onload: null
    onloadstart: null
    onprogress: null
    onreadystatechange: function () {}
    readyState: 4
    responseText: ""
    responseXML: null
    status: 0
    statusText: ""
    upload: XMLHttpRequestUpload
    withCredentials: false
    __proto__: XMLHttpRequestPrototype

TypeError: Result of expression 'data' [null] is not an object.
Failed to load resource: cancelled

The output my php script does is

{"Votes":{"votecast":"up","sumvotes":"1","totalvotes":"1"}}

I'm wondering why I keep getting null data. Any ideas? I am not doing a cross domain query. I am only querying a script on my domain.

EDIT:

I have changed the JSON output to display as {"Votes":{"votecast":"up","sumvotes":"1","totalvotes":"1"}} and jsonlint.com says it is valid JSON however it still does not work and jQuery says the result is null.

A: 

I'm not sure why it's not returning data, but you might want to make sure the url $.get is going to is the one you think it is. You could use alert(url + "view/" + $(".votediv").attr("id") +".json"); for example - of course you can also see that in Firebug.

I believe $.get can sometimes return a status of 'success' even if it's not actually loading a url.

Alex King
I have stated in my above post that I have already confirmed the url is correct by outputting the url and testing it manually.
jostster
A: 

The square brackets enclosing the JSON would give jQuery some trouble. To prove it, I used the following HTML file and two PHP test case files.


<!DOCTYPE html>
<html>
<head>
<title>SO</title>
<script
  type="text/javascript"
  src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;
</script>
</head>
<body>
Output: <span id="output"></span>
<script type="text/javascript">
$.get(
  "/SO.php",
  function(data){
    $('#output').html(data.Votes.votecast);
  },
  "json"
);

</script>
</body>
</html>

First Case PHP [FAILS, no value shown in span. id="output"]


<?php
echo '[{"Votes":{"votecast":"up","sumvotes":"1","totalvotes":"1"}}]';

Second Case PHP [PASSES, value "up" shown in span, id="output"]


<?php
echo '{"Votes":{"votecast":"up","sumvotes":"1","totalvotes":"1"}}';
jtp
@jtpresta I have changed the output to `{"Votes":{"sumvotes":"1","totalvotes":"1","votecast":"up"}}` and am still getting the same null issue.
jostster
fyi jsonlint.com shows that [{"Votes":{"votecast":"up","sumvotes":"1","totalvotes":"1"}}] is proper json as well.
jostster
@jostster - Awesome. Thank you for the heads up; I did not know about jsonlint.com. That's one of the great things about StackOverflow: everyone benefits. Glad you solved the issue!
jtp
+1  A: 

I see that you are specifying the URL in the start of your script:

var url = "http://mysite.com/vote/";

Could it be that your are violating the same origin policy? Ie. that you can only do ajax calls to the originating server.

That would give you the symptoms you describe: a blank response, but the URL works when tried manually through the browser.

Magnar
As mentioned in my question I have stated that I am querying a script on my server and not doing any cross domain query.
jostster
@Magnar it looks like you are right. It turns out if I use www in my browser since I don't have www specified in my jQuery url it causes that issue. Why would www violate the same origin policy? Is there a jQuery function to get the browsers base url so I can use that?
jostster
Same origin triggers on different subdomains as well. You can use relative URLs, just go to "/vote/".
Magnar