Laravel 5.6 ajax post without form - php

I want to use ajax with selectize to load bdd results onchange.
I need to use post because I must send data to my url.
My function looks like this :
select_etages.load(function(callback) {
xhr && xhr.abort();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var data = { id:value }
xhr = $.ajax({
type: 'post',
dataType: 'json',
data: JSON.stringify(data),
data : { bat : value },
url: 'add/etages',
success: function(results) {
callback(results);
},
error: function() {
callback();
}
})
});
In my web.php I've got this :
Route::post('/lots/add/etages', ['as' => 'lots.add_post.select', 'uses' => 'Copro\LotController#select2']);
And my controller :
public function select(Request $request)
{
return "test";
}
But when I tried to use it, I've got an "419 unknown status". I can see that it's a post ajax and my data but I've got no error message :
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
No message
If I change to get it's working but not post.
Anyone know why I can't use post ??
Thank for your help.

Maybe you just rewrite the "select2" name end of the route to "select"?

I think you need to remove $.ajaxSetup function in callback function. Code might look like this.
$(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
select_etages.load(function(callback) {
xhr && xhr.abort();
var data = { id:value }
xhr = $.ajax({
type: 'post',
dataType: 'json',
data: JSON.stringify(data),
url: 'add/etages',
success: function(results) {
callback(results);
},
error: function() {
callback();
}
})
});
});

Related

How to add a variable in ajax URL route

I am trying to concatenate a variable to my url link in ajax. The variable $news is the one that handles the notification id.
$(document).on("click", "#viewList", function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var $news = $(this).prop("value");
$.ajax({
type: "get",
url : '{{url("admin/recipients/", $news)}}', //returning an error undefined variable news
data: {newsID : $news},
success: function(store) {
console.log(store);
$('#rec').text(store);
},
error: function() {
$('.alert').html('Error occured. Please try again.');
}
});
});
In my web.php, it's route is inside a route group.
Route::group(['middleware' => 'auth:admin'], function () {
Route::prefix('admin')->group(function() {
Route::get('/recipients/{news}', 'Admin\NewsController#recipients');
});
});
So how can I make this work? By the way, my ajax is inside a blade.php file.
$news doesnt exist to blade because it executes on the time server is rendering the page. So your javascript hasn't been executed yet. To make this work, change you js code to this:
$(document).on("click", "#viewList", function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var news = $(this).prop("value");
$.ajax({
type: "get",
url : '{{url("admin/recipients")}}' + '/' + news,
data: {newsID : news},
success: function(store) {
console.log(store);
$('#rec').text(store);
},
error: function() {
$('.alert').html('Error occured. Please try again.');
}
});
});

Minimum Working Example for ajax POST in Laravel 5.7

Can someone please show a Laravel 5.7 post ajax example with a full-working minimum example in a blade template? I know there are some resources in the web, but I miss a concise, straight-forward minimum example.
You can do something like this,
web.php
Route::post('/admin/order/{id}', 'OrderController#edit')->name('admin.order.edit');
blade.php
$(document).on('click', '.delete-button', function (e) {
e.preventDefault();
var orderId = 1
$.ajax({
type: 'post',
url: '/admin/order/' + orderId,
data: {
'_token': $('input[name=_token]').val(),
'data_one': 'dataone',
},
success: function () {
toastr.success('Order Has Been Deleted Successfully.');
},
error: function(XMLHttpRequest) {
toastr.error('Something Went Wrong !');
}
});
});
$.ajax({
url: 'http://some.working/url',
type: "POST",
data: $('#formContainer').serialize(),
success: function (response) {
console.log('Success', response);
},
error: function (response) {
console.log('Error', response);
}
});
The data can be produced in many ways for example
1. Using serialize() method as shown in the above example.
2. Using FormData():
for example
var data = new FormData($('#formContainer'));
In both of the above example, one thing compulsory is that your form
must contain csrf field. which can be provided using any of the
following methods:
<input type="hidden" name="_token" value="{{ csrf_token() }}" >
or
{{ csrf_field() }}
or even more simply by just using
#csrf
in some where in your form.
In case you are not using any form, you can create the data object by
yourself like this
var data = {
_token: '{{ csrf_token() }}',
data1: 'Value1',
data2: 'Value2',
data3: 'Value2'
}
Define a Web Route
Route::get('currencies/fiat/changeStatus','FiatCurrencyController#changeStatus')->name("currencies.fiat.chanageStatus");
Call this function on click onclick="changeStatus(1,0)"
function changeStatus(id,status){
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
/* the route pointing to the post function */
url: '/currencies/fiat/changeStatus',
type: 'GET',
/* send the csrf-token and the input to the controller */
data: {_token: CSRF_TOKEN,cid:id,status:status},
dataType: 'JSON',
/* remind that 'data' is the response of the AjaxController */
success: function (data) {
console.log(data);
}
});
}
That's it all Done.
$(document).ready(function(){
/* In laravel you have to pass this CSRF in meta for ajax request */
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
/* change in website layout base on click */
$('#user_view').on('click',function (e){
e.preventDefault();
$('.loading_screen').show();
var val = $(this).data('id');
$.ajax({
url: base_path + 'user/changeview/'+val,
type: "POST",
success: function (data) {
var obj = jQuery.parseJSON(data);
if (obj.SUCC_FLAG == 0){
window.location.href = site_url;}
else{
/* for console error message. */
console.log(obj.MSG);}
$('.loading_screen').hide();
},
error: function () {
alert("server error");
}
});
});
});
Hey it's a working code and i hope this will works for you.

