unable to insert data in Angular to Laravel API - php

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?

Related

CKEditor send Null Value to database via Ajax

I'm trying to create the Event's Calendar using PHP, Ajax and CKEditor 4. When I send the value to database via Ajax, it send the null value.
It send every values(title, start date, end date) except: c_details that I use CKEditor 4
Database's picture
My form's picture
Here's my form:
<div class="modal-body">
<form id="new_calendar">
<div class="form-group">
<label>Title</label>
<input type="text" class="form-control" name="title" placeholder="">
</div>
<div class="form-group">
<label>Description</label>
<textarea type="text" class="form-control" id="editor" name="c_details" placeholder=""></textarea>
</div>
<div class="form-group">
<label>Start Date</label>
<input type="text" class="form-control" name="start" placeholder="YYYY-mm-dd">
</div>
<div class="form-group">
<label>End Date</label>
<input type="text" class="form-control" name="end" placeholder="YYYY-mm-dd">
</div>
<input type="hidden" name="new_calendar_form">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" onclick="return new_calendar();">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
Here's Ajax:
function new_calendar() {
for (instance in CKEDITOR.instances) {CKEDITOR.instances[instance].updateElement()}
$.ajax({
type: "POST",
url: "json-event.php",
data: $("#new_calendar").serialize(),
success: function (data) {
$(".close").trigger('click');
alert(data);
location.reload();
}
});
return false;}
Here's all my code on Code Sandbox, I just changed the name='description' to name='c_details'
: https://codesandbox.io/s/blissful-water-nop1y?file=/index.php
Save new data:
public function new_calendar($data)
{
$db = $this->connect();
$add_user = $db->prepare("INSERT INTO calendar (id,title,c_details,start,end) VALUES(NULL,?,?,?,?) ");
$add_user->bind_param("ssss", $data['title'], $data['c_details'], $data['start'], $data['end']);
if (!$add_user->execute()) {
echo $db->error;
} else {
echo "Saved !";
}
}
before send data to ajax request put this:
for (instance in CKEDITOR.instances) {CKEDITOR.instances[instance].updateElement()}
This will update the element textarea with information of ckeditor

post Laravel and VUEJS

i´m traying initiate with vueJS and i´m doing a aplication that update a register of my DB but always returned a 405 error in my web browser console. I´m trying send my token in request axios, and i think that is my problem, because with ajax always have to send token in the header petition. this is my actual code vueJS, HTML and route Laravel.
thanks
VUEJS
require('./bootstrap');
window.Vue = require('vue');
Vue.component('usuarios-component', require('./components/usuariosComponent.vue').default);
// inicio de VUE
const app = new Vue({
el: '#contenedorVue',
data:{
id: '',
nombreUsuario: '',
email: '',
password: '',
direccion: '',
token: '',
arrayTasks:[],
},
methods: {
enviar(){
let url = '/actualizarDatos';
axios.post(url, {
id: this.id,
nombreUsuario: this.nombreUsuario,
email: this.email,
password: this.password,
direccion: this.direccion,
token: this.token,
}).then(function(response){
this.arrayTasks = response.data;
}).catch(function(error){
console.log(error);
})
}
}
});
HTML
#extends('layouts.app')
#section('content')
#include('layouts.sidebar')
<!-- SE ESTABLECE V-MODEL para usarlo con vue, es como el ID -->
<div id="contenedorVue">
<div class="d-flex flex-row justify-content-center">
<form method="post">
<input type="hidden" v-model="token" value="{{csrf_token()}}">
<div class="form-row">
<div class="col">
<label for="email">Nombre</label>
<input type="text" class="form-control" v-model="nombreUsuario" value="{{$usuario->nombre}}">
</div>
<div class="col">
<label for="email">Email</label>
<input type="email" class="form-control" v-model="email" aria-describedby="emailHelp" value="{{$usuario->email}}">
</div>
</div>
<div class="form-row">
<div class="col">
<label for="password">Contraseña</label>
<input type="password" class="form-control" v-model="password" value="{{$usuario->password}}">
</div>
</div>
<div class="form-row">
<div class="col">
<label for="direccion">Direccion</label>
<textarea v-model="direccion" class="md-textarea form-control" rows="3">
{{$usuario->direccion}}
</textarea>
<input type="hidden" value="{{$usuario->id}}" v-model="id">
</div>
</div>
<!-- EMPEZAMOS LA FUNCIONALIDAD CON VUE DE ESTA MANERA LE DAMOS FUNCIONALIDAD AL BOTON-->
<button class="btn btn-primary mt-5" #click="enviar">Actualizar</button>
</form>
</div>
</div>
#endsection
CONSOLE ERROR
1:1 POST http://www.bonos.local/datosPersonales/1 405 (Method Not Allowed)
error post laravel
Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The POST method is not supported for this route. Supported methods: GET, HEAD.
ROUTES
Route::get('/datosPersonales/{id}', 'HomeController#datosPersonales')->name('datosPersonales');
Route::post('/actualizarDatos', 'UsuariosController#actualizarDatosPersonales')->name('actualizarDatosPersonales');
image
image 2
you need to prevent default submit form
<form method="post">
to
<form #submit.prevent="enviar">
<button class="btn btn-primary mt-5" type="submit">Actualizar</button>
</form>
here button need to have type="submit" so once you click that button it will submit form
here post and get will handel in enviar() function
ref link https://v2.vuejs.org/v2/guide/events.html#Event-Modifiers
it´s essential to do
npm run watch
or
npm run dev
for all changes be appliead... sorry for my numb

