Laravel 5.3 - jquery ajax (internal server error 500) - php

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;
},

Related

laravel ajax delete account and reregistering not working properly

new to laravel and Jason. i have this project at hand and i have to give the user the option to delete their account.
now i succeed in deleting the user from the database but there is another issue now.
the issue is. i register. and then i delete my account. but when i try to log in. it says the account exists. but the account no longer exists in the database. but when i tried logging in, it just logged me in and created a new id and username for the user in the database.
i tested this on multiple devices, pages, and even after days of deleting the account and they are all like that.
(it worked perfectly fine before adding the user delete option)
i thought it might be cookies but even when deleting the cookies it didn't work. someone suggested that there might be a secondary database but i didn't find anything.
(note: i noticed the update user info section and the URL is using firebase-auth. i tried searching for how to do that but i didn't find anything so i don't know how to delete the user using auth in laravel using ajax)
for testing, i removed the section of the code where it logs you out after deleting the account and in the console, i still get the user id which is weird. i have also updated the js code too.
in the console i get the:
the user's id
"response it worked"
and in the network, I'm not getting anything worth mentioning.
I'm also not getting anything in the console from logging in
edit: Thanks to Frank van Puffelen who answered i was able to solve this issue. this is how i used it in my code in case someone wanted to know
i just put this code right before the ajaxssetup function when deleting the user
const user=firebase.auth().currentUser;
user.delete().then(()=>{
console.log("account deleted succssfully");
}).catch((error) =>{
console.log(error);
});
this is what the codes look like
public\assets\js\common.js
//this is the login and register code
const firebaseConfig = {
apiKey: fireapiKey,
authDomain: authDomain,
projectId: projectId,
storageBucket: storageBucket,
messagingSenderId: messagingSenderId,
appId: appId,
measurementId: measurementId
};
firebase.initializeApp(firebaseConfig);
firebase.analytics();
$("#loginWithEmail").on("submit", function (event) {
event.preventDefault();
var loginbtn45 = document.getElementById("loginWithEmailBtn");
loginbtn45.textContent = `${localLOGGINGINPLEASEWAIT}`
firebase.auth().signInWithEmailAndPassword($('#inputEmail').val(), $('#inputPassword').val()).then(function (response) {
console.log(response);
$(".loader").show();
loginbtn45.textContent = `${localLOGIN}`
if (response.user.emailVerified == true) {
$.ajax({
type: "POST",
dataType: 'json',
data: {
"_token": "{{ csrf_token() }}",
'identity': $('#inputEmail').val(),
'firstname': "D",
'email': $('#inputEmail').val(),
'lastname': null,
'login_type': "fireBaseLogin",
'device_type': 3,
'device_token': "nothing"
},
headers: {
'apikey': 123
},
url: `${baseUrl}register`,
success: function (data) {
$('.signOutModal').modal('hide');
iziToast.success({
timeout: 2000,
title: `${locallOGINsuccessfully}`,
position: "topRight"
})
localStorage.setItem('userObject', JSON.stringify(data.data));
$(".loader").hide();
},
error: function (data) {
$(".loader").hide();
console.log(data);
}
});
} else {
$(".loader").hide();
iziToast.error({
icon: 'fas fa-times-circle',
message: `${localVerifyYourEmail}`,
position: "topRight"
});
}
})
.catch(function (error) {
console.log(error);
$(".loader").hide();
loginbtn45.textContent = `${localLOGIN}`
iziToast.error({
icon: 'fas fa-times-circle',
message: error.code,
position: "topRight"
});
})
});
//------------
$("#registerForm").on("submit", function (event) {
event.preventDefault();
var fullname = $("#fullname").val();
var email = $("#email").val();
var password = $("#password").val();
var confirmPassword = $("#confirmPassword").val();
if (password.length < 6) {
iziToast.error({
icon: 'fas fa-times-circle',
message: `${localPasswordLength}`,
position: "topRight"
});
} else {
if (password != confirmPassword) {
iziToast.error({
icon: 'fas fa-times-circle',
message: `${localPasswordNotMatch}`,
position: "topRight"
});
} else {
$(".loader").show();
$('#registerUser').text(`${localREGISTERINGPLEASEWAIT}`)
firebase.auth().createUserWithEmailAndPassword(email, password).then(function (response) {
sendingVerifyEmail();
console.log(response);
$('#registerUser').text(`${localREGISTERED}`)
$.ajax({
type: "POST",
dataType: 'json',
data: {
'identity': email,
'firstname': fullname,
'email': email,
'lastname': null,
'login_type': "firebasLogin",
'device_type': 3,
'device_token': "nothing"
},
headers: {
'apikey': 123
},
url: `${baseUrl}firebaseRegister`,
success: function (data) {
console.log(data);
$(".loader").hide();
iziToast.success({
timeout: 2000,
title: `${localRegistersuccessfully}`,
position: "topRight"
})
$('#registerForm')[0].reset();
},
error: function (data) {
$(".loader").hide();
console.log(data);
}
});
})
.catch(function (error) {
$(".loader").hide();
console.log(error);
$('#registerUser').text(`${localREGISTERED}`)
if (error.code == "auth/email-already-in-use") {
iziToast.error({
icon: 'fas fa-times-circle',
message: `${localUserAllreadyExist}`,
position: "topRight"
});
} else {
iziToast.error({
icon: 'fas fa-times-circle',
message: `${localEnterValideEmail}`,
position: "topRight"
});
}
})
function sendingVerifyEmail() {
firebase.auth().currentUser.sendEmailVerification().then(function (response) {
$('#registerUser').text(`${localREGISTERED}`)
console.log(response);
})
.catch(function (error) {
console.log(error);
$('#registerUser').text(`${localREGISTERED}`)
})
}
}
}
});
$(".delteuserbtn").on('click', function (e1){
e1.preventDefault();
$('.deltetemodal').modal('show');
$(".delteuserbtnyes").on('click', function (e2){
e2.preventDefault();
var theuser = localStorage.getItem('userObject');
if(theuser != null){
theuser = JSON.parse(theuser);
userid=theuser.id;
}
console.log(userid);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "DELETE",
url: "deleteAccount/"+userid,
dataType: "JSON",
success: function (response){
console.log('response it worked');
$(".deltetemodal").modal('hide');
$(".updateProfileModal").modal('hide');
localStorage.removeItem("userObject");
$('.userName').text("")
$('.useremail').text("")
$(".usersideImage").attr('src',"")
$('.signInRemove').removeClass('d-none');
$(".userLoginDiv").css("display", "none");
iziToast.success({timeout: 2000, title: localAccDeletedSuccess,position: "topRight"})
window.location.href = `${appUrl}`;
},
error: function(xhr) {
console.log(xhr.responseText); // this line will save you tons of hours while debugging
// do something here because of error
}
});
});
$(".delteuserno").on('click', function (e){
$(".deltetemodal").modal('hide');
$(".updateProfileModal").modal('hide');
});
});
$("#updateform").on('submit',function(event) {
event.preventDefault();
$(".loader").show();
var updatedata = localStorage.getItem('userObject');
updatedata = JSON.parse(updatedata);
var formdata = new FormData($("#updateform")[0]);
formdata.append('id',updatedata.id);
console.log(formdata);
$.ajax({
url: `${baseUrl}updateProfile`,
type: 'POST',
beforeSend: function(xhr) {
xhr.setRequestHeader('apikey',apikey);
xhr.setRequestHeader('userId',updatedata.id);
},
data: formdata,
dataType: "json",
contentType: false,
cache: false,
processData: false,
success: function(response) {
console.log(response)
$(".loader").hide();
iziToast.success({timeout: 2000, title: `${localUpdateSuccessfull}`,position: "topRight"})
localStorage.setItem('userObject',JSON.stringify(response.data));
$image = `${fimageUrl}${response.data.image}` ;
$(".usersideImage").attr('src',$image)
$('.userName').text(response.data.firstname)
$('.useremail').text(response.data.email)
$('.updateProfileModal').modal('hide');
},
error: function(err) { console.log(JSON.stringify(err)); }
});
});
routes/web.php
<?php
use App\Http\Controllers\ViewController;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Route;
Route::delete('deleteAccount/{id}' , [App\Http\Controllers\UserController::class, 'destroy']) ->name('destroy');
http/Controller/userController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
class UserController extends Controller {
public function destroy($id){
/* $user = users::find($id);
$user ->delete(); */
DB::table('users')->where('id', $id)->delete();
return response()->json([
'status' =>200,
'message'=>'Account Deleted Successfully',
]);
/* $directory=storage_path('framework/views');
$files=\File::allFiles($directory);
\File::delete($files); */
}
}
As far as I can see, you do two things when you create a user:
You create the user in Firebase Authentication, by calling createUserWithEmailAndPassword .
You create a record for the user in your database.
But when you delete the user, you only delete them from the database. So that means the user can indeed still log in with Firebase Authentication, since you didn't delete it from there
To also delete the user from Firebase Authentication, call delete on their profile as shown in the documentation on deleting the current user.

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
}
});
})
}
);

