Post a form using ajax in Laravel - php

I know this question has been out there many times, however I am unable to get through this.
Here is my route:
Route::post('/masters/board/edit', 'MastersController#editBoard');
My Controller:
public function editBoard() {
$board = Board::findOrFail(Input::get('id'));
$board->nick_name = Input::get('nick_name');
$board->board_name = Input::get('board');
$board->type = Input::get('type');
$board->save();
return Redirect::action('MastersController#getBoards');
}
My JS:
$("#edit_form").submit(function(e) {
e.preventDefault();
var type = "#edit_form";
var formData = {
id : $(type + " #id").val(),
nick_name : $(type + " #nick_name").val(),
name : $(type + " #board").val()
}
$.ajax({
type: "POST",
url: "masters/board/edit",
data: formData,
success: function(data) {
console.log(data);
}
});
});
});
This is throwing an error:
[Error] Failed to load resource: the server responded with a status of 500 (Internal Server Error) (edit, line 0)
Can anyone see a reason why?

Add a meta tag with the csrf_token.
<meta name="_token" content="{{ csrf_token() }}" />
And add that token to your data.
var formData = {
id : $(type + " #id").val(),
nick_name : $(type + " #nick_name").val(),
name : $(type + " #board").val()
_token: $('meta[name="_token"]').attr('content')
}
If you are going to perform lot of post requests try the following.
Use the following script to setup your ajax requests with the csrf token.
$(function() {
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name="_token"]').attr('content')
}
});
});
If you are using laravel 5 this should work out of the box.
If not you need to edit your app/filters.php file.
Replace the csrf filter with the following.
Route::filter('csrf', function() {
$token = Request::ajax() ? Request::header('X-CSRF-Token') : Input::get('_token');
if (Session::token() != $token)
throw new Illuminate\Session\TokenMismatchException;
});

Related

set name to widget's attribute in Twig

I have a field (called name), Every time i write in this field, an ajax script (live search sends data from twig to the controller without reloading) checks if the data already exist or not showing a message. My problem is that i could't set a name for this field, i tried this but it does not work
{{ form_label(form.name) }}
{{ form_widget(form.name,{'id':'name','attr':{'name':'name'}}) }}
{{ form_errors(form.name) }}
and here my function in the controller which i'm sure it works properly,
public function searchBackTeamAction(Request $request)
{
if($request->isXmlHttpRequest())
{
$serializer = new Serializer(array(new ObjectNormalizer()));
$em = $this->getDoctrine()->getManager();
$teams= $em->getRepository('TeamBundle:Team')->findOneBy(['name'=>$request->get('name') ]);
$data = $serializer->normalize($teams);
return new JsonResponse($data);
}
}
and here is my script i'm also sure that it works properly
<script>
$(document).ready(function () {
$("#name").keyup(
function(){
$.ajax({
url: "{{ path('team_searchBack') }}",
data: $("#name").serialize(),
type:"POST",
success: function (data, status, object) {
console.log(data);
if(data.name != null)
{
$("#error_login").css('display','block');
$("#submit").prop('disabled', true);
}
else
{
$("#error_login").css('display','none');
$("#submit").prop('disabled', false);
}
},
error: function(req, textStatus, errorThrown,data) {
//this is going to happen when you send something different from a 200 OK HTTP
console.log('Ooops, something happened: ' + textStatus + ' ' +errorThrown);
},
complete: function() {
// Runs at the end (after success or error) and always runs
}
});
})
}
);
</script>
Could you please help me ?
Use following javascript
<script>
$(document).ready(function () {
$("#name").keyup(
function(){
$.ajax({
url: "{{ path('team_searchBack') }}",
data: {"name": $("#name").val()},
type:"POST",
success: function (data, status, object) {
console.log(data);
if(data.name != null)
{
$("#error_login").css('display','block');
$("#submit").prop('disabled', true);
}
else
{
$("#error_login").css('display','none');
$("#submit").prop('disabled', false);
}
},
error: function(req, textStatus, errorThrown,data) {
//this is going to happen when you send something different from a 200 OK HTTP
console.log('Ooops, something happened: ' + textStatus + ' ' +errorThrown);
},
complete: function() {
// Runs at the end (after success or error) and always runs
}
});
})
}
);