Post edit form data and get it in controller using angularjs

I want to post edit form data to codeigniter controller using angularjs
this is my angularjs controller where i collect and post form data
$scope.editlist = function(id){
$http({
method:'post',
url:'http://localhost/Angular_demo/admin/index.php/welcome/get_edit_data/'+
id
}).then(function success(response){
$scope.sid = parseInt(response.data[0]['id']);
$scope.firstname = response.data[0]["first_name"];
$scope.lastname = response.data[0]['last_name'];
$scope.email = response.data[0]['email'];
});
}
$scope.saveEdit = function(id,firstname,lastname,email){
$http({
method:'post',
data:'id='+ id + '&first_name='+firstname+
'&last_name='+lastname+'&email='+email,
url:'http://localhost/Angular_demo/admin/index.php/welcome/update_data'
}).then(function success(response){
console.log(response.data);
});
}
My view where i bind and post form data
<form name="editItem" class="form-horizontal">
<input ng-model="sid" type="hidden" placeholder="Name" name="name"
class="form-control" />
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">First
Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" ng-model="firstname"
id="inputEmail3" placeholder="First name">
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Last
Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" ng-model="lastname"
id="inputEmail3" placeholder="Last Name">
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-
label">Email</label>
<div class="col-sm-10">
<input type="text" class="form-control" ng-model="email"
id="inputEmail3" placeholder="Email">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="button" class="btn btn-default" data-
dismiss="modal">Close</button>
<button type="submit" ng-disabled="editdata.$invalid"
class="btn btn-primary create-crud" data-dismiss="modal" ng-
click="saveEdit(sid,firstname,lastname,email)">Submit</button>
</div>
</div>
</form>
This is my codeigniter controller where i want to get form data
public function update_data(){
$requests = json_decode(file_get_contents('php://input'), TRUE);
$ids= array('id' =>$requests['id']);
echo json_encode($ids);
}
When i submit my form data will show null in my controller,so please help how to get form data in controller.
$scope.saveEdit = function(id,firstname,lastname,email){
$http({
method:'post',
data:'id='+ id + '&first_name='+firstname+
'&last_name='+lastname+'&email='+email,
url:'http://localhost/Angular_demo/admin/index.php/welcome/update_data'
}).then(function success(response){
console.log(response.data);
});
}
This should be like this:-
$scope.saveEdit = function(id,firstname,lastname,email){
$http({
method:'post',
data:{"id": id,"first_name":firstname,
"last_name":lastname,"email":email}
url:'http://localhost/Angular_demo/admin/index.php/welcome/update_data'
}).then(function success(response){
console.log(response.data);
});
}
Since the codeigniter code uses json_decode, the $http service should use a JavaScript object to post the data:
$scope.saveEdit = function(id,firstname,lastname,email) {
var url = 'http://localhost/Angular_demo/admin/index.php/welcome/update_data';
var data = {
id: id,
first_name: firstname,
last_name: lastname,
email: email,
};
$http.post(url, data
).then(function success(response){
console.log(response.data);
});
}
The AngularJS framework will automatically encode the JavaScript object as a JSON string.

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

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.

