$this->validate causes "Failed to load response data" - php

I have the following external form:
<form method="POST" action="http://infused.local/leads/post">
<div class="form-group">
<label>first_name</label>
<input type="text" name="first_name" class="form-control">
</div>
<div class="form-group">
<label>last_name</label>
<input type="text" name="last_name" class="form-control">
</div>
<div class="form-group">
<label>email</label>
<input type="text" name="email" class="form-control">
</div>
<div class="form-group">
<label>postal_code</label>
<input type="text" name="postal_code" class="form-control">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
Which points to the following controller method:
public function post()
{
$this->validate(request(), [
'email' => 'required|email',
]);
echo 'hello';
}
Via this route:
Route::post('leads/post', 'LeadController#post');
I've disabled CSRF protection for the form route.
When I submit the form, I get "Failed to load response data" from
Chrome.
When I remove the $this->validate call, I get "hello".
Why is this not working?

You need to return JSON and you can use the helper function:
response()->json([
'message' => 'hello'
]);
Then in your JS:
console.log(response.message);

OK apparently the validate method just redirects you back to the previous page if there are errors, unless the response is expected to be JSON. Ended up using the Validator facade instead.
Edit: Thanks for the downvotes. This website is cancer.

Related

unable to insert data in Angular to Laravel API

working with Angular fronted and Laravel back-end API with MySQL. anyway using Angular form trying to insert data to back-end.I have following codes in Angular,
employees.component.ts
// tslint:disable-next-line: typedef
insertData(){
this.dataService.insertData(this.employee).subscribe(res => {
console.log(res);
});
}
data.service.ts
// tslint:disable-next-line: typedef
insertData(data){
return this.httpClient.post('http://127.0.0.1.8000/api/addEmployees', data);
}
employees.components.html
<form (ngSubmit)="insertData()">
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" class="form-control" [(ngModel)]="employee.name">
</div>
<div class="form-group">
<label for="name">Email</label>
<input type="text" name="email" class="form-control" [(ngModel)]="employee.email">
</div>
<div class="form-group">
<label for="name">Salary</label>
<input type="text" name="salary" class="form-control" [(ngModel)]="employee.salary">
</div>
<button class="btn btn-dark btn-sm mt-4">Submit</button>
</form>
and laravel
api.php
Route::post('addEmployee','EmployeeController#addEmployee');
EmployeeController.php
public function addEmployee(Request $request){
$employee = Employee::create($request->all());
return response($employee, 201);
}
but when I go to insert data using form following errors are coming in the console -
zone-evergreen.js:2845 POST http://127.0.0.1.8000/api/addEmployees net::ERR_NAME_NOT_RESOLVED
ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://127.0.0.1.8000/api/addEmployees", ok: false, …}
how could I fix this problem here?

How do I set up a route for a form inside a landing page section in Laravel?

The website I'm working on is one continuous landing page with sections pulled in via blade pages and elements. How do I route a contact form in one of the landing page sections to a controller I've built?
I've built a controller that will send an email to my site administrator and also display a success notification to the user submitting the form. Right now, I've built the form on its own view ('example.com/contact'). Everything works appropriately when using the view. But I don't know how to get the landing page URL for the production contact form ('example.com/#contact') to route to the same (or any) controller.
#section('content')
#include('layouts.partials._header')
#include('pages.elements._about')
<div class="separator-line separator-primary"></div>
#include('pages.elements._calendar')
<div class="separator-line separator-primary"></div>
#include('pages.elements._contact') <!--form is pulled in here-->
#endsection
current web route that works with a separate view:
Route::get('/', function () {
return view('pages.landing');
});
Route::get('/contact', 'ContactController#show');
Route::post('/contact', 'ContactController#mailToAdmin');
Controller I'm trying to route the form to:
class ContactController extends Controller
{
public function mailToAdmin(ContactFormRequest $message, Admin $admin)
{
$admin->notify(new InboxMessage($message));
return redirect()->back()->with('message', 'Thanks for the message! We will get back to you soon!');
}
}
example of my form:
<div class="col-12 col-md-6">
<form class="form-horizontal" method="POST" action="/contact">
{{ csrf_field() }}
<div class="form-group">
<label for="Name">Name: </label>
<input type="text" class="form-control" id="name" placeholder="Your name" name="name" required>
</div>
<div class="form-group">
<label for="email">Email: </label>
<input type="text" class="form-control" id="email" placeholder="john#example.com" name="email" required>
</div>
<div class="form-group">
<label for="message">message: </label>
<textarea type="text" class="form-control luna-message" id="message" placeholder="Type your messages here" name="message" required></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary" value="Send">Send</button>
</div>
</form>
You need to add the route to the "action" attribute of the form tag.
Use:
<form action: "{{URL::to('/contact')}}" method:"POST">

Laravel: Says input required when it's there?

