I want to send post request with ajax to controller in laravel. The ajax request send two input arguments and I want controller to find the column in the database with the first argument and then to set the name attribute with the second input argument. But I have this error message in console 500 (Internal Server Error).
Ajax function:
var $emailInput = $('input[name=eemail]').val();
var $finduser = $('[name=userName]').val();
$.ajax({
type:"POST",
url:'/code/task1/public/editUserAdmin',
data: {
'emailInput' : $emailInput,
'finduser' : $finduser,
},
success:function(data){
// $("#editEmail").attr("readonly", true);
// $("#editEmail").val(data[0].name);
alert("OK");
}
});
Route:
Route::post('/editUserAdmin', 'usersController#editUserAdmin');
Controller function:
$findUserInput = $request->input('finduser');
$user = User::where('name',$findUserInput)->first();
if(!$user){
return response()->json(['status'=>false,'Description' => 'User could not be found.']);
}
//$user->name = $request->input('nameInput');
$user->email = $request->input('emailInput');
$user->save();
}
And also i import csrf everywhere because last time when I was making AJAX call i have problem with this csrf and the following code has fixed my problem, but now is not working.
<meta name="csrf-token" content="{{ csrf_token() }}">
$.ajaxSetup({
headers:{
'X-CSRF-TOKEN' : $('meta[name="csft-token"]').attr('content')
}
});
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('[name="_token"]').val()
}
});
and this
<h3 class="media-heading" name="userName">{{ $user->name }}</h3>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="text" class="form-control paddingzero" class=text-center" readonly value="Name Name">
<input type="text" class="form-control paddingzero" class=text-center" name="eemail" id="editEmail" readonly value="{{ $user->email }}">
Any idea?
Ajax does not have a "type" property. You will need to pass POST as method
$.ajax({
method: "POST",
url:'/code/task1/public/editUserAdmin',
data: {
'emailInput' : $emailInput,
'finduser' : $finduser,
},
success:function(data){
alert("OK");
}
});
If you are in dev mode you should enable error loggin / output. You can just open dev tools F12 (in chrome for example) and have a look at the error output. Proably it would be method not allowed or whatever.
Another minor thing is that i would recommend to not prefix actual variables with $ if you do not reference the jquery object.
var $emailInput = $('input[name=eemail]').val();
var $finduser = $('[name=userName]').val();
Instead do
var $emailInput = $('input[name=eemail]'); // if you need it more than once
var email = $emailInput.val();
or if you only need it ones better name it
var emailInput = $('input[name=eemail]').val();
Related
I have a div that has lots of posts which is created dynamically from the database. The div has input for comment facility as well. I have no problems in posting the comments and I do it using a POST method. Then I redirect to the page using return redirect('/'); method. But it links to the beginning to the page which doesn't create a good impression on the user. The user might be in the middle of the page and when he/she comments he will go to the beginning of the page and will have to scroll down again. Luckily, I have the divs with class equal to the post_id. So, isn't there any method to go to the post in which the user posted using that class?
attach the id with the url like /#post-id
Inside your contorller where you are processing and saving the comments:
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\URL;
public function yourCommentSaveFunction()
{
...
//Get the Post ID and store in $postid
return Redirect::to(URL::previous() . '#' .$postid);
}
This should work fine.
But the best way would be to use AJAX to post comments.
Edit (As request by OP)
THE AJAX METHOD
Controller will be something like:
public function saveComment(Request $request)
{
//you do the saving part..
...
$comment = $request->comment;
//after saving the comment return a json response
//you can also send other varibales like username, created at etc..
return Response::json(array(
'success' => true,
'comment' => $comment,
));
}
Route:
Route::post('/save-comment', [
'as' => 'save-comment',
'uses' => 'yourController#saveComment',
]);
And your View:
<form action="{{ route('save-comment') }}" class="comment-form">
<input type="text" name="comment">
<input type="submit" name="submit">
<input type="hidden" name="_token" value="{{ csrf_token() }}"
<div class="comment"></div>
</form>
<script>
$('.comment-form').submit(function(event){
event.preventDefault();
var comment = $this.val();
var token = $('.token').val();
var $url = "{{ route('save-comment') }}";
$.ajax({
url: route,
type: 'POST',
data: {_token: token, comment: comment},
dataType: 'JSON',
success: function (data) {
$(".comment").append('<div class="new-comment">' +data.comment +'</div>');
},
error: function(data) {
console.log("Something went wrong");
}
});
});
</script>
Please note: this is just a sample code.
I've tried doing my research on my issue but have not been able to solve it. I'm attempting to Ajax POST on click. I've read the most popular issue is due to the csrf_token, but I believe I have that handled properly?
I keep getting this error:
POST http://example.com/refreshCalendar 500 (Internal Server Error)
Here is my code...
My meta tag for the csrf token at the top of my master.blade.php file
<meta name="token" content="{{ csrf_token() }}">
Route:
Route::post('/refreshCalendar', ['as' => 'refreshCalendar', 'uses' =>'Calendar#refreshCalendar']);
Js function
function refreshCalendar(obj){
var month = obj.data('month');
var year = obj.data('year');
history.pushState(null, null, '/month/'+month+'/year/'+year);
var data = {
"month":month,
"year":year,
_token:$('meta[name="csrf-token"]').attr('content')
};
$.ajax({
type: "POST",
url: '/refreshCalendar',
dataType: 'html',
async:true,
data: data,
success: function(data){
$('#calendarHolder').html(data);
},
error: function(){alert("There was an error retrieving information");return false;}
});
}
My Controller:
namespace App\Http\Controllers;
use DateTime;
use Illuminate\Http\Request;
class Calendar extends Controller
{
public function refreshCalendar(Request $request)
{
//Set data to $request
$data = $request->all();
return show($data['month'], $data['year'], true);
}
}
<meta name="token" content="{{ csrf_token() }}">
_token:$('meta[name="csrf-token"]').attr('content')
Your meta tag name is token, however you are looking for the meta tag named csrf-token.
If meta is present, you should look to your network for issues.
That was the culprit for me:
The function below is called through a POST request. I need to retrieve URL from my database and open the link in a new tab. I'm using the Redirect::away() function for this. But it gives a MethodNotAllowedHttpException. I have tried calling this function in a GET request and it works perfectly fine.
public function generateURL(Request $request) {
$screenRow = \App\ScreenshotRow::find($request->input('row_ID'));
$baseURL = $screenRow->BaseURL;
$screenshot = \App\Screenshot::where('Setname', '=', $screenRow->Setname)->get();
$pageURL = $screenshot[0]['PageURL'];
if ($baseURL == "") {
return Redirect::away($PageURL);
}
else
return Redirect::away($baseURL);
}
Is there any way to calling this function in response to a POST request?
I would simply use an Ajax Form and redirect the User with Javascript.
Make sure to give your Form an ID
<form id="myForm" method="POST" action="{{ route('your.route') }}">
...
...
<button type="submit">Submit the Form</button>
And make this Form working with Ajax
<script>
$('#myForm [type="submit]').click(function(e){
e.preventDefault();
var form = jQuery(this).parents("form:first");
var dataString = form.serialize();
var formAction = form.attr('action');
$.ajax({
type: "POST",
url : formAction,
data : dataString,
success : function(data){
var url = $.parseJSON(data.responseText);
console.log(data);
// Redirect to a new tab with the given url
window.open(url.success, '_blank');
},
error : function(data){
var error = $.parseJSON(data.responseText);
console.log(error);
// Do what ever you want with an Error Message
alert(error)
}
},"json");
});
</script>
Okay - So if the Form receives a success Message, the success function is executed, otherwise the error function.
Lets go to the Backend Controller which handles the Request
public function generateURL(Request $request) {
$screenRow = \App\ScreenshotRow::find($request->input('row_ID'));
$baseURL = $screenRow->BaseURL;
$screenshot = \App\Screenshot::where('Setname', '=', $screenRow->Setname)->get();
$pageURL = $screenshot[0]['PageURL'];
// Return a JSON Success Message with a Success HTTP Status Code
if ($baseURL == "") {
return response()->json(['success' => $PageURL], 200);
}
// Return a JSON Error Message with a Error HTTP Status Code
else
return response()->json(['error' => $baseURL], 400);
}
Now if your Backend throws a Success Message the success function of the Ajax Form is called which redirects to a new tab based on the given url which you passed in your Backend Controller Success Response.
NOTE
To avoid the tokenmismatchexception on an Ajax Request, you should add the csrf_token to your meta Section in your <head>.
<meta name="csrf-token" content="{{ csrf_token() }}">
And fetch this csrf_token on every Form Request
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
My Blade is:
{!! Form::open(['method' => 'PUT', 'id' => 'confirmTCU',
'action' => ['TournamentUserController#confirmUser', $tournament->slug, $categoryTournament->id,$user->slug ]]) !!}
It generates my Form:
<form method="POST" action="http://laravel.dev/tournaments/bisque/categories/1/users/admin/confirm" accept-charset="UTF-8" id="confirmTCU">
<input name="_method" type="hidden" value="PUT">
<input name="_token" type="hidden" value="tiaIHtctMbo1NwbEK8TqoKOyrN8ZSyeQELSyYL9A">
<button type="submit" class="btn btn-flat text-warning-600 btnConfirmTCU" id="confirm_bisque_1_admin" data-tournament="bisque" data-category="1" data-user="admin">
<i class="text-danger glyphicon glyphicon-remove-sign"></i>
</button>
</form>
My AJAX is:
$('.btnConfirmTCU').on('click', function (e) {
e.preventDefault();
$(this).prop("disabled", true);
var inputData = $('#formDeleteTCU').serialize();
//var tournamentSlug = $(this).data('tournament');
var categoryId = $(this).data('category');
var userSlug = $(this).data('user');
$.ajax(
{
type: 'PUT',
url: url + '/categories/' + categoryId + '/users/' + userSlug + '/confirm',
data: inputData,
success: function (data) {
...
},
error: function (data) {
...
}
}
)
});
My route is:
Route::put('tournaments/{tournamentId}/categories/{categoryTournamentId}/users/{userId}/confirm', 'TournamentUserController#confirmUser');
My Controller is:
public function confirmUser($tournamentSlug, $tcId, $userSlug)
{
$user = User::findBySlug($userSlug);
$ctu = CategoryTournamentUser::where('category_tournament_id', $tcId)
->where('user_id', $user->id)->first();
$ctu->confirmed ? $ctu->confirmed = 0 : $ctu->confirmed = 1;
$ctu->save();
return redirect("tournaments/$tournamentSlug/users");
}
I saw a lot of topics about it, but none resolved my issue.
As PUT is not allowed for most of browser, Laravel send it like POST, but includes a hidden field _method with PUT value.
Beside, I am able to perform DELETE actions, but not PUT...
Besides, method works perfect when not using AJAX.
Where is my problem???
Your code should work fine, but it looks like you are serializing the wrong form. Your current code shows var inputData = $('#formDeleteTCU').serialize();, but the id for the form you've shown is confirmTCU.
Change your ajax type from 'PUT' to 'POST', Laravel will read your parameter '_method' and will take that 'POST' like a 'PUT'.
Hi guys? am trying to post data to the database using laravel 5 and ajax..am also applying using csrf protection by adding
<meta name="_token" content="{!! csrf_token() !!}"/>
to my layout header and adding the following code to my footer:
<script type="text/javascript">
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
</script>
This is my form:
<form action="{{action('QuizController#postQuiz')}}" method="POST">
<div id="name-group" class="form-group">
<label for="name">Please type your question here</label>
<input type="text" class="form-control" name="question">
</div>
<button type="submit" class="btn btn-success">Submit <span class="fa fa-arrow-right"></span></button>
</form>
This is my JS code:
var formData = {
'question' : $('input[name=question]').val(),
};
// process the form
$.ajax({
type : 'POST',
url : 'quiz',
data : formData,
dataType : 'json',
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console to see
console.log(data);
// ALL GOOD! just show the success message!
$('form').append('<div class="alert alert-success">' + data.message + '</div>');
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
This is my route:
Route::post('create/quiz', array(
'as' => 'post-quiz',
'uses' => 'QuizController#postQuiz'
));
When my controller is like the following:
public function postQuiz()
{
if(Request::ajax()) {
$question = Request::get('question');
$data['success'] = true;
$data['message'] = $question;
echo json_encode($data);
}
the ajax call works and it returns,
Object {success: true, message: "test question"}
but when I try posting data to the database using:
public function postQuiz()
{
if(Request::ajax()) {
$question = Request::get('question');
DB::table('questions')->insert([
'question' => $question,
]);
}
I get the following from the console
POST http://localhost/leoschool-laravel5/public/create/quiz 500 (Internal Server Error)
and
Object {readyState: 4, responseText: "{"success":true,"message":"test question"}<!DOCTYPE htm…l>↵</div>↵↵ </div>↵ </body>↵</html>", status: 500, statusText: "Internal Server Error"}
What could be the problem? Thanks..
A good place to start is with Chrome Developer tools. Load your page with the tools open and fire the event that does the AJAX request.
Under the network tab of the tools, it will show you every request made and allow you to preview the response as if you were not using AJAX. This will show you the laravel stack trace. I think the problem is that you're using facades and they're not namespaced correctly.
Change your controller function to this and see if it works:
public function postQuiz()
{
if(\Request::ajax()) {
$question = \Request::get('question');
\DB::table('questions')->insert([
'question' => $question,
]);
}
With the above instruction on how to use dev tools and with the corrected code, you should be able to fix your problem. A better way to write this code would look like this though:
// assuming you have these models setup
// this uses dependency injection
public function postQuiz(Request $request, Question $question)
{
if($request->ajax()) {
$newQuestion = $request->get('question');
//add fields here to create new question with
$question->create([ /*stuff*/ ]);
}