Data from JSON response not displaying after assigning to instance variable

So, I have my SPA at about 98% functional. The app pulls data from a MySQL database and allows the user to edit/delete records. For the page in question, it will edit/delete data of the specified student ID but it will not properly display the data in the text fields.
If you do not input a value it will display the first item in the JSON array but not the one you specify in the search field.
I did not do a very good job at explaining that but here is the HTML page that uses a function to pass data to the controller which then selects the corresponding student by ID and assigns it to the variable $scope.student. I then try to display the student data on the HTML page by using student.first_name (or any property) but it does not work correctly.
<h3>Edit/Delete Student with ID: {{student.student_id}}</h3>
<div class="form-group">
<label for="sid">Student ID:</label>
<input type="text" class="form-control" id="sid" ng-model="sid">
</div>
<p><button type="button" class="btn btn-primary" ng-click="getRecord(sid)">
Get Student Info </button> </p>
<div class='row'>
<div class="col-md-6">
<div class="form-group">
<label for="first_name">First Name:</label>
<input type="text" class="form-control" id="first_name" ng-model="student.first_name">
</div>
<div class="form-group">
<label for="last_name">Last Name:</label>
<input type="text" class="form-control" id="last_name" ng-model="student.last_name">
</div>
<div class="form-group">
<label for="hrs_completed">Hrs Completed:</label>
<input type="text" class="form-control" id="hrs_completed" ng-model= "student.hrs_completed">
</div>
<div class="form-group">
<label for="hrs_attempted">Hrs Attempted:</label>
<input type="text" class="form-control" id="hrs_attempted" ng-model= "student.hrs_attempted">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="gpa_points">GPA Points:</label>
<input type="text" class="form-control" id="gpa_points" ng-model= "student.gpa_points">
</div>
<div class="form-group">
<label for="major">Major:</label>
<input type="text" class="form-control" id="major" ng-model="student.major">
</div>
<div class="form-group">
<label for="advisor_id">Advisor ID:</label>
<input type="text" class="form-control" id="advisor_id" ng-model="student.advisor_id">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="text" class="form-control" id="email" ng-model="student.email">
</div>
</div>
<button type="button" class="btn btn-primary" ng-click="updateRecord()">Update</button>
<button type="button" class="btn btn-primary" ng-click="deleteRecord()">Delete</button>
And here is my controller on my Javascript page:
app.controller('editCtrl', function($scope, $http) {
$http.get("getStudentData.php")
.then(function (response) {
$scope.students = response.data;
});
$scope.getRecord = function(sid) {
id = sid;
$scope.student = $scope.students.find(s=>s.id == sid);
};
Do I need to make a seperate GET request to the server for this to work properly or do I just need to reference the student object differently?
I think there is mismatch in what you are getting as response.data and what you are trying to .find() and then what you are binding on html.
Check this plunkr.
You are trying to render by searching id property.
$scope.students.find(s=>s.id == sid);
where as you are rendering on UI using student_id property.
{{student.student_id}}
So, surely there is mismatch in what you are getting as response.data and what you are rendering using $scope.student properties. I think my plunkr will show that your function is correct.
In case this answer doesn't work, share your response.data.

Categories