Dynamic data from an input text Laravel 5.4 - ajax

I want to make the same action as the image below in one of my create forms:
I want to write the Id of the user and bring the name of it dynamically to put it in an input below, as is shown in the image.
How can I do that? I'm using laravel 5.4

use ajax request like this
$("#id_of_input").keyup(function(){
$.ajax({url: "http://example.com/api/name/" + $(this).val(), success: function(result){
$("#user_name").html(result);
}});
});
and add in web.php
Route::get('/api/name/{id}', function ($id) {
$user = User::find($id);
return $user ? $user->name : '';
});

Related

laravel link href click to save some data

Preview Your File
here link click to open pdf its fine but i want to insert some data when click this link how to insert and how to pass data laravel
You can do this in two methods
1: Using Ajax:
First insert your data then in the success redirect to your file .
2: using controller to redirect you to the file
use form to submit the data you want to controller then via controller redirect it to your file after adding data to database
something like this
public function AddDataToDatabase(Request $request)
{
$datas=New DataModal();
$datas->name = $request->name;
$datas->address = $request->address;
$datas->lastName = $request->lastName;
$datas->email = $request->email;
$data->save();
$items=Attachments::where('id',1)->get();
return redirect('Attachments/'.$items[0]->attachmentName);
}
or Using Ajax
$.ajax({
type: "POST",
url: your_URL,
data: {
'name':'your_name',
'id':'your_id',
'email':'your_email',
},
success: function(data) {
window.location = 'https://localhost/sample.pdf';
},
error: function(e) {
console.log(e);
}
});
then in your controller create a new method like this:
public function AddDataToDatabase(Request $request)
{
$datas=New DataModal();
$datas->name = $request->name;
$datas->address = $request->address;
$datas->lastName = $request->lastName;
$datas->email = $request->email;
$data->save();
return response()->json(['msg' => 'added successfully'],200);
}
Instead of a link, create form that contains the fields that you want to store in database. Make the fields hidden if they won't be filled by the user. Then submit the form to a controller. Store the data, redirect to a new path that will display the pdf.

How do I pass a variable from blade file to controller in laravel?

