Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can not get json response using $.getJSON

I am currently developing a Ruby on rails 3 application.

My server controller function render a json object as response:

class DaysController < BaseController
   ...
   def the_days
     ...
     render :json => days
   end
end

In my javascript,I use the following code to get json response from server( that's from the_day function in controller)

$.getJSON(  
             url,  
             {emp_id: emp_id},
             function(data) {
                     var result = data.response;
                     alert(result) 
                     alert(data)
                 },
                 "json"
        );

I use firefox browswer and checked with Firebug, in Firebug Net->XHR, I see the Get request is successful, and the response "days" is there. That's both request and response are successful.

But I did not see the two alert window defined in the above $.getJSON function, why? Why I can not get the response "days" in $.getJSON function??

-----------------Edited------------------

I edited my code to this one:

$.ajax({
            url: myURL,

            type: 'GET',

            data: {
                emp_id: emp_id
            },

            dataType: "json",

            success: function(data) {
                alert("hi");
                alert(data)
            }
        });

When I run this code, the browser is stuck at success: function(data)

like image 377
Mellon Avatar asked Dec 08 '25 12:12

Mellon


1 Answers

If data is coming back null, but the response was otherwise successful, I'd say that you're sending the request in a manner that violates the Same Origin Policy.

The request needs to be sent to the same host/port/protocol that served the original page.

If this is only an issue in your development environment, you can test in Chrome by launching it from a Terminal application with --disable-web-security.


EDIT: Try changing the parameter name from data to something else, like dat or whatever.

Then try an alert:

alert( dat );

I've heard of some browsers having trouble with the data parameter when you utilize the data property of an AJAX call.

like image 114
user113716 Avatar answered Dec 11 '25 01:12

user113716



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!