How to call edit method of the resource controller using AJAX in Laravel5.6 - ajax

In my laravel project I am using resource controller for update. but it is not working. I tried but it failed.
my blade
<!doctype html>
<html lang="{{ app()->getLocale() }}">
<head>
<title>{{ config('app.name') }}</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<link href="{{ asset('css/app.css') }}" rel="stylesheet" type="text/css" />
<link href="{{ asset('css/style.css') }}" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
<h1>{{ config('app.name') }}</h1>
<form class="dis-none" id="FormAjax">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" />
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="address">Address</label>
<textarea class="form-control" rows="3" id="address"></textarea>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="country">Country</label>
<input type="text" class="form-control" id="country" />
</div>
</div>
</div>
<button type="submit" id="SaveAjax" class="btn btn-success">Save Form</button>
<button type="button" id="cancel" class="btn btn-danger">Cancel</button>
</form>
<div id="ShowAjax" class="row">
<button type="button" id="AddForm" class="btn btn-success">Add Form</button>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Address</th>
<th>Country</th>
<th>Action</th>
</tr>
</thead>
<tbody id="data">
</tbody>
</table>
</div>
</div>
<script type="text/javascript" src="{{ asset('js/app.js') }}"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("#AddForm").click(function () {
$("#FormAjax").fadeIn();
$("#ShowAjax").hide();
$('#UpdateForm').text('Save Form');
});
$("#SaveAjax").click(function () {
$("#FormAjax").hide();
$("#ShowAjax").fadeIn();
});
$(document).on('click', '#cancel', function () {
$('#name').val('');
$('#country').val('');
$('#address').val('');
});
$(document).on('click', '#edit', function () {
$("#FormAjax").fadeIn();
$("#ShowAjax").hide();
name = $(this).parent().parent().find('#ename').text();
address = $(this).parent().parent().find('#eaddress').text();
country = $(this).parent().parent().find('#ecountry').text();
$('#name').val(name);
$('#address').val(address);
$('#country').val(country);
$('#SaveAjax').text('Edit');
$('#SaveAjax').prop('id', 'UpdateForm');
$('#UpdateForm').attr('data-id', $(this).data('id'));
});
$(document).on('click', '#UpdateForm', function () {
name = $('#name').val();
country = $('#country').val();
address = $('#address').val();
url = "peoples";
id = $(this).data('id');
editUrl = url + '/' + id + '/edit';
$.get( {{ route('editUrl') }}, {name:name, country:country, address:address, id:id}, function (data) {
console.log('success');
});
});
});
</script>
</body>
</html>
route/web.php
Route::resource('peoples', 'PeopleController');
PeopleController.php
public function edit(People $people)
{
if($request->ajax()) {
$request->validate([
'name' => 'required',
'address' => 'required',
'country' => 'required',
]);
$people = People::find($request->id);
$people->name = $request->name;
$people->address = $request->address;
$people->country = $request->country;
$people->save();
return response()->json();
}
}
When I try type in browser http://localhost:8000/peoples I see this error.
Route [editUrl] not defined. (View: C:\xampp\htdocs\Tutorials
Laravel\Ajax\resources\views\peoples.blade.php)

You cannot use the route() helper here as you have not named your routes. Instead, try using the url() helper to generate the URL.
url(id . '/edit')
But, here I see another problem as the id will come in dynamically when the JS executes by which time the Laravel helper would have already executed. So, I would suggest the following approach:
url = {{ base_url() }} + '*apiPrefix*' + '/peoples/' + id + '/edit'

Related

ajax laravel not inserting or code not working