I have ProjectController that fetches data from the database and passes it to a blade file. One of the data items is the project_id. I want to pass the project _id from the blade file to another controller BidController.
ProjectController.php
public function show($id)
{
$project = Project::find($id);
return view('project.show',['project'=>$project]);
}
show.blade.php
div class="card-header">PROJECT <p>{!! $project->id !!}</p></div>
BidController.php
public function store(Request $request)
{
$bid = new Bid;
$bid->project_id = $project_id;
dd($project_id);
}
The dd(); does not output the project_id. I need help in passing the project_id from the blade file to the BidController method.
You can't directly set a model's id like you're doing in the line $bid->id = $project_id;. Are you trying to set up a relationship? That should be more like $bid->project_id = $request->project_id;.
Blade templates can't really pass things back to controllers, once they're in the browser your app is sort-of finished running. You need to create an HTML link/request on the page (like a form post request) that'll request the next thing from your app when the user clicks it.
If you want to create a button that creates a new bid for an existing project, you could do something like set up a form with a hidden field of 'project_id' that posts back to '/bids' which goes to the route 'bids.store'. You'll find 'project_id' under $request->project-id'.
You can send an AJAX request from Javascript:
View
<script type="text/javascript">
var project_id= {!! json_encode($project->id) !!}
$.ajax({
type: 'POST',
url: url, //Your bidController route
data: {project_id: project_id},
error: function (jqXHR, textStatus, errorThrown) {
console.log(errorThrown)
},
success: function()
{
console.log('successful')
}
});
</script>
This will sent the data to the controller asynchronously so the user experience doesn't get affected.
One extra point: In your Bid controller, as project_id is coming from the request, you'll have to use:
$bid->id = $request->project_id;
I hope it helps!
PS: I'm using JQuery for this, so you'll have to include it if you don't already have.
I think this will solve your problem :
ProjectController.php
public function show($id)
{
$project = Project::findOrFail($id);
return view('project.show',compact('project');
}
web.php
Route::post('/bids/store/{id}' , 'BidController#store')->name('bids.store');
show.blade.php
div class="card-header">PROJECT <p>{{$project->id}}</p></div>
<form action="{{route('bids.store', $project->id)}}" method="post">
BidController.php
public function store(Request $request, $id)
{
$bid = new Bid;
$bid->id = $id;
$bid->save();
dd($id);
}

Getting value from request in Laravel using ajax

I have this ajax method in PostsController
public function ajax(Request $request)
{
//dd($request);
$this->authorize('view', Post::class);
$posts = Post::orderBy("created_at","desc")->paginate(5);
$comments = Comment::all();
return response()->json(array("posts"=> $posts, "comments"=> $comments), 200);
}
which works great when you just getting data and sending it.
So i tried besides requesting data by ajax, to send some data alongside ajax request. How can i access that data inside controller?
Here is a method which resides inside certain blade:
function ajax(){
let var1 = "gg";
let var2 = "bruh";
let token = document.querySelector("meta[name='csrf-token']").getAttribute("content");
let url = '/posts';
$.ajax({
type: "POST",
url: url,
headers:
{
'X-CSRF-TOKEN': token
},
data: {
'var1': var1,
'var2': var2
},
success: function(data) {
console.log(data);
}
});
}
To simplify: How can i, dd() or dump(), given data(var1 & var2) by ajax function from blade in PostsController?
Here is route:
Route::post('/posts', "PostsController#ajax");
And here is some "gibberish" when i try to dd() it:
dd() is a laravel function and dump()for php. so you cannot use them from javaScript.
You cannot dd() or dump() from direct ajax request or JavaScript.
What you can do is, console log your data, or check from browser developer portion, network tab to see which data you are getting from the ajax response. You can find browser developer portion in,
for chrome:
Insepect > Network
for mozila:
Insepect Element > Network
If you are telling about get var1 and var2 on controller, you can just get them by $request->var1 and $request->var2.
Hasan05 was right. Just needed to know right direction. So to get data parameter of ajax request i modified ajax controller method:
public function ajax(Request $request)
{
$var1 = $request->input('var1');
$var2 = $request->input('var2');
$this->authorize('view', Post::class);
$posts = Post::orderBy("created_at","desc")->paginate(5);
$comments = Comment::all();
return response()->json(array("posts"=> $posts, "comments"=> $comments, "var1"=> $var1, "var2"=> $var2), 200);
}

How to send PUT request with a file and an array of data in Laravel

I am programing a web app using Laravel as API and Angularjs as frontend. I have a form to update product using PUT method with a array of informations and a file as product image. But I couldn't get the input requests in the controller, it was empty.
Please see the code below :
web.php ( route )
Route::group(['prefix' => 'api'], function()
{
Route::put('products/{id}', 'ProductController#update');
});
My angularjs product service :
function update(productId, data, onSuccess, onError){
var formData = new FormData();
formData.append('imageFile', data.imageFile);
formData.append('image', data.image);
formData.append('name', data.name);
formData.append('category_id', data.category_id);
formData.append('price', data.price);
formData.append('discount', data.discount);
Restangular.one("/products", productId).withHttpConfig({transformRequest: angular.identity}).customPUT(formData, undefined, undefined, {'Content-Type': undefined}).then(function(response) {
onSuccess(response);
}, function(response){
onError(response);
}
);
}
My ProductController update function
public function update(Request $request, $id) {
// Just print the request data
dd($request->all());
}
This is what I see in Chrome inspectmen
Please share your experiences on this problem. Thanks.
what you need is Only normal POST request with new field named _method=put then your code will work normally:
You can't do that, according to this discussion. What you should do instead is to 'fake' the PUT request by using Form Method Spoofing
Try this method:
public update(Request $request, $id)
{
$request->someVar;
$request->file('someFile');
// Get variables into an array.
$array = $request->all();
Also, make sure you're using Route::put or Route::resource for your route.

Pass data to all routes?

I use a set of data on every route. Is there a way to pass this data to all routes without having to specify the data under each route, like:
Route::get('/', function()
{
$data = Data::all();
return View::make('index')->with('data', $data);
});
Route::get('/another', function()
{
$data = Data::all();
return View::make('another')->with('data', $data);
});
You can use view()->share() in a service provider, like so :
view()->share('key', 'value');
You will then be able to access value using {{ key }} in all your views.
You can put it in the boot() method of the default AppServiceProvider.
Use view composers.
View::composer('profile', function($view)
{
$view->with('count', User::count());
});
Now each time the profile view is rendered, the count data will be bound to the view.
Also you need assign composer to many views, so you can just use ['profile', 'dashboard'] instead of 'profile'.
Or you can share a data with one function:
View::share('name', 'Steve');

Resources