I am using jquery ajax in laravel for update data from database. I wrote this code and the $ajax() part not working. but everything before that working great. Please let me know where I am doing wrong?
1) AJAX function:
$(".Editform").click(function() {var id=$(this).attr("id");
// alert(id);
$("#saveBtn").on ('click',function() { var name =
// alert(name);
$("input[name=name]").val();
$.ajax({type:'POST',url:'edit-records',data:{id:id,name:name },success:
function(result){alert.show(); $('#MyModal').modal('hide');
console.log(result);}});});});
2) Controller:
public function updaterec(Request $request, $id)
{
$name = $request->input('name');
DB::update('update m_employee set employee_name = ? where employee_id = ?',[$name,$id]);
echo "Record updated successfully";
}
3) web.php:
Route::post('edit-records','viewemployeeController#updaterec');
Route::get('view-records','viewemployeeController#index');
You should not use $id as parameter if it's not defined in the route.
Change your controller:
public function updaterec(Request $request)
{
$name = $request->input('name');
$id = $request->input('id');
DB::update('update m_employee set employee_name = ? where employee_id = ?',[$name,$id]);
echo "Record updated successfully";
}
---------OR---------
Change your Route and Ajax code:
Route::post('edit-records/{id}','viewemployeeController#updaterec');
$.ajax({type:'POST',url:'edit-records/'+id,data:{id:id,name:name },success: function(result){alert.show(); $('#MyModal').modal('hide'); console.log(result);}});});
});
Related
I'm working on a Vue.js/Laravel web application for a company that offers school workshops. I've managed to make it possible to add an image to a workshop when it doesn't yet have one (POST), but when I try to update an existing workshop picture (PUT), $request->file always returns null and I can't seem to figure out why.
Workshops table:
Uploads table:
(workshop_picture contains the id of the corresponding upload in the uploads table)
onFileSelected function in the workshop edit page:
onFileSelected (event) {
this.selectedFile = event.target.files[0]
let formData = new FormData()
formData.append('file', event.target.files[0])
if (this.workshop.workshop_picture) {
console.log('Workshop already has a picture, updating current picture...')
axios.put('/api/upload/' + this.workshop.workshop_picture.id,
formData,
{ headers: { 'Content-Type': 'multipart/form-data' } })
.then(response => {
this.workshop.workshop_picture = response.data.id
this.workshop_picture_preview = '/uploads/' + response.data.internal_name
})
.catch(function () {
alert('Uploaden mislukt!')
})
}
}
UploadController.php:
class UploadController extends Controller
{
public function store(Request $request)
{
$request->validate(['file' => 'mimes:jpeg,png,jpg']);
$internal_name = Str::random(32) . '.' . $request->file->extension();
$upload = new Upload();
$upload->name = $request->file->getClientOriginalName();
$upload->internal_name = $internal_name;
$upload->size = $request->file->getSize();
$upload->save();
$request->file->move(public_path('uploads'), $internal_name);
return response($upload, 200)->header('Content-Type', 'json');
}
public function update(Request $request, $id)
{
$request->validate(['file' => 'mimes:jpeg,png,jpg']);
$internal_name = Str::random(32) . '.' . $request->file->extension();
$upload = Upload::find($id);
$upload->name = $request->file->getClientOriginalName();
$upload->internal_name = $internal_name;
$upload->size = $request->file->getSize();
$upload->save();
$request->file->move(public_path('uploads'), $internal_name);
return response($upload, 200)->header('Content-Type', 'json');
}
}
The form data clearly contains the selected file, so I have absolutely no clue why it says $request->file is null.
I have to save data in a database table with userid using laravel ajax. Can anyone please help me to solve this issue
my controller code
public function store(Request $request)
{
$rearcameras = new Rearcameras();
$rearcameras->user_id = auth()->id();
$rearcameras->name = $request->name;
$rearcameras->size = $request->size;
$rearcameras->type = $request->type;
return $this->sendResponse($rearcameras->toArray(), 'Command Send Successfully successfully.');
}
and the response it getting is
{"success":true,"data":{"user_id":null,"name":null,"size":null,"type":"f-camera"},"message":"Command Send Successfully successfully."}
I have to save logged userId on submitting....I'm getting user_id null how can I store user_id please help me.
Thanks in advance
Update your controller code
public function store(Request $request)
{
$rearcameras = new Rearcameras();
$rearcameras->user_id = Auth::user()->id;
$rearcameras->name = $request->name;
$rearcameras->size = $request->size;
$rearcameras->type = $request->type;
$rearcameras->save();
return $this->sendResponse($rearcameras->toArray(), 'Command Send Successfully successfully.');
}
Don't forget to use use Auth at the top of the controller
I have a 3 part form that I want to be able to update the database after each submit. There is one table that holds all the fields below.
form1 asks for first and last name
form2 asks for email and phone
form3 asks for city and state
In my controller I have 3 separate functions to save each step of the form:
public function name(Request $request){
$lead = Lead::firstOrNew(123);
$lead->firstName = $request->get('firstName ');
$lead->lastName = $request->get('lastName');
$lead->save();
return redirect('/form2');
}
public function info(Request $request){
$lead = Lead::find(123);
$lead->email = $request->get('email');
$lead->phone = $request->get('phone');
$lead->save();
return redirect('/form3');
}
public function address(Request $request){
$lead = Lead::find(123);
$lead->city = $request->get('city');
$lead->state = $request->get('state');
$lead->save();
return redirect('/done');
}
Is there any way to combine that to one update function?
Just do conditional check, update the model and define redirect url:
public function info(Request $request) {
$lead = Lead::firstOrNew(123);
if ($request->has('firstName') && $request->has('lastName')) {
$lead->firstName = $request->get('firstName ');
$lead->lastName = $request->get('lastName');
$redirect = '/form2';
} else if ($request->has('email') && $request->has('phone')) {
$lead->email = $request->get('email');
$lead->phone = $request->get('lastName');
$redirect = '/form3';
} else if ($request->has('city') && $request->has('state')) {
$lead->city = $request->get('city');
$lead->state = $request->get('state');
$redirect = '/done';
}
$lead->save();
return redirect($redirect);
}
Also, you can probably do group update via update just make sure you whitelist the attributes in your model
public function info(Request $request) {
$lead = Lead::firstOrNew(123);
$lead->update($request->all());
if ($request->has('firstName') && $request->has('lastName')) {
$redirect = '/form2';
} else if ($request->has('email') && $request->has('phone')) {
$redirect = '/form3';
} else if ($request->has('city') && $request->has('state')) {
$redirect = '/done';
}
return redirect($redirect);
}
Or I'd better just add a redirect variable to your form like:
<input type="hidden" name="redirect" value="form1">
and simplify your controller method like:
public function info(Request $request) {
$lead = Lead::firstOrNew(123);
$lead->update($request->all());
return redirect($request->input('redirect'));
}
You could refactor the methods to call a common "update" function. See example code below.
public function name(Request $request){
$this->update(123, $request);
return redirect('/form2');
}
public function info(Request $request){
$this->update(123, $request);
return redirect('/form3');
}
public function address(Request $request){
$this->update(123, $request);
return redirect('/done');
}
private function update($id, $request) {
$lead = Lead::find($id);
foreach ($field as ['firstName', 'lastName', ...]) {
if ($request->has($field)) {
$lead->{$field} = $request->get($field);
}
}
$lead->save();
}
You can add a hidden field to all three forms (but with the name name, e.g form_name), and set their values to identify the form (form1, form2, form3) when it is submitted. Then in your controller, you check the value of the form_name field on the request to determine where you want to redirect to, like this:
public function info(Request $request) {
$lead = Lead::firstOrNew(123);
$lead->update($request->all());
//this will be from the hidden field (form_name)
$form_type = $request->get('form_name');
if ($form_type == 'form1') {
$redirect = '/form2';
} else if ($form_type == 'form2') {
$redirect = '/form3';
} else if ($form_type == 'form3') {
$redirect = '/done';
}
return redirect($redirect);
}
If you have the option for using javaScript then save the first and second form data on cookies or local storage and when the user reaches last part of the form then take data out of cookies or local storage then added with the last form, but keep these in the hidden input.
Given that HTTP requests are stateless (which means each request know nothing about the one before and after it), I would rather prefer you use sessions, so that you can be able to store information as you redirect from one form to the other. In that case, your code should look like so:
<?php
public function name(Request $request){
Session::put('nameData', $request->all()); //Store the info from form1 in session and redirect to form2
return redirect('/form2');
}
public function info(Request $request){
$validSessionData = Session::has('nameData');
if (!$validSessionData) { //Check if the user filled form1, if not, go back to form1
return redirect('/form1');
}
$nameAndInfo = Session::pull('nameData', []) + $request->all(); //Merge the info from form1 with info from form2. You could decide to keep them separate and merge later.
Session::put('nameAndInfo', $nameAndInfo);
return redirect('/form3');
}
public function address(Request $request){
$validSessionData = Session::has('nameAndInfo');
if (!$validSessionData) { Another check. You could also extend this by checking for form2 session data
return redirect('/form1');
}
$allData = Session::pull('nameAndInfo', []) + $request->all(); //Merge all session data
$lead = Lead::firstOrNew(123);
$lead->firstName = $allData['firstName'];
$lead->lastName = $allData['lastName'];
$lead->email = $allData['email'];
$lead->phone = $allData['phone'];
$lead->city = $allData['city'];
$lead->state = $allData['state'];
$lead->save();
return redirect('/done');
}
I want to send post request with ajax to controller in laravel. The ajax request send two input arguments and I want controller to find the column in the database with the first argument and then to set the name attribute with the second input argument. But I have this error message Creating default object from empty value
Ajax function:
$('#saveUserProfile').on('click', function () {
var $finduser = $('input[name=findUser]').val();
var $name = $('input[name=userprofilename]').val();
$.ajax({
type:"POST",
url:'/code/task1/public/updateUser',
data: {
'name' : $name,
'finduser' : $finduser,
// 'email' : $email,
},
success:function(data){
$("#input1").val(data[0].name);
}
});
});
and the function in my controller
public function updateUser(Request $request){
$return_array = array();
$findUserInput = $request->get('finduser');
$user = User::where('name',$findUserInput) -> first();
$user->name = $request->get('name');
$user->save();
$data = DB::select("SELECT * FROM users where name='$findUserInput'");
if(count($data) > 0){
foreach($data as $da){
$return_array[] = $da;
}
}
return $return_array;
}
Update: I also make ajax function and controller for finding user which is working good.
ajax function:
$('#buttonFindUser').on('click', function () {
var $name = $('input[name=findUser]').val();
$.ajax({
type:"GET",
url:'/code/task1/public/findUser',
data: {
'name' : $name,
},
success:function(data){
$("#input1").val(data[0].name);
$("#input2").val(data[0].email);
$("#input3").val(data[0].created_at);
}
});
});
Function in my controller:
public function findUser(Request $request){
$return_array = array();
$findUserInput = $request->get('name');
$data = DB::select("SELECT * FROM users where name='$findUserInput'");
if(count($data) > 0){
foreach($data as $da){
$return_array[] = $da;
}
}
return $return_array;
}
Any ideas?
But I have this error message Creating default object from empty value
What's happening is that you are trying to save a user that doesn't exist. You need to check if the $user is null or not in your controller. Right now, the user couldn't be found with the provided name so $user becomes null.
So, you can modify your code to do a null check on $user like so:
public function updateUser(Request $request){
$return_array = array();
$findUserInput = $request->get('finduser');
$user = User::where('name',$findUserInput) -> first();
if(!$user)
return response()->json(['status'=>false,'Description' => 'User could not be found.']);
$user->name = $request->get('name');
$user->save();
$data = DB::select("SELECT * FROM users where name='$findUserInput'");
if(count($data) > 0){
foreach($data as $da){
$return_array[] = $da;
}
}
return $return_array;
}
Here's the null check:
if(!$user)
return response()->json(['status'=>false,'Description' => 'User could not be found.']);
When we don't have a valid user, we just reply back with a json response stating that it couldn't be found.
Update:
Seeing as your input is not being retrieved in the controller, you need to make some changes in JS:
First, you are doing a post request and I cannot see a CSRF token. To add it, follow this answer: https://stackoverflow.com/a/37582060/6270112
So, your data will now become:
data: '_token=' + $('#token').val() + '&name=' + $name + '&finduser=' + $finduser
Also, as aleksejjj mentioned, you need to fix your jquery selectors as well. So, your existing selectors:
var $finduser = $('input[name=findUser]').val();
var $name = $('input[name=userprofilename]').val();
will become:
var $finduser = $('input[name^="findUser"]').val();
var $name = $('input[name^="userprofilename"]').val();
Next, in your controller you need to replace $request->get(...) with $request->input(...).
$findUserInput = $request->get('finduser');
will become
$findUserInput = $request->input('finduser');
and repeat the same with the name field as well.
You need to check your user exist
$user = User::where('name', $findUserInput)->first();
if($user)
{
$user->name = $request->get('name');
$user->save();
}
change this code
$user = User::where('name',$findUserInput) -> first();
to
$user = User::where('name','=',$findUserInput) -> first();
I hope this will work. :)
I need to fetch user_id, firstname, lastname from user table and feedback_id,comment,user_id and recipe_id from feedback table where user_id from user is equal to the user_id in user table.
Review.html
<div class="items item item-avatar" ng-repeat="comment in feedbackdata">
<img src="img/asd.jpg">
<h2>{{comment.firstname}} {{comment.lastname}}</h2>// I don't know what to put here
<p>{{comment.feedback_id}}</p>
<p>{{comment.comment}}</p>
<p>{{comment.user_id}}</p>
<p>{{comment.recipe_id}}</p>
Controller.js
.controller('CommentCtrl', function($scope, CommentList,$state,$location,SessionService,getFeedbackService) {
$scope.userdata = SessionService.getObject('userdata');
$scope.newComment={};
$scope.newComment.userID = $scope.userdata.user_id;
getFeedbackService.all().then(function(payload) {
$scope.feedbackdata = payload.data;
console.log(payload);
});
$scope.addComment = function(){
CommentList.add($scope.newComment);
console.log($scope.newComment);
};
})
Service.js
.factory('getFeedbackService', function($http){
return {
all: function() {
return $http.get("http://localhost/admin-recipick/api/Main/get_feedback_data");
}
};
});
main.php
public function get_feedback_data()
{
$postdata = json_decode(file_get_contents("php://input"));
$feedback = $this->User_model->feedback_data();
echo json_encode($feedback);
}
user_model.php
public function feedback_data()
{
$this->db->select('*');
$this->db->from('feedback')
$this->db->join('user','user.user_id = feedback.user_id');
$query = $this->db->get();
return $query->result_array();
}