Ajax request on Controller fails

I have a problem with the following code in Laravel. I need to send some variables to my controller, do something with them and return three variables back. I made have made the ajax call, the route and the controller but the ajax call fail. As an error code I receive this.
View
function gg() {
var slider_value = document.getElementById('paradnyi').value;
var checkbox_value = document.getElementById('check_box').value;
var dto = {slider_value : slider_value, checkbox_value : checkbox_value};
$.ajax({
url : "/calc_change",
contentType : 'application/json',
data : JSON.stringify(dto),
type : 'POST',
success: function(data) {
document.getElementById('visits').innerHTML = data[0];
document.getElementById('slaves').innerHTML = data[1];
},
error: function(xhr, str){
alert('Возникла ошибка: ' + xhr.responseCode);
}
});
}
Routes
Route::post('/calc_change',['uses'=>'PagesController#calc_change','as'=>'calc_change']);
Controller
public function calc_change(Request $request){
$data = array();
$data[]=1;
$data[]=2;
//dd($data);
return response()->json($data);
}
You have to add this code before ajax call in jquery section
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});

Laravel 5.3 - jquery ajax (internal server error 500)

I am trying to use jquery ajax in laravel5. What actually happens all the time is consolelog giving me an internal server error 500. I found some csrf solutions and added them to my code but they didnt help me. Any ideas?
$('.takImg').click(function(){
var photoId = $(this).parent().attr('id');
$.ajax({
type : "POST",
url : "/save_like",
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
data: {photoId : photoId},
success : function(msg) {
console.log(msg);
},
complete : function(r) {
console.log(r);
},
error: function(error) {
console.log(error);
}
});
});
I also added this meta to my head:
<meta name="csrf_token" content="{{ csrf_token() }}" />
Everything goes through routes:
`Route::any('/save_like', 'Controller#saveLike');`
To the controller:
public function saveLike($photoId){
DB::update('UPDATE `photo_links` SET likes = likes + 1 WHERE `id` = ?', array($photoId));
}
First the _token should be always sent in the http request so you could just add it to the data :
$('.takImg').click(function(){
var photoId = $(this).parent().attr('id');
var _token = $('meta[name="csrf_token"]').attr('content');
$.ajax({
type: "POST",
url: "/save_like",
data: {_token:_token, photoId:photoId},
success : function(msg) {
console.log(msg);
},
complete : function(r) {
console.log(r);
},
error: function(error) {
console.log(error);
}
});
});
internal server error 500 mean the problem come from your server what mean in your case here it come from the action saveLike in your controller, so my guess is that this problem come from the expression WHEREid= ? :
DB::update('UPDATE `photo_links` SET likes = likes + 1 WHERE `id` = ?', array($photoId));
____________________________________________________________^^^^^^^^^^
You're passing an array to = and that will cause the issue, try :
public function saveLike(){
$photoId = INPUT::get('photoId');
DB::update("UPDATE `photo_links` SET likes=likes+1 WHERE `id` = $photoId");
}
Hope this helps.
That's what i use in my app:
$("#captcha-gen-button").click(function(e){
e.preventDefault();
$.ajax({
url: "/captcha-ajax",
method: "POST",
headers: { 'X-CSRF-Token' : '{!! csrf_token() !!}' }
}).done(function(image) {
$("#captcha-img-container").html(image);
});
});
I think the problem is here:
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
What happened when there is no token? beforeSend won't return anything. Change to this:
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
return xhr;
},

Laravel ajax internal servor 500 (internal server-error)

