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 OverflowCan 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.
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.
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
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.
You can send it as a request parameter
function check() {
var array = [1, 2];
window.location.href = "{{URL::to('/modulos/contas_ti/gerar_protocolo')}}" + "?array[]=1&array[]=2";
}
Controller :
public function gerarProtocolo(Request $request) {
$data = request('array');
return view('modulos.contas-ti.gerar_protocolo', compact('data'));
}
A better way to do is, create one form with hidden variable than when you are calling you javascript check() function, store the array value in the hidden variable and than use javascript form.submit() method.
You can make ajax call in frotend, and backend do like this
$dicomfilearray = json_encode($dicom->pluck('filename'))->toArray());
return view('xray.view')->withDicomfilearray($dicomfilearray);
when you working in javascript and need data in javascript then why you need view part. Actually, I just read your comment.
If in Ajax
so I suggest send array with json_encode and populate that data into view with javascript.
simply right below in controller
response()->json(['status'=>200,'data'=>$dicomfilearray])
Update So ,you not sending ajax request so, simply. do like below.
controller:-
$data = json_encode($dicomfilearray);
return view('your-view',compact('data'));
javascript
var dicomarray = '{{ $data }}';
In Laravel 5, use response() to return a JSON object from an AJAX call, like this:
return response(['title' => $title, 'description' => $description]);
In your Javascript, you would then access this data using object notation, so:
$.get("URL", function(data){
var title = data.title;
var description = data.description;
// Etc, etc
});
public class AssignmentViewModels
{
public string title { get; set; }
public string id { get; set; }
public string class { get; set; }
public string date { get; set; }
public string description { get; set; }
}
public JsonResult updateAssignment(string title, string id, string class, string date, string description)
{
var model = new AssignmentViewModels();// if you have a list of data return, make "List<AssignmentViewModels>()" ,& in Ajax sucess method, make a foreach loop & collect the data.
model = repository._update(title,id,class,date,description);//return updated data
return Json(model, JsonRequestBehavior.AllowGet);
}
var URL = ResolvedUrl.replace('ActionName', 'updateAssignment').replace('ControllerName', 'YourController');
var data = { title: title, id: id, class: subject, date: date, description: description };
$.get(URL, data, function (result) {
if ($('#h2')[0]) {
$('#h2').val(result.title);// no need to use JSON.parse
}
}
Use this package https://github.com/laracasts/PHP-Vars-To-Js-Transformer
public function index()
{
JavaScript::put([
'foo' => 'bar',
'user' => User::first(),
'age' => 29
]);
return View::make('hello');
}
HTML
<input type="hidden" id="club-id" value="<?php echo $club->id ?>" />
Javascript
var club_id = $('#club-id').val().trim();