Laravel 5 Route Not Found 404 - php

I am trying to post user emails to subscribe to my site but my console keeps giving me a 404 exception for the route. I have a table called betas, and a model called Beta in App\Beta.php. Here is my route:
use App\Beta;
use Illuminate\Http\Request;
Route::post('/email',['middleware'=>'csrf',function (Request $request){
$validator=Validator::make($request->all(),[
'email' => 'required|max:64|email|unique:betas,email'
]);
//if validator passes save the email in the database
if($validator->passes()){
$beta = new App\Beta;
$beta->email=$request->email;
$beta->save();
$response=array(
'status' => 'Email posted successfully'
);
}
else{
$messages = $validator->messages();
$response=array(
'messages' => $messages->first('email'),
'status' => 'Email post failed',
);
}
return response()->json($response);
}]);
Below is my js file:
$("#betaForm").submit(function(){
$(".loadingPic").show();
var email=$("#emailInput").val();
console.log("email:"+email);
//pause for a bit to see pretty loading icon
console.log("before setTimeout");
var load=setTimeout(function(){return undefined;}, 1000);
console.log("after setTimeout");
if(email==""){
$("#warningMessage").html("please input your email");
$("#warningMessage").show();
}
else{
$.post({
url: $(this).prop('action'),
data: {
"_token": $( this ).find( 'input[name=_token]' ).val(),
"email": email
},
success: function(result){
if (result.status!='Email posted successfully'){
$("#warningMessage").html(result.messages);
$("#warningMessage").removeClass( "alert-success");
$("#warningMessage").addClass("alert-danger");
$("#warningMessage").show();
}
else{
$("#betaForm button").prop("disabled",true);
$("#betaForm button").html("Awesome! Well Be In Touch.");
}
},
dataType: 'json'
});
}
$(".loadingPic").hide();
return false;
});
When the submit button is pressed, I receive the error in my browser console.

I think issue on 'middleware'=>'csrf'.

Related

AJAX Post, Codeigniter 4 /PHP - The controller is not catching the posted data

I have the below ajax js. I am trying to make a POST to my controller with the id . In the line starting with let id ... when I log it to console, I can see the id number but the controller doesn't receive it. Also in XHR/payload I see [object Object] which do not know why.
$(document).on('click', '.delete-task', function(event){
// id comes from data-id
let id = $(event.currentTarget).attr('data-id');
$.ajax({
url: ajaxUrl+'/admin/tasks/delete',
type: 'POST',
// what data you passing.
data: {
'id' : id
},
processData: false,
contentType: false,
dataType: 'json',
success: function(data) {
console.log(data);
}
});
});
Route is; $routes->match(['get', 'post'], '/admin/tasks/delete', 'Admin\Task\Task_Controller::task_delete');
For my controller, I have the below. As it is a post, I expect to be able to get the id by using $this->request->getVar('id') but doesn't work. I always get 'success' => '0 'msg' => "No Task To Delete" returned. Any pointers appreciated.
```
public function task_delete(){
$id = $this->request->getVar('id');
if(empty($id)){
$response = [
'success' => 0,
'msg' => "No Task To Delete",
];
echo json_encode($response);
} else {
$task = new TaskModel();
$task->task_delete($id);
$response = [
'success' => 1,
'msg' => "Task Deleted",
];
echo json_encode($response);
}
}```
So I can see id=103 in the payload in the console but for somereason but reaching the controller. Interesting also is when I log log_message('error', $request->getMethod()); it is a critical error as blank. Even log_message('error', $request->isAjax()); is critical error as blank.

CodeIgniter4: Resubmitting form using Ajax giving 403 Forbidden

