HessamSH
HessamSH

Reputation: 357

How can I send an array from Controller to JavaScript in Laravel?

There is data that needs to be sent to View from Controller. From what I've read, this is the way to do it, but the alert doesn't show anything in the page. Here's the method I use in Controller:

public function provider() {
    $sites = array(
    0 => "Mon", 
    1 => "Tue", 
    2 => "Wed", 
    3 => "Thu",
    4 => "Fri", 
    5 => "Sat",
    6 => "Sun",);
    return ($sites);
}

And here is the javascript piece I use in View:

<script type="text/javascript">
    function provider() {
        $.ajax({
            type: "POST",
            url: '/resultsprovirder',
            cache: false,
            success: function() {
                alert(data);
                alert("success");
            },
            error: function() {
                alert(data);
                alert("error");
            }
        });
     };
</script>

Also, is there a more secure way than AJAX?

Upvotes: 2

Views: 3133

Answers (2)

Shreeraj
Shreeraj

Reputation: 767

Try this way:

In your controller

public function provider() 
{

  $sites = [
    0 => "Mon", 
    1 => "Tue", 
    2 => "Wed", 
    3 => "Thu",
    4 => "Fri", 
    5 => "Sat",
    6 => "Sun"
  ];

  $response = [
     'msg' => 'Success',
     'status' => 1,
     'data' => $sites
  ];

  return response()->json($response);

}

In your view file

<script>
    $(document).ready(function(){
        getdata();
    });

    function getdata(){
       var ajx = new XMLHttpRequest();
       ajx.onreadystatechange = function(){
           if(ajx.readyState == 4 && ajx.status == 200){
               var demo = JSON.parse(ajx.responseText);
               console.log(demo.data);
           }
       }

       ajx.open("GET",'/resultsprovirder',true);
       ajx.send();
    }
</script>

You will get your data in demo.data or check your console.

Upvotes: 0

Mohammad GH
Mohammad GH

Reputation: 41

At first your code structure if wrong .lets try a simple example.

Example

In MVC frameworks like laravel you should define your routes :

yourproject/app/HTTP/routes.php

Route::get('/',PageController@home);

Now lets build our Controller: In your teminal (cmd in windows):
php artisan make:controller PageController

And your controller file ( yourproject/app/http/controllers/PageController.php ) in your class :

public function home()
    {
        $sites = array(
            0 => "Mon",
            1 => "Tue",
            2 => "Wed",
            3 => "Thu",
            4 => "Fri",
            5 => "Sat",
            6 => "Sun",);
        return view('home',['Sites' => $sites] );// This Line says that your home view is in yourproject/resources/views/home.blade.php and pass $Sites to that file
    }


Finally.in yourproject/resources/views/home.blade.php :

<script>
    var sites= @json($Sites);//@json is Blade shortcode for json_encode
</script>

Now you can use your sites var in your page js!
Ajax used when you want exchange datas between server and client without refreshing all of the page and not for sending data from controller in first of load ! and in parentheses : if you want use ajax in laravel you should set AjaxSetup for avoiding CSRF attacks.before your ajax request :

 $.ajaxSetup({
                  headers: {
                      'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                  }

This is The most secure way to send var to your views . Hope this help you,
Best Regard,Mohammad

Upvotes: 1

Related Questions