Laravel : How to pass variable from View (javascript) to Controller? [duplicate] - javascript

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

Related

Insert data to MySQL with Ajax in Laravel

I have a JS variable which store a JSON value in my blade view and I want to insert it to MySQL in Laravel project. But I don't know how to write it right. This is what I tried in my blade view:
<body>
<div id="fb-editor"></div>
<div id="saveToDatabase">
<button id="saveBtn" type="button">Save To Database</button>
</div>
</body>
<script>
var formBuilder = $('#fb-editor').formBuilder();
$("#saveBtn").click(function() {
var mFormData = formBuilder.actions.getData(); //my JSON data
$.ajax({
type: 'POST',
url: '/saveToDatabase',
data: {"mFormData":mFormData}
}).done(function (msg) {
alert("Data saved!");
});
});
</script>
But when I run it, it appear error said: jquery.js:8630 POST http://localhost/saveToDatabase 404 (Not Found).
How I can fix this?
Thank you very much!
First, enter your database details on .env file.
You need to use two routes. One for the blade file to render and another for the api request.
On routes/web.php, define your route,
Route::get('/', function(){ return view('app');});
Create app.blade.php in resources/views/ folder with your HTML code.
On routes/api.php, define your route like this
Route::post('saveToDatabase','HomeController#saveToDb')
Next, you need to create saveToDb method on the HomeController.
Open App\Http\Controller\HomeController.php
Create a new method
public function saveToDb()
{
// Database Insertion Code goes here
}
Laravel Provide CSRF Protection to the POST request. So add Exception to this route by adding it in the App\Http\Middleware\VerifyCSRFToken.php
protected $except = [
'api/*'
];
For the insertion operation, we can do this with the help of the model.
So first create Form.php in App\ folder.
Inside that, we specify the fields of the database.
<?php
use Illuminate\Database\Eloquent\Model;
class Form extends Model
{
protected $fillable = [
"key", "data"
];
protected $hidden = [];
}
Next, we can use this model to insert data to the Form table.
In your HomeController.php at the top
use App\Form;
use Request;
Now we can update the saveToDb function that we write before.
public function saveToDb()
{
// Request all the post data
$req = Request::all();
// From that post data store key and data part to form table
Form::create($req);
}
If you have any issue in route, controller or model. Refer Laravel official docs: https://laravel.com/docs/5.8/routing
And this one is also useful to get started to laravel. https://laracasts.com/series/laravel-from-scratch-2018
The route is not selected correctly. http://localhost/saveToDatabase is not find for do something

How to get array from controller on javascript blade in Laravel

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>

How to make a "condition if" in php when the <span> is changed? [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 5 years ago.
View
<input type="text" id="textToDisplay" />
<br />
<input type="button" value="Add message" onClick="showMessage()" />
<br />
<span id="messageSpan"><span>
JS
function showMessage() {
var message = jQuery("#textToDisplay").val();
jQuery("#messageSpan").text(message);
}
By the way, i'm using laravel. Basically, what I want to do is, if user input 22 then it will shows success message. All these do it in php without changing/adding in js. jsfiddle example
Basically my idea is like this,
<?php
if(<span id="messageSpan"><span> == 22)
success
else
<span id="messageSpan"><span>
?>
You cannot do this like the way to describe it above. You either have to do in using only javascript / jquery or you use both languages (php and javascript) and
sent an ajax request to your server do something there and return some data to your client (javascript) and show that in your view.
I added some comments so that the process is better to understand, if you have any questions just ask.
I would do this using ajax so you are going to use javascript and php which should be better for you right now.
So this is your html markup:
<input type="text" id="textToDisplay" />
<br />
<input type="button" value="Add message" onClick="showMessage()" />
<br />
<span id="messageSpan"><span>
And now you are going to sent the input value using ajax to your controller, like this:
$(document).ready(function(){
// on each key up we are going to sent the value later you should probably change this and sent the value after you click on a button
$('#sentMessage').keyup(function(){
// this holds the current value of the input field
var inputValue = $(this).val();
// you are going to sent the input data to this route '/showMessage'
// you are going to use the post method
$.ajax({
type: "POST",
url: '/showMessage',
data: {
inputValue: inputValue
},
// if you post is successful then do following ....
success: function(data) {
// here we are just going to show the message inside you span, the returned data comes from your controller
$("#messageSpan").text(data.inputValue);
},
// if there was an error do following ....
error: function(data) {
// if there was an error you could just show a message with some error message
$("#messageSpan").text('ERROR!');
}
});
});
});
In your Laravel Controller class you need have have a function like this:
public function showMessage(Request $request)
{
// $inputValue contains the inputValue data from your ajax call
$inputValue = $request->inputValue;
// You could / should also do some validation here later on ...
// Thus you should probably save the data, I do not know what excatly you are going to do with it later ...
// now we are sending back the data
return response()->json($inputValue);
});
What you also have to do it to create a proper route so that your ajax request finds it.
So in your routes.php you need to createa a route like this:
Route::get('/showMessage', ['as' => 'showMessage', 'uses' => 'YourController#showMessage']);