i want to insert to the database by ajax crud i am inserting but the code dosn't work iam using jquery javascript framework
i want to insert to the database by ajax crud i am inserting but the code dosn't work iam using jquery javascript framework
i dont' know why although i am writing correctly
please help
here is my code
my blade file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="{{asset('css/app.css')}}">
</head>
<body>
<div class="container">
<div class="row" style="matgin-top:50px;">
<div class="col-md-6">
<div class="card">
<div class="card-hehader bg-primary text-white">Add new product</div>
<form id="form" action="{{route('products.store')}}" method="post" enctype="multipart/form-data">
#csrf
#method('POST')
<div class="form-group">
<label for="">product name</label>
<input type="text" name="name" class="form-control">
<span class="text-danger error-text product_name_error"></span>
</div>
<div class="form-group">
<label for="">product image</label>
<input type="file" name="image" class="form-control">
<span class="text-danger error-text product_name_error"></span>
</div>
<button type="submit" class="btn btn-info">add</button>
</form>
</div>
</div>
<div class="col-md-6">
<div class="card">
<div class="card-header bg-primary">All Products</div>
<div class="card-body">
</div>
</div>
</div>
</div>
</div>
<script src="{{asset('js/app.js')}}"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#form').on('submit',function(e){
e.preventDefault();
var form = this;
$.ajax({
url:$(form).attr('action'),
method:$(form).attr('method'),
data:new FormData(form),
processData:false,
dataType:'json',
contentType:false,
beforeSend:function(){
$(form).find('span.error-text').text('');
},
succes:function(data){
if(data.code == 0){
$.each(data.error, function(prefix,val){
$(form).find('span.'+prefix+'_error').text(val[0]);
});
}
else{
$(form)[0].reset();
alert(data.msg);
// fetchAllProducts();
}
}
})
});
});
</script>
</body>
</html>
and my controller store function
public function store(Request $request)
{
$path = 'files/';
$file = $request->file('product_image');
$file_name = time().'_'.$file->getClientOriginalName();
// $upload = $file->storeAs($path, $file_name);
$upload = $file->storeAs($path, $file_name, 'public');
if($upload){
Product::insert([
'name'=>$request->name,
'image'=>$request->image,
]);
return response()->json(['code'=>1,'msg'=>'New product has been saved successfully']);
}
}
I check out your controller portion and found something messy, would you mind trying with the below code:
if ($request->has('image')) {
$fileName = time() . '_' . $request->image->getClientOriginalExtension();
$request->image->storeAs('Files', $fileName, 'image');
$product = new Product();
$product->name = $request->name;
$product->image = $fileName;
$product->save();
return response()->json(['code'=>1,'msg'=>'New product has been saved
successfully']);
}

I am using websocket to send images in a chat with spring boot and STOMP client with js

Hello everyone I am using websocket to send images using stomp client and am facing this error:
Uncaught TypeError: Cannot read property 'files' of null
at sendMyImage (app.js:46)
at HTMLButtonElement.<anonymous> (app.js:68)
at HTMLButtonElement.dispatch (jquery.js:5201)
at HTMLButtonElement.q.handle (jquery.js:5009)
sendMyImage # app.js:46
(anonymous) # app.js:68
dispatch # jquery.js:5201
q.handle # jquery.js:5009
This is the code that am using in my index.html
<html>
<head>
<title>chat app</title>
<link href="/webjars/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="/main.css" rel="stylesheet">
<script src="/webjars/jquery/jquery.min.js"></script>
<script src="/webjars/sockjs-client/sockjs.min.js"></script>
<script src="/webjars/stomp-websocket/stomp.min.js"></script>
<script src="/app.js"></script>
</head>
<body>
<div id="main-content" class="container">
<div class="row">
<div class="col-md-6">
<form class="form-inline">
<div class="form-group">
<label for="connect">WebSocket connection:</label>
<button id="connect" class="btn btn-default" type="submit">Connect</button>
<button id="disconnect" class="btn btn-default" type="submit" disabled="disabled">Disconnect
</button>
</div>
</form>
</div>
<div class="col-md-6">
<form class="form-inline">
<div class="form-group">
<label for="participantId">ParticipantId :</label>
<input type="number" id="participantId" class="form-control" placeholder="Your id here...">
</div>
<div class="form-group">
<label for="id">Content :</label>
<input type="text" id="content" class="form-control" placeholder="Your message content here...">
</div>
<button id="send" class="btn btn-default" type="submit">Send</button>
</form>
</div>
<div class="col-md-6">
<form class="form-inline">
<div class="form-group">
<label>Select an image and hit send:</label>
<input type="file" id="file" accept="image/*"/>
<button id="sendImage" class="btn btn-default" type="submit">Send Image</button>
</div>
</form>
</div>
</div>
<div class="row">
<div class="col-md-12">
<table id="conversation" class="table table-striped">
<thead>
<tr>
<th>chatmessages</th>
</tr>
</thead>
<tbody id="chatmessages">
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
and this is my app.js code :
var stompClient = null;
const messageWindow = document.getElementById("messages");
const fileInput = document.getElementById("file");
const sendImageButton = document.getElementById("sendImage");
function setConnected(connected) {
$("#connect").prop("disabled", connected);
$("#disconnect").prop("disabled", !connected);
if (connected) {
$("#conversation").show();
}
else {
$("#conversation").hide();
}
$("#chatmessages").html("");
}
function connect() {
var socket = new SockJS('/ws');
socket.binaryType = "arraybuffer";//heere
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/user/chatmessages', function (chatmessage) {
showChatMessage(JSON.parse(chatmessage.body));
});
});
}
function disconnect() {
if (stompClient !== null) {
stompClient.disconnect();
}
setConnected(false);
console.log("Disconnected");
}
function sendParticipantIdAndContent() {
stompClient.send("/app/chat", {}, JSON.stringify({'participantId': $("#participantId").val(),'content': $("#content").val()}));
}
function sendMyImage() {
let file = fileInput.files[0];
sendMessage(file);
fileInput.value = null;
}
function showChatMessage(message) {
$("#chatmessages").append("<tr><td>" + message.message + "</td></tr>");
}
function addImageToWindow(image) {
let url = URL.createObjectURL(new Blob([image]));
messageWindow.innerHTML += `<img src="${url}"/>`
}
$(function () {
$("form").on('submit', function (e) {
e.preventDefault();
});
$( "#connect" ).click(function() { connect(); });
$( "#disconnect" ).click(function() { disconnect(); });
$( "#send" ).click(function() { sendParticipantIdAndContent(); });
$( "#sendImage" ).click(function() { sendMyImage(); });
});
I really want to know what is the problem because i didn't get why he would be reading the file as a null.
Please tell me where did i mess up
and thank you
The problem is because the fileInput in your javascript is read as null.
you could try something like this
<input type="file" id="file" >
and access content like this
let file = document.getElementById("file").files[0];
And the problem here is definitely not related stomp or spring or websocket.

