laravel 5.3: HTTP/1.0 405 Method Not Allowed - javascript

route:
Route::post('serial', 'HomeController#serial');
Route::get('doctorlist',['as'=>'doctorlist','uses'=>'HomeController#doctorlist']);
script:
#section('scripts')
<script>
$(document).ready(function() {
src = "{{ route('doctorlist') }}";
$("#search_text").autocomplete({
source: function(request, response) {
$.ajax({
url: src,
dataType: "json",
data: {
term : request.term
},
success: function(data) {
response(data);
}
});
},
min_length: 3,
});
});
</script>
controller:
public function doctorlist(Request $request)
{
$query = $request->get('term','');
$doctors=Doctors::where('doctors_name','LIKE','%'.$query.'%')->get();
$data=array();
foreach ($doctors as $doctor) {
$data[]=array('value'=>$doctor->doctors_name,'id'=>$doctor->serial_no);
}
if(count($data))
return $data;
else
return ['value'=>'No Result Found','id'=>''];
}
it always goes to serial route. not going doctorlist

Related

How to delete image with ajax in laravel

I am trying to delete a record from my products table, each product has an image. I don't know how to delete the image from the file where it is stored.
Product.js
$(document).ready(function() {
$("#btn-delete").click(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'DELETE',
url: '/product/' + $("#frmDeleteProduct input[name=product_id]").val(),
dataType: 'json',
success: function(data) {
$("#frmDeleteProduct .close").click();
window.location.reload();
},
error: function(data) {
console.log(data);
}
});
});
});
function deleteProductForm(product_id) {
$.ajax({
type: 'GET',
url: '/product/' + product_id,
success: function(data) {
$("#frmDeleteProduct #delete-title").html("¿Do you want to delete this product (" + data.products.name + ")?");
$("#frmDeleteProduct input[name=product_id]").val(data.products.id);
$('#deleteProductModal').modal('show');
},
error: function(data) {
console.log(data);
}
});
}
ProductController.php
I read that I need to put something like this in my controller File::delete('img/products/' . $image); but I don't now how.
public function destroy($id)
{
//File::delete('img/products/' . $image);
$products = Product::destroy($id);
return response()->json([
'error' => false,
'products' => $products,
], 200);
}
You need to pass as a parameter to File::delete() the full path when your image was save. For example, if your images were in a laravel storage path in the subdirectory img/products/, and the name of the image is the id of the product with the .jpg extension, you can do this:
public function destroy($id)
{
$fullImgPath = storage_path("img/products/$id.jpg");
if(File::exists($fullImgPath)) {
File::delete($fullImgPath);
}
$products = Product::destroy($id);
return response()->json([
'error' => false,
'products' => $products,
], 200);
}
But if you have the name of the image in your Product model, you can do this:
public function destroy($id)
{
$product = Product::find($id);
$fullImgPath = storage_path("img/products/".$product->image_name);
if(File::exists($fullImgPath)) {
File::delete($fullImgPath);
}
$product->delete();
return response()->json([
'error' => false,
'products' => $product->id,
], 200);
}

How to set serialization in Asp .Net Core

