1

I am trying to get JSON data from API on Laravel 5 , The route gives me correct Data in the browser but when trying to access this route in JQuery it failed. the route is: http://localhost:8000/search/student/all

worked finally in the browser and the data is displayed in json format but this script failed:

 $(document).ready(function(){
     $("button").click(function(){
        $.getJSON("http://localhost:8000/search/student/all", function(result){
            $.each(result, function(i, field){
                $("div").append(field + " ");
            });
        });
    });
});

I replaced localhost:8000 with 127.0.0.1:8000 but nothing changed.

Note: I generated the json response using Laravel

$students=App\Student::all();
return response()->json($students);
GantTheWanderer
  • 1,255
  • 1
  • 11
  • 19
mahmoud
  • 23
  • 6

2 Answers2

1

In jquery you can do like something below

$.get( "http://localhost:8000/search/student/all", function(data ) {
  var obj = jQuery.parseJSON(data);
  console.log(obj);
});

Another possibility use jsonp

JSONP is really a simply trick to overcome XMLHttpRequest same domain policy. (As you know one cannot send AJAX (XMLHttpRequest) request to a different domain.)

$.ajax({
     url:"http://localhost:8000/search/student/all",
     dataType: 'jsonp', 
     success:function(data){
          var obj = jQuery.parseJSON(data);
          console.log(obj)
     },
     error:function(){

     }      
});

Basic example of using .ajax() with JSONP?

Community
  • 1
  • 1
sumit
  • 15,003
  • 12
  • 69
  • 110
  • thanks but the problem is still the same working fine on browser but in jquery no results retrieved. – mahmoud Jan 24 '17 at 00:26
  • ok the log give me this error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/search/student/all(Reason: CORS header 'Access-Control-Allow-Origin' missing). – mahmoud Jan 24 '17 at 00:35
  • you can accept it as correct answer , if it helped you . This is how stack overflow works :) – sumit Jan 24 '17 at 00:58
  • @sumit the `toJson` isn't necessary when passing a collection to be printed as a JSON response. What OP had for their PHP code is fine. – deefour Jan 24 '17 at 02:16
  • Yea , his problem was related to "CORS header" . I have already edited my post – sumit Jan 24 '17 at 02:18
0

Try like this...

<script type="text/javascript">
     $(document).ready(function(){
 $("button").click(function(){
    $.getJSON("http://localhost:8000/search/student/all", function(result){
        $.each(result.students, function(i, field){
            $("div").append(field.name + " ");//name is database field name such as id,name,address etc
        });
    });
});
</script>

PHP

$students=App\Student::all();
echo json_encode($students);//or return $students->toJson();
Hikmat Sijapati
  • 6,869
  • 1
  • 9
  • 19