Live Search using Ajax and Getting Error "500 (Internal Server Error)" on Laravel 5.8

I was following tutorial to Live Search using ajax on Laravel, but in the implementation I get error:
GET http://localhost:8000/search?search=k 500 (Internal Server Error)
I was following this tutorial 3 times but always getthis same error. I modified like this:
<!DOCTYPE html>
<html>
<head>
<meta name="_token" content="{{ csrf_token() }}">
<title>Live Search</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="panel panel-default">
<div class="panel-heading">
<h3>Products info </h3>
</div>
<div class="panel-body">
<div class="form-group">
<input type="text" class="form-controller" id="search" name="search">
<input type="hidden" name="_method" value="POST">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</div>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>ID</th>
<th>Product Name</th>
<th>Description</th>
<th>Price</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$('#search').on('keyup',function() {
$value=$(this).val();
$.ajax({
type : 'get',
url : '{{URL::to('search')}}',
data:{'search':$value},
success:function(data){
$('tbody').html(data);
}
});
});
</script>
<script type="text/javascript">
$.ajaxSetup({ headers: { 'csrftoken' : '{{ csrf_token() }}' } });
</script>
</body>
</html>
my controller:
public function search(Request $request)
{
if($request->ajax()) {
$output="";
$products=DB::table('products')->where('title','LIKE','%'.$request->search."%")->get();
if($products) {
foreach ($products as $key => $product) {
$output.='<tr>'.
'<td>'.$product->id.'</td>'.
'<td>'.$product->title.'</td>'.
'<td>'.$product->description.'</td>'.
'<td>'.$product->price.'</td>'.
'</tr>';
}
return Response($output);
}
}
}
I was trying this code for 3 different database and always get the same error 500 .
You have call ajax using get method, so first check your route file.
I think you are calling search method using post method.
Also in ajax code default is get method
you have to specify : method : post
you need to declare variable in Jquery/Javascript like below :
var value=$(this).val();
and pass this variable like below in ajax :
data:{'search':value}
Change above lines ,it should work !

Response is empty string