How to pass data from Laravel View to Ajax or Javascript code without html div (id or class) - Laravel 5.3

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.

Thymeleaf page refresh followup - Now with AJAX

As a followup to my earlier question about using Thymeleaf and preventing page refresh:
http://forum.thymeleaf.org/Preventing-page-refresh-Thymeleaf-amp-Spring-MVC-td4029155.html
Basically I had a working Spring MVC app that uses Thymeleaf to save form data. When the user saves the data the page would refresh (since I wanted to leave them on the page for more edits) and I wanted to eliminate the page refresh.
I have coded up some Javascript to use JQuery Ajax to post the data to my Spring MVC Controller. The trick seemed to be to not use a submit button, just a regular button and bind a JS function to it for sending the data to the server.
It all seems to work perfectly, but I want to make sure I understand what is happening. In particular I'm wondering if Thymeleaf is now redundant. I don't think it is because when I initially load the page Thymeleaf is still bound to the data bean. From using the debugger on the server side in the controller it looks like the post request calls the mapped method and passes in the data to the model.
I would appreciate your comments on whether or not this is the correct way to accomplish this.
Finally, how do I handle an error, say for example the repository fails to persist the data for any reason?
Thanks very much.
Here are the important parts of the form:
<FORM id="adminDataForm" action="#" th:action="#{/admin_ajax}" th:object="${adminFormAjax}" method="post">
<input type="button" value="Save Changes" id="post" onClick="sendData()" />
Here is the Javascript:
function sendData()
{
$.ajax(
{
type: "POST",
data: $("#adminDataForm").serialize(),
cache: false,
url: "/admin_ajax",
success: function(data)
{
alert("Your changes have been saved");
},
error: function()
{
alert("Error - Data not saved");
}
});
}
Here is the controller:
#SessionAttributes("adminFormAjax")
#Controller
public class TestController
{
final static protected long INDEX_RA = 2L;
#Autowired
private AdminDataRepository rep;
#RequestMapping(value="/admin_ajax", method=RequestMethod.GET)
public String adminFormAjax(Model model)
{
AdminData ad = rep.findById(INDEX_RA);
// If there is no configuration record, create one and assign the primary key
if(ad == null)
{
ad = new AdminData();
ad.setId(INDEX_RA);
}
model.addAttribute("adminFormAjax", ad);
return "adminFormAjax";
}
#RequestMapping(value="/admin_ajax", method=RequestMethod.POST)
public #ResponseBody AdminData adminSubmit(#ModelAttribute("adminFormAjax") AdminData ad, Model model)
{
rep.save(ad);
model.addAttribute("adminFormAjax", ad);
return ad;
}
}
So breakdown of answer.
Thymeleaf not redundant, it will still render the HTML page prior to sending to client. Ajax just does the further processing for you on client side.
You can use submit button as well, you just need to ensure your form is properly structured and you have javascript listening for your submit button click e.g.
$("#submitbutton").on('click', function (){//do stuff});
You handle any and all exceptions/issues within your Ajax controller as you would with standard controller. You need to separate issue handling at different levels. e.g. respository level issues should be managed at rep level, controller/pojo should be at controller level (or pojo if you using one for processing). You should also be capturing any exceptions through a global medium (e.g. ControllerAdvice).
Any issues/errors you pick up you should be communicating back via your return call in adminSubmit, and managing the relevant client response in ajax.

Categories