Paul A.
Paul A.

Reputation: 597

Send a request to a route in Symfony2 using Javascript (AJAX)

I have a working prototype Symfony2 RESTful webservice which I am still working on and I am trying to figure out how a client can send JSON or consume JSON data from the webservice. All I need is an example(s) on how to send a request or post data to it and I can figure out the rest. From my browser, if I visit http://localhost/app_dev.php/users.json, I get the correct result from my database as JSON, e.g. [{"id":1,"username":"paulo","username_canonical":"paulo","email":"[email protected]","email_canonical":"[email protected]","enabled":true,"salt":"66r01","password":"UCxSG2v5uddROA0Tbs3pHp7AZ3VMV","last_login":"2013-12-03T13:55:15-0500","locked":false,"expired":false,"roles":[],"credentials_expired":false,"first_name":"Monique","last_name":"Apple"}, ... etc.

All other routes are working correctly and I can get the same result by using httpie or cURL. Now, the problem I am trying to solve is to get the same JSON data using AJAX (and mobile iOS, Android, etc later). Here is my attempt at using AJAX JS:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript">


        $.ajax({
            dataType: "json",
            type: "GET",
            url: "http://192.168.1.40/symfony/web/app_dev.php/users.json",
            success: function (responseText)
            {
                alert("Request was successful, data received: " + responseText); 
            },
            error: function (error) {
                alert(JSON.stringify(error));
            }
        });
</script>

The AJAX alerts the following results which indicates an error: {"readyState":0,"responseText":"","status":0,"statusText":"error"}

What am I doing wrongly and how can I solve the problem. Kindly give an example.

Upvotes: 0

Views: 572

Answers (1)

kinghfb
kinghfb

Reputation: 1021

This is a cross-domain request issue. You need to make the request to the same domain you are on. This is a browser-level security feature.

For example, you can only request URLs on http://192.168.1.40 if you are currently ON http://192.168.1.40. This means that a request from http://192.168.1.39 (for example) won't work

Upvotes: 2

Related Questions