I'm working on a project in CodeIgniter4. I'm trying to make an Ajax call to an endpoint (/adjustments/store). I'm validating the form using CodeIgniter and showing the validation errors in my view. The issue is when the first time, i submit the form, it works and shows some validation errors. But when i fill the form correclty (to get not validation errors) and resubmit it again it gives me 403 forbidden error in the console.
Ajax call
$.ajax({
type: 'post',
url: '/adjustments/store',
dataType: 'html',
data: {
number,
date,
type,
account,
description,
adjData,
csrf_test_name
},
success: function (res) {
if (IsJsonString(res)) {
const response = JSON.parse(res);
if (response.hasOwnProperty('validation_errors')) {
const errors = response.validation_errors;
for (err in errors) {
$(`input[name=${ err }]`)
.parent()
.append(`<small class="text-danger">${ errors[err] }</small>`)
}
}
}
function IsJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
console.log(res);
}
CodeIgniter Controller
public function store () {
$data = $this->request->getPost(NULL);
// Validate
if (! $this->validate([
'number' => 'required',
'date' => 'required',
'type' => 'required',
'adjData' => 'required',
]))
{
echo json_encode(['validation_errors' => $this->validator->getErrors()]);
return;
}
echo json_encode($data);
}
Any solution to this?
If you are resubmitting a form then you have update csrf token on every request with ajax.
Whenever validation fails pass csrf token and update it every time.
In your controller -
public function store () {
$data = $this->request->getPost(NULL);
// Validate
if (! $this->validate([
'number' => 'required',
'date' => 'required',
'type' => 'required',
'adjData' => 'required',
]))
{
echo json_encode(['validation_errors' => $this->validator->getErrors(), 'csrf' => csrf_hash()]);
return;
}
echo json_encode($data);
}
In you ajax -
$.ajax({
type: 'post',
url: '/adjustments/store',
dataType: 'html',
data: {
number,
date,
type,
account,
description,
adjData,
csrf_test_name
},
success: function (res) {
if (IsJsonString(res)) {
const response = JSON.parse(res);
$("input[name='csrf_test_name']").val(response ["csrf"]);
if (response.hasOwnProperty('validation_errors')) {
const errors = response.validation_errors;
for (err in errors) {
$(`input[name=${ err }]`)
.parent()
.append(`<small class="text-danger">${ errors[err] }</small>`)
}
}
}
function IsJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
So once you update csrf then it will work fine.
Thanks.

500 Error in Laravel with Ajax post

I've got 6 different routes that can be chosen from an input select. Each selected route then posts to its own database.
The problem is I get a 500 error back for all of them, but on half of them, it actually posts to the database. I've gone through line-by-line, and other than the variable names, the code is identical. Here's an example of one that doesn't work at all.
submit.js
$('#submit-event').on('click', function() {
event.preventDefault()
let title = $('#title').val()
let type = $('#type').val() // for selecting which DB
let start = $('#start').data('DateTimePicker').date()
let end = $('#end').data('DateTimePicker').date()
let data = {
'_token': token,
'title': title,
'start': start,
'end': end
}
console.log(type); // logs the correct POST route
$.ajax({
method: 'POST',
url: type,
data: data,
success: function(data) {
console.log(data);
},
error: function(err) {
console.log(err)
}
});
})
routes.php
Route::post('/createmeeting', [
'uses' => 'MeetingController#postCreateMeeting',
'as' => 'createmeeting'
]);
MeetingController.php
class MeetingController extends Controller
{
// Get Meeting from DB - works
public function getMeetings()
{
$meetings = Meeting::orderBy('created_at', 'desc')->get();
return $meetings;
}
// Add new Meeting to DB - doesn't work (500 error)
public function postCreateMeeting(Request $request)
{
if (!request['_token']) {
return redirect()->route('calendar')->with(['message' => "You must be logged in"]);
}
// Save Meeting
$meeting = new Meeting();
$meeting->title = $request['title'];
$meeting->start = $request['start'];
$meeting->end = $request['end'];
if ($request->user()->meetings()->save($meeting)) {
$message = 'Event successfully added to calendar';
return redirect()->route('calendar')->with(['message' => $message]);
}
return redirect()->route('calendar')->with(['message' => $message]);
}
}
Responses to similar problems suggest a problem with the token, but I test for that here. Any idea where the mistake could be happening?

Codeigniter always return error message

I tried to convert the codeigniter form handling using ajax then display validation error if validation is false but in my current state, it always throw an error. Check the code below for reference.
PHP:
public function add () {
$post_data = $this->input->post('formdata');
$data = array (
'identity' => $post_data ['email'],
'password' => $post_data ['password'],
'email' => $post_data ['email'],
'group' => array($post_data['group_id']),
'additional_data' => array (
'first_name' => $post_data['first_name'],
'last_name' => $post_data['last_name'],
'active' => $post_data['active'],
'date_registered' => date('Y/m/d h:i:sa')
)
);
// custom error message
$this->form_validation->set_message('alpha_dash_space', '%s appears to be invalid. Must contain only alphabets.');
$this->form_validation->set_message('matches', '%s does not match the Confirm Password field. ');
if ($this->form_validation->run() == TRUE) {
$result['data'] = $this->ion_auth->register($data['identity'], $data['password'], $data['email'], $data['additional_data'], $data['group']);
} else {
$result['message'] = validation_errors();
}
echo json_encode($result);
}
JS:
function submit_form (form_id) {
var url = $(form_id).attr("action");
var formData = {};
$(form_id).find("input[name]").each(function (index, node) {
formData[node.name] = node.value;
});
$(form_id).find('select[name]').each(function (index, node) {
formData[node.name] = node.value;
});
$(form_id).find('textarea[name]').each(function (index, node) {
formData[node.name] = node.value;
});
$.ajax({
type: "POST",
data: {
'formdata': formData
},
url: url,
dataType: 'json',
success: function(result) {
if (result.data) {
console.log(success);
swal({
title: "Success!",
text: "You've done it great!",
type: "success"
},
function(){
location.reload();
});
} else {
$('#error-msg').html(result.message);
}
},
error: function(data) {
swal({
title: "Error!",
text: "Oops, something went wrong. Check and try again.",
type: "error"
});
}
});
}
Note: Form validation are set in config directory. So no issues in form rules. All are running good except I think the jquery that handles the condition.
Edit like below:
if ($this->form_validation->run() == FALSE) {
$result['message'] = validation_errors();
} else {
$result['data'] = $this->ion_auth->register($data['identity'],
$data['password'], $data['email'], $data['additional_data'],
$data['group']);
}
Also you have set_message but not set_rules. If you want to use form_validation library, you should set some rules.

Ajax call returning CSRF-token on success and not returning messages

This issue works fine when calling ajax from PHP, but I can't seem to get it working with Laravel 5.2. All I'm trying to do is send an email using AJAX when submitting a form.
This is my routes.php entry for sending the email:
Route::post('/send', 'CommsController#send');
And this is my layout.blade.php file:
<head>
<meta name="csrf-token" content="{{ csrf_token() }}" />
</head>
$( document ).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
...
$( "#send" ).button().click(function(event) {
var form = $( "#contact-form" ),
postAction = form.attr('action'),
isValid = form.valid(),
valSum = $(".validation-summary");
if ( isValid ) {
var postData = {
message_type: "contact"
,first_name: first_name.val()
,last_name: last_name.val()
,email: email.val()
,message: message.val()
};
// process the form
$.ajax({
type: "POST",
// our data object
url: postAction, // the url where we want to POST
data: postData
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
if ( ! data.success ) {
valSum.removeClass( "success" );
valSum.addClass( "validation-summary error" );
valSum.html( data );
} else {
// $( ".validation-summary" ).html( "Message sent." );
valSum.html( data.message );
}
})
// using the fail promise callback
.fail(function(data) {
// show any errors
// best to remove for production
console.log(data);
valSum.removeClass( "success" );
valSum.addClass( "validation-summary error" );
valSum.html( "Server Error: " + data.statusText + " processing your request, please contact Dorothea or report a bug." );
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
} else {
return false;
}
});
And finally here is my CommsController send() function:
public function send(Request $request) {
//check if its our form
if ( Session::token() !== Request::get( 'csrf-token' ) ) {
return Response::json( array(
'message' => 'Unauthorized attempt to create setting'
));
}
$message_type = strval(Request::input('message_type'));
$first_name = strval(Request::input('first_name'));
$last_name = strval(Request::input('last_name'));
$email = strval(Request::input('email'));
$message = strval(Request::input('message'));
$to = "robinson.jeanine6#gmail.com";
// subject
$subject = "Dorothea - Contact Us";
Mail::send('email.contact', ['request' => Request::all()], function ($message) use ($request) {
$message->from($this->email, $this->email);
$message->to($user->email, $user->email)->subject($subject);
});
$response = array(
'status' => 'success',
'message' => 'Message sent.',
);
return Response::json( $response );
}
This question is related to the one I posted here, but instead of getting a MethodNotAllowedHttpException, all that been returned now from the AJAX call is the CSRF-token value.
Replace .done callback with .success to get the return data.
.success(function(data) {
if (data.status != 'success' ) {
valSum.removeClass( "success" );
valSum.addClass( "validation-summary error" );
}
// eventually, print out the return message
valSum.html(data.message);
})
Just wanted to let everyone that tried to help me out know that sending of emails works fine in Laravel if I change the post request to a get request.
Not too sure why this is, so if anyone can shed some light as to why this would be the case that would be great.

Categories