I'm trying to code a login system in Laravel and it keeps telling me the text box is required. I've added the textbox, rechecked the names are correct and I've made sure I enter text on submit of the form it belows to.
It keeps saying "The credentials.username field is required.", if I remove the required from the validation it will say it for password too.
HTML:
<form method="post">
<div id="login-columns">
<div id="login-column-1">
<label for="credentials-email">Username</label>
<input id="credentials-email" name="credentials.username" tabindex="2" type="text">
<input id="credentials-remember-me" name="_login_remember_me" tabindex="5" type="checkbox">
<label class="sub-label" for="credentials-remember-me">Keep me logged in</label>
</div>
<div id="login-column-2">
<label for="credentials-password">Password</label>
<input id="credentials-password" name="credentials.password" tabindex="3" type="password">
</div>
<input name="_token" type="hidden" value="{{ csrf_token() }}">
<div id="login-column-3">
<input style="margin: -10000px; position: absolute;" type="submit" value="Login"> <a class="button" href="#" id="credentials-submit" tabindex="4"><b></b><span>Login</span></a>
</div>
<div id="login-column-4">
888 Online
</div>
</div>
</form>
PHP:
public function onPost(Request $request)
{
$validator = Validator::make($request->all(), [
'credentials.username' => 'required|exists:users',
'credentials.password' => 'required'
]);
if ( $validator->fails()) {
return Redirect::back()->withErrors($validator->messages());
}
else {
if (!Auth::attempt(['username' => $request->input('credentials.username'), 'password' => $request->input('credentials-password')])) {
return Redirect::back()->withMessage('Failed Authentication')->withColor('danger');
}
else {
$user = Auth::user();
$user->save();
return Redirect::to('/home');
}
}
}
I believe the issue you are seeing is that Laravel treats 'credentials.username' as a "Nested Attribute". For instance if you are rendering a view 'layout.head' it will automatically look for the file head.blade.php inside the layout folder.
I think in this case it's assuming you are passing it an array like:
<input id="credentials-email" name="credentials[username]" tabindex="2" type="text">
<input id="credentials-password" name="credentials[password]" tabindex="3" type="password">
Have you tried:
<input id="credentials-email" name="credentials_username" tabindex="2" type="text">
<input id="credentials-password" name="credentials_password" tabindex="3" type="password">
There is a very brief mention of nested attributes on the Laravel validation documentation page: https://laravel.com/docs/5.4/validation
Don't use dot inside name input.
Replace credentials.username by credentials_username.
Or even better, just username.
In laravel validation dot(.) Represent array of items. In this case you need to modify your input field name like this <input name="credentials[username]"> <input name="credentials[password]">

form validation using ajax in codeigniter

In this when i submit my form it shows errors first then reload the page and go to index page.. but i want is show only error message not reload page after.. here my controller is
class User extends CI_Controller {
public function index()
{
$this->load->view('index');
}
public function error()
{
/* Load form helper */
$this->load->helper(array('form'));
/* Load form validation library */
$this->load->library('form_validation');
/* Set validation rule for name field in the form */
$form_data = array('brand_name' => $this->input->post('brand_name'), 'your_name ' => $this->input->post('your_name'), 'mobile_no' => $this->input->post('Mobile No.'));
if($this->form_validation->run($form_data) == FALSE )
{
echo validation_errors();
}
else
{
$this->load->view('submit');
}
}
}
and my view file named index.php is
<script type="text/javascript">
$(document).ready(function(){
$('#get').click(function(){
$.post("<? base_url() . 'user/error' ?>",
$("form").serialize(),
function(result) {
$("#error_message").html(result).appendTo("form");
},"html");
});
});
</script>
<form role="form" action="" class="form-inline" name="form" method="POST" id >
<div id="error_message" style="color:red"></div>
<?php echo form_open('form'); ?>
<div class="col-md-3">
</div>
<div class="col-md-2">
<div class="form-group">
<input type="text" class="form-control" placeholder="Brand Name" name="brand_name" onfocus="this.placeholder = ''" onblur="this.placeholder='Brand Name'">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<input type="text" class="form-control" placeholder="Your Name" name="your_name" onfocus="this.placeholder = ''" onblur="this.placeholder='Your Name'">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<input type="text" class="form-control" placeholder="Mobile No" name="mobile_no" onfocus="this.placeholder = ''" onblur="this.placeholder='Mobile No'">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<input type="submit" id="get" class="btn btn-success" name="submit" value="Proceed" ></input>
</div>
</div>
<div class="col-md-3">
</div>
</form>
i just want it shows error message only not reload page after please help... thanks in advance
You are trying to post form in AJAX so you will need to set the form data manually
Tested with CI 2
$form_data = array('brand_name' => $this->input->post('brand_name'), 'your_name ' => $this->input->post('your_name')); // other fields as required for validations
And validation for the same would be
if($this->form_validation->run($form_data) == TRUE ){
//validation passed
}else{
//validation fail
}
For CodeIgniter 3, as the Online documentation mentions try https://www.codeigniter.com/userguide3/libraries/form_validation.html#validating-an-array-other-than-post
Validating an Array (other than $_POST)
Sometimes you may want to validate an array that does not originate from $_POST data.
In this case, you can specify the array to be validated:
$data = array(
'username' => 'johndoe',
'password' => 'mypassword',
'passconf' => 'mypassword'
);
$this->form_validation->set_data($data);