Laravel 5.5 delete item with ajax call on click

I am trying to delete a model item via an ajax call when you click on an icon.
Without an ajax call and just with a form everything works great.
This exception is thrown when I look in my network tab of my chrome dev tools
"Symfony\Component\HttpKernel\Exception\HttpException"
This is my icon:
<i class="fa fa-trash-o deletebtn" aria-hidden="true" data-pointid="<?php echo $damagePoint->id ?>"></i>
My ajax call:
$(".deletebtn").click(function(ev){
let pointid = $(this).attr("data-pointid");
$.ajax({
url: '/pointdelete/' + pointid,
type: 'delete',
success: function (response) {
}
});
})
My route:
Route::delete('pointdelete/{id}', 'DamagePointController#delete');
My controller method
public function delete($id)
{
$todo = DamagePoint::findOrFail($id);
$todo->delete();
return back();
}
if you are using delete route is like similar to post.Here is the sample code.you can change as per your need
$(".deletebtn").click(function(ev){
let pointid = $(this).attr("data-pointid");
$.ajax({
type: 'DELETE',
url: '/pointdelete',
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: {id:pointid,"_token": "{{ csrf_token() }}"},
success: function (data) {
alert('success');
},
error: function (data) {
alert(data);
}
});
});
Route
Route::delete('pointdelete','DamagePointController#delete');
controller
public function delete(Request $request){
if(isset($request->id)){
$todo = DamagePoint::findOrFail($request->id);
$todo->delete();
return 'success';
}
}
Please check below code:
Route::delete('pointdelete',['as' => 'point.delete','uses' => 'DamagePointController#delete']);
<button class="fa fa-trash-o deletebtn" aria-hidden="true" onclick="delete({{ $damagePoint->id }}"></button>
<script type="text/javascript">
function delete(id){
var _token = "{{ csrf_token() }}";
$.ajax({
url : "{{URL::route('your-delete-route')}}",
type : 'delete',
dataType : 'json',
data : {
'id': id,
'_token':_token
},
beforeSend : function() {
},
complete : function() {
},
success : function(resp)
{
console.log(resp);
}
});
}
</script>
public function delete(Request $request,$id)
{
DamagePoint::destroy($id);
return response()->json(['success' => true],200);
}
Try this kind of ajax call
$(".deletebtn").click(function(ev){
let pointid = $(this).attr("data-pointid");
$.ajax({
url: '/pointdelete/' + pointid,
data : {'_method':'delete','_token':'your csrf token'},
//type: 'delete',
type:'post',
success: function (response) {
}
});
})
Also, verify that what URL is called in request header information in your chrome developer tools.
you just don't need a form try to put your token as {{ csrf_token() }} in ajax.
Recently I got the same error and none of above solutions worked for me in laravel 5.7
I had code something like -
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type:'POST',
async: false,
url:validUrl,
data:{id:1},
success:function(response){
if(response && response.error) {
//show error
} else {
// success
}
}
});
Then I had to set csrf token first using setup method - changed code is something like -
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type:'POST',
async: false,
url:validUrl,
data:{id:1},
success:function(response){
if(response && response.error) {
//show error
} else {
// success
}
}
});

return a json value from an mvc controller method in php

i would like to get an json type value from an mvc controller method. everything is correct but an error occures'.
my jquery ajax function:
function user_login(uname,pass){
$.ajax({
url: 'http://localhost/s/login_request',
type:'POST',
data:{uname:uname,pass:pass},
dataType:"json",
cache: false,
})
.done(function(response){
//do something
alert('1234');
})
.fail(function(jqXHR,textStatus){
alert(JSON.stringify(jqXHR));
});
}
and here is my php code(mvc controller method):
function login_request(){
header('Content-Type: application/json');
echo json_encode(array('testvalue'));
}
when i run the code, the .fail section executed and the following value was returned:
{"readyState":4,"responseText":"[\"testvalue\"]","status":200,"statusText":"OK"}
how can i solve this? thanks...
Try using
$.ajax({
url: 'http://localhost/s/login_request',
type:'POST',
data:{uname:uname,pass:pass},
dataType:"json",
cache: false,
success: function(data) { },
fail: function(xhr, status) { alert(JSON.stringify(xhr)) },
error: function() { },
complete: function() { alert('1234') }
});

How to fix 500 error in AJAX and Laravel 5?

I've been stuck with a 500 (internal server error) for a long time and I don't know why. I need to pass these codes later.
Blade
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function() {
$('#addChirp').submit(function() {
var msg = $('#message').val();
console.log(msg);
var dataString = "message="+msg;
console.log(dataString);
$.ajax({
type: "POST",
url: "post",
data: dataString,
success: function(data) {
console.log(data);
$('#showData').html(data);
},
error: function(data) {
alert("fail");
}
});
});
});
Routes
Route::post('post', function() {
if(Request::ajax()) {
return var_dump(Response::json(Request::all()));
}
});
Try calling Request and Response as a global facade following
Route::post('post', function() {
if(\Request::ajax()) {
return var_dump(\Response::json(\Request::all()));
}
});
If that does not work can you please update your question with full ajax response so problem can be narrowed down?
I think you havn't added any meta value in your head tag of html like
<meta name="csrf_token" content="{{ csrf_token() }}" />
If csrf tag exist than try modify your jax call.
X-CSRF-TOKEN': $('input[name="_token"]').value()
Or, you can manually fetch and pass the value of the _token hidden field in each of your AJAX calls

Categories