Im getting the following error on my Ajax post back {"readyState":0,"status":0,"statusText":"error"}
on my first ajax call but the second one returns data I want.
My C# method (UserSelect) JsonResults shows the data when I put break point
My C# code :
public IActionResult OnPostAreaSelect(string Id)
{
//Generating list for Areas
Guid ModelId = new Guid(Id);
List<ModelArea> modelAreas = _context.ModelArea.Distinct()
.Where(w => w.ModelId == ModelId).OrderBy(o => o.AreaColumn.Name).Include(i => i.AreaColumn).ToList();
return new JsonResult(modelAreas);
}
public IActionResult OnPostUserSelect(string Id)
{
//Generating list for Users
Guid ModelId = new Guid(Id);
List<UserModel> userModels = _context.UserModel
.Where(w => w.ModelId == ModelId).OrderBy(o => o.User.FullName)
.Include(i => i.User)
.ToList();
return new JsonResult(userModels);
}
My JavaScript :
<script type="text/javascript">
$(document).ready(function () {
$("#RepfocusModelDropdown").change(function () {
var Id = $(this).val();
if (Id != null) {
$.ajax({
async: true,
type: "POST",
url: "./Create?handler=UserSelect",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
Id: Id
},
crossDomain: true,
dataType: "json",
success: function (response) {
alert(JSON.stringify(response));
},
error: function (response) {
alert(JSON.stringify(response));
}
});
$.ajax({
type: "POST",
url: "./Create?handler=AreaSelect",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
Id: Id
},
dataType: "json",
success: function (response) {
alert(JSON.stringify(response));
},
error: function (response) {
alert(JSON.stringify(response));
}
});
}
})
})
The second ajax call on my script works fine only the first one returns the error
How can I solve the error
When you work with EntityFramework (or other ORM) there may be problems with serialization because an entity could have some circular references. To avoid this problem a solution is to set serialization settings:
services.AddMvc().AddJsonOptions(opt => {
opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
or:
Newtonsoft.Json.JsonConvert.DefaultSettings = () => new Newtonsoft.Json.JsonSerializerSettings {
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
};

draggable rows using ajax in laravel

i'm here trying to make a draggable rows for table and update the change in the database, so i follow on tutorial the drag and drop works fine but the changes not save in the database.
this is the tutorial i'm follow
https://shareurcodes.com/blog/create-drag-and-droppable-datatables-using-jquery-ui-sortable-in-laravel
and here my codes
searchController
class SearchController extends Controller {
public function index() {
// $customers = Customer::all();
$customers = Customer::orderBy('order', 'ASC') - > select('id', 'first_name', 'last_name', 'email', 'phone') - > get();
return view('search.search', compact('customers'));
}
public function updateOrder(Request $request) {
$customers = Customer::all();
//$customer = Customer::findOrFail($id);
foreach($customers as $customer) {
$customer - > timestamps = false;
$id = $customer - > id;
foreach($request - > order as $order) {
if ($order['id'] == $id) {
$customer - > update(['order' => $order['id']]);
}
//if($order['id'] = $id){
// $customer->update($request->all());
// }
}
}
return response('Update Successfully', 200);
}
}
search.blade.php
<script type="text/javascript">
$(function() {
$("#table").DataTable();
$("#tablecontents").sortable({
items: "tr",
// cursor: 'move',
opacity: 0.6,
update: function() {
sendOrderToServer();
}
});
function sendOrderToServer() {
let order = [];
$('tr.row1').each(function(index) {
order.push({
id: $(this).attr('data-id'),
position: index + 1
});
});
$.ajax({
type: "POST",
dataType: "json",
url: "{{ url('search.search') }}",
data: {
order: order,
_token: '{{csrf_token()}}'
},
success: function(response) {
if (response.status == "success") {
console.log(response);
} else {
console.log(response);
}
}
});
}
});
</script>
route
Route::post('search/search','searchController#updateOrder');
this is the table
Schema::create('customers', function (Blueprint $table) {
$table->increments('id');
$table->string('first_name');
$table->string('last_name');
$table->string('email')->unique();
$table->string('phone');
$table->integer('order');
$table->timestamps();
when i drag and drop this error in the console
jquery.min.js:4 POST http://adminproject.test/search.search 404 (Not Found)
Can you try changing ajax route like below
url: "{{ url('search/search') }}"
it was a silly mistake,
just change the url in javascript
from
url: "{{ url('search.search') }}",
to
url: "{{ url('search') }}",

How to call a codeigniter function in ajax?

In controller I have a _remap() for routing.
My controller is as follows:
public function _remap($id)
{
$this->index();
}
public function index()
{
$this->accesscontrol->can_or_redirect('view', 'translation');
$this->output->view('translation/language');
}
function process(Request $request){
// if(Response::ajax()) return "OK";
return json_encode(array('ok'));
}
My view is as follows:
$('#lang_choice1').each(function() {
$('#src_trans_lang').val($("#lang_choice1 option:selected").val());
var msg = $(this).val();
$.ajax({
type: "POST",
url: '<?=site_url('translation/language/process')?>',
data: msg,
success: function(data){ }
});
return false;
});
I am trying to call the function process in ajax and its not getting called. How do I need to modify the _remap function to call ajax calls as well?
Try This
Script part
$('#lang_choice1').each(function () {
$('#src_trans_lang').val($("#lang_choice1 option:selected").val());
var msg = $(this).val();
$.ajax({
type: "POST",
url: '<?= site_url('language/process') ?>',
data: {"msg":msg},
dataType:"json",
success: function (data) {
console.log(data);
}
});
return false;
});
Controller process function
function process() {
$data = $this->input->post();
$result['status'] = "ok";
$result['response'] = $data;
echo json_encode(array($result));
exit(0);
}
Check response in console

jQuery autocomplete not working with JSON

I am trying to implement the jQuery autocomplete. I feel like everything is set up just fine, however It's not working.
SearchSkies method
public JsonResult SearchSkies(string query)
{
SkiDao skiDao = new SkiDao();
IList<Ski> skies = skiDao.SearchSkies(query);
List<string> brands = (from Ski s in skies select s.Brand).ToList();
return Json(brands, JsonRequestBehavior.AllowGet);
}
The script in View
<script type="text/javascript">
$( function() {
$( "#searchBox" ).autocomplete({
source: function( request, response ) {
$.ajax( {
url: '#Url.Action("SearchSkies","Skies")',
dataType: "json",
data: {
query: request.term
},
success: function (data) {
response(data);
}
} );
},
minLength: 2,
});
});
</script>
You are not mentioning type of request(GET/POST) in ajax call.
$(document).ready(function () {
$("#searchBox").autocomplete({
source: function(request,response) {
$.ajax({
url: "/Skies/SearchSkies",
type: "POST", <<----
dataType: "json",
data: { query: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Name, value: item.Name };
}))
}
})
},
messages: {
noResults: "", results: ""
}
});
})
And the controller
public class SkiesController : Controller
{
// GET: Home
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult SearchSkies(string query)
{
SkiDao skiDao = new SkiDao();
IList<Ski> skies = skiDao.SearchSkies(query);
List<string> brands = (from Ski s in skies select s.Brand).ToList();
return Json(brands, JsonRequestBehavior.AllowGet);
}
}

Categories