Laravel 4 throwing MethodNotAllowedHttpException

I am making a simple registration form that then submits data to my database. However, the problem that I am running into is that the code that should submit the info to the database is not working.
Here's the form that I made using Twitter Bootstrap
<!DOCTYPE html>
<html>
<body>
<div class="modal-body">
<div class="well">
<div id="myTabContent" class="tab-content">
<div class="tab-pane active in" id="login">
<form method="POST" action='/adding_to_table' class="form-horizontal">
<fieldset>
<div id="legend">
<legend class="">Create Your Account</legend>
</div>
<div class="control-group">
<!-- Username -->
<label class="control-label" for="firstname">First Name</label>
<div class="controls">
<input type="text" id="first_name" name="firstname" placeholder="" class="input-xlarge">
</div>
</div>
<div class="control-group">
<!-- Username -->
<label class="control-label" for="lastname">Last Name</label>
<div class="controls">
<input type="text" id="last_name" name="lastname" placeholder="" class="input-xlarge">
</div>
</div>
<div class="control-group">
<!-- Username -->
<label class="control-label" for="email">E-mail</label>
<div class="controls">
<input type="text" id="e_mail" name="email" placeholder="" class="input-xlarge">
</div>
</div>
<div class="control-group">
<!-- Username -->
<label class="control-label" for="username">Username</label>
<div class="controls">
<input type="text" id="username" name="username" placeholder="" class="input-xlarge">
</div>
</div>
<div class="control-group">
<!-- Password-->
<label class="control-label" for="password">Password</label>
<div class="controls">
<input type="password" id="password" name="password" placeholder="" class="input-xlarge">
</div>
</div>
<div class="control-group">
<!-- Button -->
<div class="controls">
<button class="btn btn-primary">Submit</button>
</div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
</div>
<script class="cssdeck" src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script class="cssdeck" src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.1/js/bootstrap.min.js"></script>
</body>
<html>
This is the route that I am passing to the action field in my form:
Route::get('/adding_to_table', function()
{
return View::make('create');
});
And this is the create.php file that the route (above) is supposed to load which takes care of
the database submission
DB::table('user_info')->insert(
array("First_name" => Input::post('firstname'),
"Last_name" => Input::post("lastname"),
"E-mail" => Input::post("email"),
"Username" => Input::post("username"),
"Password" => Input::post("password"),
)
);
echo "Successfully entered user information into data table";
However, Laravel doesn't like this and is throwing this error at me:
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
Open: /Users/brendanbusey/Desktop/php_site/laravelSite/bootstrap/compiled.php
}))->bind($request);
} else {
$this->methodNotAllowed($others);
}
}
protected function methodNotAllowed(array $others)
{
throw new MethodNotAllowedHttpException($others);
}
protected function check(array $routes, $request, $includingMethod = true)
I have double and triple checked to make sure that I am using the names and not the id's from my html form when I'm sending the data via POST and all my names from the columns in my database match the ones in my code. Any help would be greatly appreciated!
You need to have two routes defined, one for GET and one for POST. If you want to use the same adding_to_table url, it should be something like
Route::get('/adding_to_table', function() {
// code to display your form initially
});
Route::post('/adding_to_table', function() {
// code to process the form submission
});
Maybe I'm not understanding you correctly, but it looks like you are using View::make() to try to run your db insert code. I believe View::make() is just intended to render blade templates, so I don't think this will work. Instead you could put that type of thing into a controller method, or even directly into the post route closure. To access the submitted values, you should use Input::get('firstname') etc. In the laravel docs here it explains that
You do not need to worry about the HTTP verb used for the request, as
input is accessed in the same way for all verbs.
You need to change the form opening line in your HTML to this:
<form method="POST" action='adding_to_table' class="form-horizontal">
In your routes.php file, you need to have this:
Route::get('adding_to_table', function()
{
return View::make('create');
});
Route::post('adding_to_table', function()
{
DB::table('user_info')->insert(
array("First_name" => Input::get('firstname'),
"Last_name" => Input::get("lastname"),
"E-mail" => Input::get("email"),
"Username" => Input::get("username"),
"Password" => Input::get("password"),
)
);
});
Change
Input::post() to Input::get()
to retrieve inputs.
Just add {{ csrf_field() }} below your form, like this:
<form method="POST" action='/adding_to_table' class="form-horizontal">
{{ csrf_field() }}
in Create.blade.php
{!! Form::open(array('route' => 'ControllerName.store','method' => 'POST','files' => true)) !!}
in Controller :-
public function store(Request $request)
{
$this->validate($request, [
'first_name' =>'required',
'last_name' => 'required',
'e_mail' =>'required',
'username' => 'required',
'password' =>'required',
]);
ModelName::create($request->all());
return route->(ControllerName.index);
NOTE : check model with all fields are fillable are not .

Categories