500 (Internal Server Error) in Laravel

Please help. I have this jQuery code
$('.modal-footer').on('click', '.edit', function() {
var serializedData = $(".form-horizontal").serialize();
var criscore = new Array();
$('input[name^=criscore]').each(function(){
criscore.push({score:$(this).val(), criid:$(this).data('criid')});
});
for (var key in criscore) {
var score = criscore[key].score;
var criid = criscore[key].criid;
//console.log(score +" s "+ criid);
$.ajax({
method: 'post',
url: '/judges/candidates/scorecandidates',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: {
'_token': $('input[name=_token]').val(),
'canId': $('input[name=canId]').val(),
'catId': $('input[name=catId]').val(),
'criId': criid,
'score': score,
'judgeId': $('input[name=judgeId]').val()
},
success: function(data) {
console.log(data);
}
});
}
});
and in my controller is
public function scorecandidates(Request $req)
{
$data = new Score();
$data->canId = $req->canId;
$data->catId = $req->catId;
$data->criId = $req->criId;
$data->score = $req->score;
$data->judgeId = $req->judgeId;
$data->save();
return response()->json($data);
}
my problem is that it is still keeps having an 500 (Internal Server Error)
Even though I already put the csrf token is different ways.. Can any body help me?
Thank you

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

Post a form using ajax in Laravel

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;
});

Categories