I have a shopping cart which is stored in session and I want to refresh the session without reloading the page
I have tried this:
View:
Add to cart
<script>
$(document).ready(function() {
$('#product').click(function(event) {
event.preventDefault();
let url = "{{ route('add-to-cart') }}";
let id = $(this).data('id');
$.ajax({
url: url,
type: 'POST',
data: {product_id: id, _token: "{{ Session::token() }}"}
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
});
});
Route:
Route::post('/add-to-cart', 'ProductsController#addToCart')->name('add-to-cart');
ProductsController:
public function addToCart(Request $request)
{
if ($request::ajax()) {
$id = $request->product_id;
$product = Product::find($id);
if (Session::has('products')) {
$products = Session::get('products');
$products[] = $product;
Session::put('products', $products);
}
else {
$products = array($product);
Session::put('products', $products);
}
return response()->json();
}
}
And when I click add to cart it gives 500 (Internal Server Error) in the console
You're accessing the ajax() method statically (using ::), when you should be using -> instead:
if ($request->ajax()) {
Using the Laravel log file
As mentioned in the comments, Laravel is probably telling you this in storage/logs/laravel.log, complete with a long call-stack trace (the lines that you mentioned, beginning with "#38" and "#39"). Just scroll up to before "#1" and you'll find your culprit.
Laravel doesn't allow without passing X-CSRF-TOKEN,
following is my working example hope it helps you.
Route :
Route::post('block-user','UserController#BlockUser');
Now you need to add ajax setup before your ajax call so in
blade.php :
Add this in header
<meta name="csrf-token" content="{{ csrf_token() }}" />
My script like :
<script>
//Ajax setup
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
//Ajax call
$(".blockuser").bootstrapSwitch();
$('.blockuser').on('switchChange.bootstrapSwitch', function () {
var userid = $('#userid').val();
$.ajax({
url:'/block-user',
data:{user_id : userid},
type:'post',
success: function(data){
alert(data);
}
});
});
</script>
Controller :
public function BlockUser(Request $request)
{
$userid = $request->get('user_id');
//perform operation
}

Ajax DELETE redirects even if prevented

I'm trying to delete row from database with DELETE method and using AJAX in my Laravel 5.2 project. Everything is working, picture is deleted from server and the row is deleted from database but after deleting it redirects to JSON response.
My controller's action:
public function deletePhoto(Photo $photo)
{
if ($photo->delete()) {
unlink('files/' . $photo->filename);
unlink('files/thumbs/' . $photo->filename);
return response()->json(['result' => 0]);
}
return response()->json(['result' => 1]);
}
It works this way while adding photos (it adds but doesn't redirect).
Here is my ajax code:
$('#deleteForm').submit(function(e) {
var currentElement = $(this);
var formUrl = $(this).attr('action');
$.ajax({
type: 'POST',
url: formUrl,
data: {_method: 'delete', _token: '{{ csrf_token() }}'},
success: function(data) {
if (data.result == 0) {
currentElement.parent().fadeOut(400, function() {
$(this).remove();
});
} else {
alert('Wystąpił błąd podczas usuwania zdjęcia! Proszę spróbować ponownie!');
}
}
});
return false;
});
I tried many changes (from laracast and stackoverflow) with method, token and data but nothing worked.
How do I solve this problem?
Add a prevent default to your submit event. The page is redirecting because you're initiating a submit event.
e.preventDefault();
Change submit event to:
$("#form-submit-button").click(function(e){
});
try this:
$('#deleteForm').submit(function(e) {
e.preventDefault()
var currentElement = $(this);
var formUrl = $(this).attr('action');
$.ajax({
type: 'POST',
url: formUrl,
data: {_method: 'delete', _token: '{{ csrf_token() }}'},
success: function(data) {
if (data.result == 0) {
currentElement.parent().fadeOut(400, function() {
$(this).remove();
});
} else {
alert('Wystąpił błąd podczas usuwania zdjęcia! Proszę spróbować ponownie!');
}
}
});
return false;
});
you need to add preventDefault to prevent the page from redirecting
check from console if there is errors in javascript code to work the e.preventDefault

Categories