I am creating a simple upload files web application using laravel in the backend and I am trying to print the response that is sent from the server -which is supposed to be informed about the uploaded file- in the console, but it shows me an empty string.
here is my controller:
<?php
namespace App\Http\Controllers;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Storage;
class UploadsController extends Controller
{
public function getUpload(){
return view('upload');
}
public function postUpload(request $request){
// //
$result = print_r($request,true);
$time = Carbon::now();
if ($request->hasFile('file')) {
$file = $request->file('file');
$extension = $file->getClientOriginalExtension();
$fileName = $file->getClientOriginalName();
//$upload_success = $file->storeAs('public',$file->getClientOriginalName());
$upload_success=Storage::disk('local')->put($fileName, fopen($file, 'r+'));
if ($upload_success) {
return response()->json(['request'=>$request->getContent()], 200);
}
else {
return response()->json('error', 400);
}
}
return response()->json('no file to upload', 400);
}
}
and my view where I am printing the response:
<html>
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>upload</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="/js/xhr2.js"></script>
<script type="text/javascript">
$(function(){
$('#upload').on("click",function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("#file").upload("/upload",function(data){
$('#spin').css('display','none');
$('#msg').css('display','block');
console.log(data);
},function(prog,val){
$('#prog').html(val+"%");
$('#prog').width(''+val+'%');
if(val == 100){
$("#prog").html('Completed');
$('#spin').css('display','block');
}
});
});
});
</script>
</head>
<body>
<div class="container">
<div style="margin-top:5px"><input type="file" id="file" name="file" ></div>
<div style="margin-top:5px;margin-bottom: 5px">
<input type="button" id="upload" value="upload" class="btn btn-success btn-lg">
</div>
<div class="progress">
<div class="progress-bar" role="progressbar" style="width: 0%;" aria-valuemin="0" aria-valuemax="100" id="prog"></div>
</div>
<div id="spin" style="display:none">
<i class="fa fa-circle-o-notch fa-spin" style="font-size:24px"></i>
</div>
<div class="alert alert-success" style="display: none" id="msg" style="text-align: center">
<strong>Success!</strong>You have uploaded the file successfully
</div>
</div>
</body>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</html>
and here is a sample of what I get:
I would know if I am doing it wrong, and if not, why it is empty,
Thanks.
You're not using a form element.
Wrap your inputs in a basic html form:
<form method="POST" action="#">
#csrf
...
</form>
Then use jquery to post the form to the laravel route.

Url is getting updated but navigation is not happening on button click in angular js

I am doing POC on login application using angular js. On button click I need to navigate to another page. The code which I have written is only updating the url but the view is not getting loaded. I have used ng-view or ui- view also. And I have used $location.path. But still unable to navigate to other page
Here is my code
index.html:
<html ng-app='myApp'>
<head>
<title>Jasmine</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<script src="Scripts/angular.min.js"></script>
<script src="Scripts/angular-route.min.js"></script>
<script src="routing.js" type="text/javascript"></script>
</head>
<body>
<div id='content' ng-controller='LoginController'>
<div class="container">
<form class="form-signin" role="form" name="myForm" ng-submit="login()">
<h3 class="form-signin-heading">Login Form</h3>
<span>
<b>Username :</b> <input type="text" class="form-control" ng-model="user.name" required>
</span> <br />
<br /> <span>
<b>Password :</b> <input type="password"
class="form-control" ng-model="user.password" required>
</span>
<br><br>
<button class="btn btn-lg btn-primary btn-block" type="submit" ng-disabled="myForm.$invalid">
<b>Sign in</b>
</button>
</form>
</div>
{{message}}
</div>
<div ui-view></div>
</body>
</html>
Here I have used ui-view.. when i use this, url is updating but not the view..
when i use ng-view, the script block is happening both in chrome and firefox.
routing.js:
var applog = angular.module('myApp', ['ngRoute']);
applog.controller("LoginController", function ($scope, $location, $window) {
$scope.message = "hi";
$scope.login = function () {
var username = $scope.user.name;
var password = $scope.user.password;
$location.path('/home');
};
});
applog.controller("HomeController", function ($scope, $location) {
$scope.msg = "qwerty";
});
applog.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'index.html',
controller: 'LoginController'
}).when('/home', {
templateUrl: '/home.html',
controller: 'HomeController'
}).otherwise({
redirectTo: 'index.html'
});
});
Here I tried with hash also.. not working
Home.html:
<div ng-controller="HomeController">
Welcome....
</div>

Resources