I'm trying to delete a Symfony3 entity with ajax.
Problem is $form->isValid() returns false, but there are no errors on the form (or any child elements). What am I missing here?
Controller
/**
* #Route("/{profileID}/delete", name="profile_delete")
* #ParamConverter("Profile", options={"mapping": {"profileID": "id"}})
* #Method("DELETE")
*/
public function deleteAction(Request $request, Profile $Profile)
{
$form = $this->createDeleteForm($Profile);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->remove($Profile);
$em->flush();
return new JsonResponse(array('message' => 'profile removed'));
} else {
return new JsonResponse(array('message' => 'error'));
}
}
private function createDeleteForm(Profile $Profile)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('profile_delete', array('profileID' => $Profile->getId())))
->setMethod('DELETE')
->getForm()
;
}
Twig
$.ajax({
url: "{{ path('profile_delete', {'profileID': Profile.id}) }}",
type: 'delete',
success:function(data){
console.log(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(textStatus);
console.log(errorThrown);
}
});
You're submitting the form without a csrf-token. A quick fix is to add the token as data:
$.ajax({
url: "{{ path('profile_delete', {'profileID': Profile.id}) }}",
type: 'delete',
data: {
form: {
_token: "{{ csrf_token('form') }}"
}
},
success:function(data){
console.log(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(textStatus);
console.log(errorThrown);
}
});
form here is the form name and could also be set manually. E.g. delete-form:
private function createDeleteForm(Profile $Profile)
{
return $this
->get('form.factory')
->createNamedBuilder('delete-form', FormType::class, null, [
'action' => $this->generateUrl('profile_delete', array('profileID' => $Profile->getId())),
'method' => 'DELETE',
])
->getForm()
;
}
with:
$.ajax({
url: "{{ path('profile_delete', {'profileID': Profile.id}) }}",
type: 'delete',
data: {
'delete-form': {
_token: "{{ csrf_token('delete-form') }}"
}
},
success:function(data){
console.log(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(textStatus);
console.log(errorThrown);
}
});
Related
I am struggling with this code. I am unable to send a response with ajax.
Ajax script is here.
$(document).ready(function () {
$('#selectSize').change(function () {
var idSize = $(this).val();
$.ajax({
type: "get",
dataType: 'json',
url: 'getproductprice',
data: {
idSize: idSize
},
success: function (response) {
console.log("working");
},
error: function () {
console.log("error");
}
});
});
});
Here is the Blade markup
<select name="size" id="selectSize" style="width:150px;">
<option value="">Select Size</option>
#foreach($productDetails->attributes as $size)
<option value="{{$productDetails->id}}-{{$size->size}}">{{$size->size}}</option>
#endforeach
</select>
And here is the controller code
public function getProductPrice(Request $request)
{
$data = $request->all();
$proArr = explode("-", $data['idsize']);
$proAttr = ProductsAttribute::where(['product_id' => $proArr[0], 'size' => $proArr[1]])->first();
$getCurrencyRates = Product::getCurrencyRates($proAttr->price);
echo $proAttr->price . "-" . $getCurrencyRates['USD_Rate'] . "-" . $getCurrencyRates['GBP_Rate'] . "-" . $getCurrencyRates['EUR_Rate'];
echo "#";
echo $proAttr->stock;
}
I do not know, What I am doing wrong .when I select option value.
error will come like.
"Trying to get property 'image' of non-object (View:
C:\xampp\htdocs\wrost\resources\views\shop\product-details.blade.php)"
Your ajax should be -
$.ajax({
url: 'getproductprice',
type: 'POST',
data: {idSize: idSize},
beforeSend: function (request) {
return request.setRequestHeader('X-CSRF-Token', $("meta[name='csrf-token']").attr('content'));
},
success: function (response) {
console.log(response);
},
error: function (err) {
console.log(err);
alert("Something Went Wrong, Please check again");
}
});
First make sure you add meta tag for csrf in your head
<meta name="csrf-token" content="{{ csrf_token() }}">
At last you need to add header object in your ajax object
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
it will be like this
$.ajax({
type: "get",
dataType : 'json',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url:'getproductprice',
data: {idSize: idSize},
success:function(response){
console.log("working");
},
error:function(){
console.log("error");
}
});
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
}
}
});
I want to return data from my database with .ajax() but it throws out an error with the entire HTML of a page. Why is it doing that?
My .ajax() call:
$.ajax({
url: '{{ URL('reports/groupsUsersGet') }}',
dataType: "json",
data: {
group_id : $('#group').val(),
},
success: function(data) {
alert(data);
},
error: function (data) {
console.log('Error:', data);
}
});
route
Route::get('reports/groupsUsersGet',
array(
'as' =>'groupsUsersGet',
'uses' => 'ReportsController#groupsUsersGet'
)
);
view(form)
{{ Form::select('grup',$group,null,['class'=>'form-control','id'=>'group']) }}
controller
$term = Input::get('group_id');
$results = array();
DB::table('users')->where('group', 'LIKE', '%'.$term.'%')->get();
foreach ($queries as $query) {
$results[] = [
'id' => $query->id,
'value' => $query->nick
];
}
return Response::json($results);
Also send the csrf_token() as data.
$.ajax({
url: '{{ URL('reports/groupsUsersGet') }}',
dataType: "json",
data: {
_token: <?php echo csrf_token();?>,
group_id : $('#group').val(),
},
success: function(data) {
alert(data);
},
error: function (data) {
console.log('Error:', data);
}
});
It seems to me that you aren't sending CSRF token in the request, as #HikmatSijapati specified. In ajax request you can pass csrf token like this:
You could, for example, store the token in a HTML meta tag:
<meta name="csrf-token" content="{{ csrf_token() }}">
Then, once you have created the meta tag, you can instruct a library like jQuery to automatically add the token to all request headers. This provides simple, convenient CSRF protection for your AJAX based applications:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Hope this helps!
Try this:
In your controller you can't define $queries variable inside your method.
ajax call
$.ajax({
url: "{{ URL('reports/groupsUsersGet') }}",
method: 'GET',
dataType: "json",
data: {
group_id : $('#group').val(),
},
success: function(data) {
alert(data);
},
error: function (data) {
console.log('Error:', data);
}
});
controller
$term = Input::get('group_id');
$results = array();
$queries = DB::table('users')->where('group', 'LIKE', '%'.$term.'%')->get();
foreach ($queries as $query) {
$results[] = [
'id' => $query->id,
'value' => $query->nick
];
}
return Response::json(['results' => $results], 200);
Thank you everyone for your help but the error was in my not including use Response at the top of controller. When I did that it worked.
Trying to get AJAX image upload working on Laravel 4 but having issues.
This is what I have:
The form:
{{ Form::open(array('class' => 'update-insertimage-form', "files" => true,)) }}
{{ Form::file('image', array('class' => 'update-insertimage-btn', 'name' => 'update-insertimage-btn')) }}
{{ Form::close() }}
And the PHP:
$createImage = Image::make(Input::file('update-insertimage-btn'))->orientate();
$createImage->resize(600, null, function ($constraint) {
$constraint->aspectRatio();
});
$createImage->save("user_uploads/cover_images/TEST.jpeg");
jQuery:
$('.update-insertimage-form').submit(function() {
$(".submit-newupdate-btn").addClass('disabled');
var rootAsset = $('.rootAsset').html();
$.ajax({
url: rootAsset+'saveUploadedImage',
type: 'post',
cache: false,
dataType: 'json',
data: $('.update-insertimage-form').serialize(),
beforeSend: function() {
},
success: function(data) {
if(data.errors) {
$('.modal-body').append('<div class="alert alert-danger centre-text modal-error-message" role="alert"><strong>Error!</strong> '+ data.errors +'</div>');
} else if (data.success) {
$(".form-control-addupdate").append(data.name);
}
},
error: function(xhr, textStatus, thrownError) {
alert('Something went to wrong.Please Try again later...');
}
});
return false;
});
I use this same exact code else where which works fine but not with AJAX.
The error is this:
{"error":{"type":"Intervention\\Image\\Exception\\NotReadableException","message":"Image source not readable","file":"\/Applications\/MAMP\/htdocs\/buildsanctuary\/vendor\/intervention\/image\/src\/Intervention\/Image\/AbstractDecoder.php","line":257}}
Any help?
Note, tried using formData and changed the jQuery to:
$('.update-insertimage-form').submit(function() {
$(".submit-newupdate-btn").addClass('disabled');
var rootAsset = $('.rootAsset').html();
var formData = new FormData();
formData.append('update-insertimage-btn[]', $('.update-insertimage-btn')[0].files[0], $('.update-insertimage-btn')[0].files[0].name);
$.ajax({
url: rootAsset+'saveUploadedImage',
type: 'post',
cache: false,
dataType: 'json',
data: formData,
processData: false,
contentType: false,
beforeSend: function() {
},
success: function(data) {
if(data.errors) {
$('.modal-body').append('<div class="alert alert-danger centre-text modal-error-message" role="alert"><strong>Error!</strong> '+ data.errors +'</div>');
} else if (data.success) {
$(".form-control-addupdate").append(data.name);
}
},
error: function(xhr, textStatus, thrownError) {
alert('Something went to wrong.Please Try again later...');
}
});
return false;
});
But that is throwing the error:
{"error":{"type":"ErrorException","message":"preg_match() expects parameter 2 to be string, array given","file":"\/Applications\/MAMP\/htdocs\/buildsanctuary\/vendor\/intervention\/image\/src\/Intervention\/Image\/AbstractDecoder.php","line":208}}
Thanks for any help.
Try passing the form to the FromData contructor instead of trying to manually add the file to it.
var formData = new FormData($('.update-insertimage-form')[0]);
I want to perform multiple operation when i select value from dropdownbox for that i am using ajax in larvel.My problem is when i select dropdown list value it get passsed through the ajax,from ajax it calls controller based on that i want fetch required filed from datatabase but ajax does not return any success result.Here is my code.
view
{{ Form::select('asset_type_id', $assettype_list,
Input::old('asset_type_id', $assetdetail->asset_type_id), array('class'=>'select2','id'=>'asset_type_id', 'style'=>'width:350px')) }}
ajax
$(document).ready(function() {
$("#asset_type_id").change(function() {debugger;
// alert($('#asset_type_id option:selected').val());
var data=$('#asset_type_id option:selected').val()
$.ajax({
type: 'POST',
url: '/Controllers/Admin/AssetdetailsController',
data: data,
cache: false,
success: function(data)
{
check(data);
},
error: function(xhr, textStatus, thrownError) {
alert('Something went to wrong.Please Try again later...');
}
});
});
});
controller
public function postPositions($data)
{
if (Request::ajax())
{
$positions = DB::table('asset_types')->select('is_nesd')->where('id', '=', $data)->get();
return $positions;
}
}
route
Route::post('Controllers/Admin', [usesu'Controllers\Admin\AssetdetailsController#postPositions');
In your ajax, try to change the URL:
$(document).ready(function() {
$("#asset_type_id").change(function() {debugger;
// alert($('#asset_type_id option:selected').val());
var data=$('#asset_type_id option:selected').val()
$.ajax({
type: 'POST',
url: '{{ URL::route('post_form') }}',
data: data,
cache: false,
success: function(data)
{
check(data);
},
error: function(xhr, textStatus, thrownError) {
alert('Something went to wrong.Please Try again later...');
}
});
});
});
And in your route (see Laravel 4 Docs)
Route::post('Controllers/Admin', array('uses' => 'Controllers\Admin\AssetdetailsController#postPositions', 'as'=>'post_form'));
Update
To solve the error with the controller, try this:
public function postPositions()
{
if (Request::ajax())
{
$data = Input::get('form_data');
$positions = DB::table('asset_types')->select('is_nesd')->where('id', '=', $data)->get();
return $positions;
}
}
And the JS code:
$(document).ready(function() {
$("#asset_type_id").change(function() {debugger;
// alert($('#asset_type_id option:selected').val());
var f_data=$('#asset_type_id option:selected').val(); // changed
$.ajax({
type: 'POST',
url: '{{ URL::route('post_form') }}',
data: { form_data: f_data }, // changed
cache: false,
success: function(data)
{
check(data);
},
error: function(xhr, textStatus, thrownError) {
alert('Something went to wrong.Please Try again later...');
}
});
});
});
you may need to change URL to url: '/Controllers/Admin'.
Because you made Route as Controllers/Admin.
View:
{{ Form::open(array('url' => 'crud', 'method' => 'get', 'id' => 'myform', 'name' => 'myform')) }}
{{ Form::select('application',$download_options, Input::get('application'),$options = array('id' => 'application', 'class' => 'application')) }}
{{ Form::label('date', 'date', array('id' => 'date_label')); }}
{{ Form::select('date', $options = array('id' => 'date', 'class' => 'date')) }}
{{ Form::submit('Display', array('class' => 'btn btn-small btn-info', 'id' => 'submit')) }}
{{ Form::close() }}
<script>
$(document).ready(function($) {
$('#application').change(function(e){ // e=event
var application = $('#application option:selected').val();
$.getJSON('/getdata/'+application, function(data){
$('select#date').html('$'+data);
});
});
});
</script>
Route:
Route::get('getdata/{application}', function($application){
$selectboxtwo = DB::table('downloads')
->where('application', '=',$application)
->groupBy('date')
->lists('date');
return $selectboxtwo;