I'm working on a laravel project and am trying to pass an array from a controller to javascript. The following code is from my controller.
$dicomfilearray = $dicom->pluck('filename')->toArray();
return view('xray.view')->withDicomfilearray($dicomfilearray);
And below is the Javascript in that's in the blade file I'm trying to pass it to.
var dicomarray = '{{ json_encode($dicomfilearray) }}';
console.log(dicomarray);
And the following is a log result from the Javascript.
["storage/uploads/storeid1/27/10/dicom/c4p4Oco3rU.dcm","storage/uploads/storeid1/27/10/dicom/RNil0NPPzQ.dcm"]
I would like to get a list from this array. Any advice or guidance on this would be greatly appreciated, Thanks.
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 }}';
You can do something like this and this even works if you want to pass the variable to external javascript file. All you have to do is to call the init function with passed parameters.
<script>
$(function () {
init({{ json_encode($dicomfilearray) }} });
function init(dicomfilearray){
//use your variable here
}
</script>
Related
This question already has an answer here:
How to send a variable from JS to my Laravel Controller
(1 answer)
Closed 2 years ago.
I'm extremely new to Laravel (level -0). Our backend guy used it for a web app that we are developing. So after googling i finally figured out how to pass variables from Controller to View. Now i need to pass from View to Controller. I saw that there are some question regarding this but the way its been asked/answered i really dont understand. So what i have now is
Controller :
public function index()
{
$title = "Congratulations";
$messageOne = "You've learned something new!";
$messageTwo = "Remember all the tips!";
return view('pages.index',compact('title','messageOne'));
}
View (where i want the string to be displayed) :
<div>
{{$title}}
<br>
{{$messageOne}}
</div>
These messages (messageOne, and others) will change depending on button click which is controlled via js. I was thinking in the js function i could have a variable set like :
$('thebutton').click(function(){
var buttonclicked = "learning";
})
then send that variable to Controller then in Controller (im not sure how to code it but..) check what the string of buttonclicked variable is and depending on the string return to View the message string. From searches i have to also tweak the Route (which im not sure about as well)?
is that flow possible? otherwise, advice on how i can do this will be appreciated.
UPDATE
the suggested link to another question in the comment helped which answers the question. also, all the answers helped in some way so im not sure which to choose. Do i have to choose only 1?
One way you can send it using the $.ajax() or the other way you can send it using query parameters like so:
<a href={{ route('route-name', ['param 1' => 'Param 1 Value', ......]) }}Click me!</a>
Then in your route define your route as following.
Route::get('/url/{param1}/{param2}/.....', 'ControllerName#MethodName')->name('route-name');
Then go to your controller and define your function like so:
use Illuminate\Http\Request;
public function functionName(Request $request){
// Get your variables from $request
$param1 = $request->param1;
$param2 = $request->param2;
}
In JS you should use ajax for passing data from view to controller for example
$('thebutton').click(function(){
var buttonclicked = "learning";
//her xyz your url
$.get( "xyz", { value: buttonclicked } )
.done(function( data ) {
//write your code after success
});
});
then in controller get the value from ajax request
public function test(Request $request){
dd($request->value);
}
View to Controller. You can post data via ajax call.
or Submit the form data to controller form post method
<form method="post" action="/controller" />
<input type="text" value="100" id="txt" name="txt" />
<button type="submit"/>
</form>
Once submit data 100 go to controller. By this way we can pass data to controller.
JS to Controller Pass data
var pincode = $('#pincode').val();
$.ajax({
type:'POST',
url:"{{ route('post_data') }}",
data:{"_token": "{{ csrf_token() }}","postal":pincode},
success:function(data){
//Success code
}
});
Controller code like below
public function post_data(Request $request)
{
$postal_code = addslashes($request->all()['postal']);
}
Hope it helps
So, currently I am passing values stored in Database MySQL to View (using Controller). I do simple querying ModelName::where()->first();.
I have my data right now in View. I want to use that data in Ajax or Javascript code that I am writing.
I can have 46 values and one way to do this is to have <div id="field1"></div> for 46 times set div style to display:none in css and in Javascript use document.getElementById('field1'); to access the values and finally, do whatever I want to do with it.
But I find this quite long and un-necessary to do as there is no point of printing all the values in html first and then accessing it. How can I directly get {{$data}} in Javascript?
myCode
public function index(Request $request){
$cattfs = Cattf::all();
$cattts = Cattt::all();
$cattos = Catto::all();
return view('/index',compact('cattfs'));
}
View
Nothing in the view. and I prefer it to be none.
Javascript and Ajax
$(document).ready(function()
{
init();
});
function init(){
my_Date = new Date();
var feedback = $.ajax({
url:url,
dataType: "JSON",
type: "GET",
}).success(function(data){
console.log(data);
//I have some data called data from url
//I want some data from controller like: cattf,cattt,catto
//I will combine url data and cattf and do simple arithmetic to it
//finally output to the view.
}).responseText;
}
One good way would be to actually make a small API to get your data. Let's say you wanted to retrieve users.
In the api.php file in your route folder:
Route::get('/posts', function () {
return Post::all();
});
and then you just need to use http://yourUrl.dev/api/posts as your URL sent in your .ajax() call to work with what you need.
I found best solution use this: https://github.com/laracasts/PHP-Vars-To-Js-Transformer
It takes values from controller directly to Javascript.
I am trying to send a row and column number of the clicked cell via GET method.
to php file, where I can check if this cell contains something or not.
For example that the URL will loke like this:
.php?c=3&r=5
I am using:
https://www.w3schools.com/jquery/ajax_get.asp and I have been trying to send data like it is listed on W3schools:
Request "test.php" and send some additional data along with the request (ignore return results):
$.get("test.php", { name:"Donald", town:"Ducktown" });
I am doing it like this:
$(document).ready(function() {
$("td").click(function(event) {
var clickedBtnID = $(this).attr('id');
values=clickedBtnID.split('.');
var row=values[0];
var col=values[1];
$.get("info.php", {"row":row, "col":col});
I was looking at some other examples on StackOverFlow, like:
How to send data to PHP file using JQuery Ajax?
I would like to say it that info.php is the diferent .php file, as the one we are working from. And another thing is that the best way to do this, would be to do it without refreshing the page. So is Ajax call the best way for this? I have tried many different things, but it seems like I can't send the data via GET method.
I'm not 100% sure I understand what you're looking to do, but I'll try to help!
Have you tried something like this? In your js file:
$.get("info.php?c=3&r=5");
Then in your PHP file:
//Retrieve the variables
$c = ($_GET["c"]);
$r = ($_GET["r"]);
//Then do what you need to do with $c and $r
Let me know if that helps.
I have tried this:
$.ajax({ url: 'info.php',
data: {'row':row, 'col':col},
type: 'GET',
success: {}
});
And it works perfectly. I don't know why the jquery $.get didn't work.
I'm working with symfony2 and I need to send data from javascript function to the controller.
This works when there is no data to send in the url
document.location.href="{{path("modifMalade")}}"
But I don't know how to do to put parameter on it?
All you need is just to read the docs:
http://symfony.com/doc/current/reference/twig_reference.html#path
In your case, it could look like this:
document.location.href="{{ path("modifMalade", {'param1': 'value1'})}}"
So in my controller logic, I build up a large array of data, which I json_encode into a variable which is passed to my view. However, I want this data to be sortable on the client side using JavaScipt--I don't think the details of how the sorting is done are relevant but I'm curious what the best way is to get my array from PHP to Javascript. Currently, I'm thinking of just having a tag in my html like
<script type="text/javascript">var jsonData = <?php echo $myData ?>; </script>
where myData is the encoded array I made in PHP, and then jsonData is available for me to use anywhere else.
However, this would mean the entire ugly array would show up in the source code of my page. This isn't a security concern or anything, but I feel that there must be a better way to do this that's not quite as "ugly".
Any advice is appreciated.
You have two options.
If you don't want 'ugly' HTML source, you can query your application with ajax and have your json array be stored in a variable. This can be accomplished with a simple route and controller method.
In your routes.php
Route::get('api/myData',array('as'=>'api.myData','uses'=>'MyController#getMyData'));
In your MyController.php
public function getMyData() {
return whateverYouWant();
}
You can then do an ajax request to route('api.myData')
The route method is a global function which is available in your view. It will take the named route, api.myData and generate a URL for it.
The other option is as you described, passing the array to your view.