Andresson
Andresson

Reputation: 13

Ajax request to Laravel 4 returns 200 ok but method always return fail

IM doing i simple request to a Laravel web service.

This is the response in the controller:

data = array(
 'name' => 'Dummy',
 'size' => 'XL',
 'color' => 'Blue'
 );
 return Response::json($data);

Using POSTman i can see that everything looks fine: URL:

Response:
{"name":"Dummy","size":"XL","color":"Blue"}

HEADERS:
Cache-Control →no-cache
Connection →Keep-Alive
Content-Type →application/json
Date →Mon, 04 Nov 2013 15:15:27 GMT
Keep-Alive →timeout=5, max=100
Server →Apache/2.4.6 (Ubuntu) PHP/5.5.3-1ubuntu2
Transfer-Encoding →chunked
X-Powered-By →PHP/5.5.3-1ubuntu2

Then i go to a simple javascript call, like:

$.getJSON("http://localhost/myapi/public/content", function(json) {
                console.log("log " + json.name);            
            });

or

$.ajax({ 
type: 'get', 
url: 'http://localhost/myapi/public/content',
 dataType: 'json', 
async: false, 
success: function(data) { alert("success"); }, 
error: function() { alert("error"); } });

Firefox console returns a "200 OK", but Javascript always report an error.

where is the problem??

SOLUTION:

Laravel Response is not sending by default

header('Access-Control-Allow-Origin: *');

Just added and now im getting the json data correctly.

Upvotes: 1

Views: 2681

Answers (1)

Adam Elsodaney
Adam Elsodaney

Reputation: 7808

Another solution is to add an App::after middleware, in app/filters.php

App::after(function($request, $response)
{
    $response->headers->set('Access-Control-Allow-Origin', '*');

    // You may also require these additional method calls
    $response->headers->set('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
    $response->headers->set('Access-Control-Max-Age', '1000');
    $response->headers->set('Access-Control-Allow-Headers', 'X-Requested-With, Origin, X-Csrftoken, Content-Type, Accept');

    return $response;
});

Upvotes: 1

Related Questions