You can pass a php array to index.js file like this:

index.blade.php

<script type="text/javascript">var chart_data =<?php echo chartData; ?>;</script>
{{Html::script('js/pages/index.js')}}

variable chart_data will be accessible in index.js file

Answer from Zeeshan Tariq on Stack Overflow
🌐
Laracasts
laracasts.com › discuss › channels › laravel › how-to-pass-array-from-controller-to-javascript
how to pass array from controller to javascript
December 11, 2017 - in my controller return view('myview', ['array' => $tempArray]); this is my array like this array:24 [▼ 0 => array:2 [▶] 1 => array:2 [▼ "week" => 1 "progress" => "0.18" ] 2 => array:2 [▶] . . . and i want to pass this array to javascript in my view how to get array value??
🌐
Laracasts
laracasts.com › discuss › channels › laravel › how-to-pass-entire-array-from-controller-to-view-in-js
How to pass entire array from controller to view in js?
$path_images = array(); if($detail->path_image1 != null && $detail->path_image1 != ""){ $image = ['size' => Storage::disk('image')->size($detail->path_image1),'url' => $detail->path_image1]; array_push($path_images,$image); } $jsonData = collect($path_images)->toJson(); return view('content',compact('detail','jsonData')); I have dd($jsonData); and it is showing the result format as you stated · "[{"size":41718,"url":"85\/1qc9FO180s6RYjPVmB4REz88ihfVgRtzhbqbYPMf.png"}]" ... Sorry, i think i missed out. Your suggested method at blade view ... is working. However i need to modify the data from controller by converting them to associative array instead of collect($array)->toJson();
🌐
DbeTech
dbestech.com › tutorials › passing-laravel-array-in-javascript
Passing (laravel) Array in Javascript
php array to javascript array, laravel pass array from controller to javascript, php array to json php json_encode to javascript array, pass array to json php, how to pass javascript variable to laravel route
Top answer
1 of 2
1

Can you change:

$data = json_decode($_POST['data'], true);

to:

$data = json_decode(Input::get('data'));

and make sure you have: use Input; above your class extends Controller

See if that works.

Edit: Also make sure your routes (in the Controllers folder) are correct.

2 of 2
0

You should console.log() your javascript by placing the following in you ajax post:

error : function(e){
   console.log(e);
}

You can then see what errors you are getting in your browsers' developers tools panel.

You should also be aware that that Laravel posts require a csrf token unless you have explicitly turned them off, which means you will need to add this token in to your post as well. So you should end up with:

$("#submit").on('click', function() {
    $.ajax({
        url:'/app/Http/Controllers/Search/search_address', // Is this what you meant, is this the route you set up?
        type: 'POST',
        data: {'data': objs, '_token' : '<?=csrf_token()?>'},
        success : function(data){
          // Do what you want with your data on success
        },
        error : function(e){
           console.log(e);
        }
    });
});

Notice that I've embedded php inside the javascript, which is just to illustrate the point. Ideally javascript is kept in it's own files, so you would then need to find a way to pass this token through. I personally use knockoutjs for this type of thing (AngularJS is also popular), but you can easily do something like:

<input type="hidden" id="_token" value="{{ csrf_token() }}" />

in your HTML, then pull this value from inside your ajax request:

data: {'data': objs, '_token' : $('#_token').val()}

EDIT

I've just noticed your url, it looks like you are trying to access the controller directly. You need to set up a route in your routes.php file, such as:

Route::post('/searchAddress', 'YourController@search_address');

Then use:

url: /searchAddress

in your ajax request.

Top answer
1 of 2
1

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

2 of 2
0

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.

🌐
Stack Overflow
stackoverflow.com › questions › 44308834 › send-array-from-controller-to-javascript-in-view-laravel-5-4
php - send array from controller to javascript in view (laravel 5.4) - Stack Overflow
Try adding dd($artArr); in your controller and post the data. ... i don't rendered anything yet, i just need some array list in my script like this: { 1:'name',2:'another name',3:'third' } ... dd($artArr) output is: array:6 [▼ 1 => "firstname ...
🌐
Helperbyte
helperbyte.com › questions › 235150 › how-to-pass-an-array-in-js-from-laravel-controller
How to pass an array in JS from laravel controller? - Laravel - Helperbyte
August 23, 2019 - More answers about "How to pass an array in JS from laravel controller?" 2 answers · lizzie.Schneider answered on August 23rd 19 at 15:05 · For example, so Or something like: return view("test", ["array" => json_encode([1,2,3])]; var arr = {{$array}}; Kimberly_Brekke13 answered on August ...
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 53877555 › how-do-i-pass-an-array-from-a-controller-into-blade-in-laravel-using-javascript
php - How do I pass an array from a controller into blade in laravel using javascript - Stack Overflow
<script src="//code.jquery.com/jquery-3.3.1.min.js"></script> <script type="text/javascript"> $(document).ready(function() { var a; var array = {{!! json_encode($data) !!}}; var i; var b; $('#bulan').keyup(function(){ var bayar=parseInt($('#bulan').val()); for(a=0;a<=array;a++){ if(bayar==array[a]){ i=1; } else{ i=0; } } $('#hasil').val(i); }); }); </script>
🌐
Stack Overflow
stackoverflow.com › questions › 54278104 › passing-array-of-dates-from-controller-to-javascript-in-laravel
Passing Array of Dates From Controller to JavaScript in Laravel - Stack Overflow
I have a DatePicker in one of my Laravel views. I'm trying to pass an array of dates to the DatePicker from the controller to make these dates inactive on the page (the user should not be able to m...
🌐
Stack Overflow
stackoverflow.com › questions › 66853670 › how-to-pass-array-of-objects-to-laravel-controller-through-ajax
jquery - How to pass array of objects to laravel controller through ajax? - Stack Overflow
How to pass an array to ajax and access in controller? 2 · How can I send an array from Controller to JavaScript in Laravel? 0 · How to send array of data to controller with ajax in laravel · 1 · how send array to controller use ajax? 0 · Problem on passing array to ajax request in laravel ·
🌐
Laracasts
laracasts.com › discuss › channels › laravel › how-to-send-array-from-script-to-controler
how to send array from script to controler
(1/1) FatalThrowableError Type error: Too few arguments to function App\Http\Controllers\RabController::saveJson(), 0 passed and exactly 1 expected ... <button class="btn btn-primary" id='save' onclick="sendData()">Import File</button> <script type="text/javascript"> function sendData() { var data = [ 1, 2, 3 ]; $.ajax({ url:'/test', type: 'POST', dataType:'json', contentType: 'json', data: {data:JSON.stringify(data)}, contentType: 'application/json; charset=utf-8', }); } </script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
🌐
Stack Overflow
stackoverflow.com › questions › 50437391 › javascript-array-to-laravel-controller
php - Javascript array to laravel controller - Stack Overflow
May 21, 2018 - Now in my controller, im trying to access that array to then loop on it · Copy<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Configuracion; class OpcionesController extends Controller { public function store(Request $request){ $usuarios = request('users'); error_log($usuarios); } }