Update DB::table from passed object of array in laravel - php

In laravel, I'm trying to update several tables and rows. i have items that are to be received and checked by 2 different users.
in my show.blade.php, i have this verify button and submit button depending on the user.
#if (($current_user_id != $saved_receiver_id) && ($saved_receiver_id != $not_yet_received))
<div class="row padder m-b">
<div class="col-md-12">
<label for="received_by" class="pull-left" >Received by:</label> <span class="fa"></span>
<input type="hidden" name="receiver_id" value="{{ $saved_receiver_id }}" >{{ $receiver_username }}</input>
</div>
</div>
<div class="row padder m-b">
<div class="col-md-12">
<label for="received_date" class="pull-left" >Received date:</label> <span class="fa"></span>
<input type="hidden" name="received_date" value="{{ $received_date }}" >{{ $received_date }}</input>
</div>
</div>
<input type="hidden" name="purchase_orders_id" value="{{ $purchase_order_number }}">
<input type="hidden" name="checker_id" value="{{ $current_user_id }}">
<div class="row padder m-b">
<div class="col-md-12">
<label for="final_checker_remarks" class="pull-left" >Final Remarks</label>
<textarea class="form-control col-md-12" name="final_checker_remarks" value="{{ $final_checker_remarks }}" id="final_checker_remarks">{{ $final_checker_remarks }}</textarea>
</div>
</div>
<br />
<div class="row">
<div class="col-md-12">
<button type="button" class="pull-right btn btn-success btn-sm submit-btn" id="update-form-submit" data-action="verified">Verified</button>
</div>
</div>
#else
<div class="pull-right">
<div class="btn-group">
<button type="button" class="btn btn-info btn-sm submit-btn" id="update-form-submit" data-action="submit">Submit List</button>
</a>
</div>
#endif
now in my ReceivesController.php, i have this postUpdate function,
public function postUpdate(Request $request)
{
if (! $request->ajax()) {
abort(404);
}
$items = json_decode($request->items);
$action = json_decode($request->action);
if(!count($items) && !count($items->purchase_item_id)){
return false;
}
$cnt = count($items->purchase_item_id);
// Receiver Submit function
if ($action == "submit") {
// Saves the received id of the one who received to purchase order table
DB::table('purchase_orders')
->where('id', $items->purchase_orders_id)
->update([
'receiver_id' => $items->receiver_id,
]);
// Saves the quantity received and receiver remarks to purchase items table
for($i=0; $i<$cnt; $i++){
DB::table('purchase_items')
->where('id', $items->purchase_item_id[$i])
->update([
'quantity_received' => $items->quantity_received[$i],
'receiver_remarks' => $items->receiver_remarks[$i],
]);
}
// Items Received Success Message
$message = 'Items Received';
}
// QA or Checker Finalize function
else {
// Saves the checker id, and final checker remarks of the one who made the QA to purchase order table
DB::table('purchase_orders')
->where('id', $items->purchase_orders_id)
->update([
'checker_id' => $items->checker_id,
'final_checker_remarks' => $items->final_checker_remarks,
]);
// Saves the quality received and checker remarks to purchase items table
for($i=0; $i<$cnt; $i++){
$quality_received = $items->quality_received;
if(is_array($items->quality_received)){
$quality_received = $items->quality_received[$i];
}
$checker_remarks = $items->checker_remarks;
if(is_array($items->checker_remarks)){
$checker_remarks = $items->checker_remarks[$i];
}
$quantity_received = $items->quantity_received;
if(is_array($items->quantity_received)){
$quantity_received = $items->quantity_received[$i];
}
$receiver_remarks = $items->receiver_remarks;
if(is_array($items->receiver_remarks)){
$receiver_remarks = $items->receiver_remarks[$i];
}
DB::table('purchase_items')
->where('id', $items->purchase_item_id[$i])
->update([
'quality_received' => $quality_received,
'checker_remarks' => $checker_remarks,
'quantity_received' => $quantity_received,
'receiver_remarks' => $receiver_remarks,
]);
// Increments or Adds the quantity received to items table
DB::table('items')
->where('purchase_items.id', $items->purchase_item_id[$i])
->join('purchase_items', 'items.id', '=', 'purchase_items.item_id')
->increment('items.measurement', $items->quantity_received[$i]);
}
/ / Items Finalized Success Message
$message = 'Items Verified';
}
// Returns Success Message
return response()->json([
'success' => true,
'message' => $message
]);
}
Now my problem is only the first letter of the word that is typed in the input area are being saved, and in others they are not saved, however, in other, it can be saved. I know its weird, but i cant find which part of my codes is doing such result, what is it that i need to do for me to update my tables correctly? Thanks in advance for the help.
Update: Here is my receive-form-function.js
/* ========================================================================
* Initialize Pages
* ======================================================================== */
$(initialPages);
/* ========================================================================
* Major function
* ======================================================================== */
/* ==== function to init this page === */
function initialPages($) {
// if($('#receives-list-table').length){
// DataTables("#receives-list-table", "receives");
// }
if($('#receiveItems-list-table').length){
$("#receiveItems-list-table").DataTable({
responsive: true,
ordering: false,
});
}
$('#update-form-submit').on('click', function(){
var action = $(this).data('action');
updateReceiveItem(action);
});
clearInputs();
}
/* === dataTables === */
function DataTables(selector, controller) {
$(selector).DataTable({
responsive: true,
processing: true,
serverSide: true,
ajax: url+'/'+controller+'/paginate'
});
}
function updateReceiveItem(action){
loadingModal('show','Updating ....');
ajaxCsrfToken();
var data = $('#receiveItems_id').serializeArray();
data = JSON.stringify(data);
// data = JSON.parse(data);
data = JSON.stringify($('#receiveItems_id').serializeObject());
// data = $('#receiveItems_id').serializeObject();
$.ajax({
url: url+'/receives/update',
type: 'post',
data: {'items':data, 'action': action},
dataType: 'json',
complete: function() {
loadingModal('close');
},
error: function(result) {
},
success: function(result) {
successAlert('#receiveItems-result', result.message);
// if (result.success) {
// $('input, select, textarea').attr('disabled', true);
// } else {
// alert(result.message);
// }
}
});
console.log(data);
return false;
}
/**
* Use to format serialize data and convert to json data
*
* Usage: JSON.stringify($('form').serializeObject())
*/
$.fn.serializeObject = function() {
var o = Object.create(null),
elementMapper = function(element) {
element.name = $.camelCase(element.name);
return element;
},
appendToResult = function(i, element) {
var node = o[element.name];
if ('undefined' != typeof node && node !== null) {
o[element.name] = node.push ? node.push(element.value) : [node, element.value];
} else {
o[element.name] = element.value;
}
};
$.each($.map(this.serializeArray(), elementMapper), appendToResult);
console.log(o);
return o;
};

my $.fn.serializeObject = function() above seems to have the bug, i tried using another $.fn.serializeObject = function(), and it gave me the json object that i want. here is the $.fn.serializeObject = function() that i am using now.
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};

Related

Ajax retrieving errors not working Laravel

I'm trying to retrieve errors when a user fills a form submitted using ajax. I'm following this tutorial. I'm not getting the result expected despite the logic I think should be right.
Here is my blade view code :
#extends('layouts.layout')
#section('title','Soumettre thématique')
#section('content')
<body>
<div class="container_fluid">
<div class="row">
<div class="alert alert-danger print-error-msg" style="display: none;">
#if($errors->any())
<ol style="color: red">
#foreach($errors->all() as $error)
<li>
{{$error}}
</li>
#endforeach
</ol>
#endif
</div>
</div>
</div>
<form method="POST" action=" {{route('themes.store')}} ">
#csrf
<!-- Intitulé du thème -->
<input type="text" name="intitule" id="intitule" placeholder="Intitulé du thème" required><br>
<!-- Catégorie -->
<select name="categorie" required>
<option value="">-- Catégorie --</option>
<option value="web">Développement web</option>
<option value="appMobile">Programmation application mobile</option>
<option value="secure">Sécurisation</option>
<option value="other">Autre</option>
</select> <br>
<!-- Filière désirée -->
<input type="checkbox" name="filiere[]" id="GL" value="GL" required>
<label for="GL">Génie Logiciel</label><br>
<input type="checkbox" name="filiere[]" id="SI" value="SI" required>
<label for="SI">Sécurité Informatique</label><br>
<input type="checkbox" name="filiere[]" id="IM" value="IM" required>
<label for="IM">Internet et Multimédia</label><br>
<input type="checkbox" name="filiere[]" id="SIRI" value="SIRI" required>
<label for="SIRI">Systèmes d'Information et Réseaux Informatiques</label><br>
<!-- Descriptif -->
<textarea name="description" id="description" placeholder="Description de la thématique" required>{{old('description')}} </textarea><br>
<input type="submit" name="submit" id="submit" value="Ajouter">
<span id="error-message" class="text-danger"></span>
<span id="success-message" class="text-success"></span>
</form>
<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
<script type="text/javascript">
$(function (){
var itsChecked = null;
$('input[type=checkbox]').on('click', function(){
if($('input[type=checkbox]:checked').length > 0){ //S'il y a au moins 1 ([...].length > 0) ckecked
// alert('At least one is checked');
$('#GL').removeAttr("required");
$('#SI').removeAttr("required");
$('#IM').removeAttr("required");
$('#SIRI').removeAttr("required");
}
else if(!$('input[type=checkbox]:checked').length > 0){ //S'il n'y a aucun checked (!(at least 1)>0)
// alert('None is checked');
$('#GL').attr('required','');
$('#SI').attr('required','');
$('#IM').attr('required','');
$('#SIRI').attr('required','');
}
});
$('#submit').on('click',function(e){
e.preventDefault();
var _token = $("input[name='_token']").val();
var intitule = $("input[name='intitule']").val();
var categorie = $("select[name='categorie']").val();
var filiereChecked = [];
$.each($("input[type='checkbox']:checked"), function(){
filiereChecked.push($(this).val());
});
var filiere = filiereChecked.join(", ");
var filiere = filiere.toString();
$.ajax({
url: "{{route('themes.store')}}",
type: 'POST',
data: {
_token:_token,
intitule:intitule,
categorie:categorie,
filiere:filiere
},
success: function(data){
if($.isEmptyObject(data.error)){
alert(data.success);
}
else{
// console.log(data.error);
printErrorMsg(data.error);
}
}
});
});
function printErrorMsg (msg) {
$(".print-error-msg").find("ul").html('');
$(".print-error-msg").css('display','block');
$.each( msg, function( key, value ) {
$(".print-error-msg").find("ul").append('<li>'+value+'</li>');
});
}
});
</script>
</body>
#endsection
The controller store function :
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$validator = Validator::make($request->all(),[
'intitule' => 'unique:themes,intitule'
]);
$theme = new Theme;
$theme->intitule = $request->input('intitule');
$theme->description = $request->input('description');
$theme->categorie = $request->input('categorie');
$request->merge([
'filiere' => implode(',', (array) $request->get('filiere'))
]);
$theme->filiereDesiree = $request->input('filiere');
$theme->save();
if ($validator->passes()) {
return response()->json(['success'=>'Added new records.']);
}
return response()->json(['error'=>$validator->errors()->all()]);
}
The problem is I'm not getting a message at all, either success or error may it be. I don't know where I'm doing wrong there.
P.S:
I've already used Ajax to submit this form. I did it using XMLHttpRequest object. The problem was I do not know how to use the 422 status to return errors using this XHR object. I've looked for it but found nothing really helpful.. So I changed this method to use here the ajax() jquery function which seems to be more used. Still not getting the messages.. It's the first time I try to manage the validation errors using Ajax. Your help would be very welcome
You can use this on your controller.
return response()->json(array('errors'=>$validator->getMessageBag()->toArray(),));
and in javascript try to use this one
success: function(data){
if(data.error){
printErrorMsg(data.error);
}
else{
alert(data.success);
}
}
ajax code
$.ajax({
url: "{{route('themes.store')}}",
type: 'POST',
data: {
_token:_token,
intitule:intitule,
categorie:categorie,
filiere:filiere
},
success: function(data){
if(data.error){
printErrorMsg(data.error);
}
else{
alert(data.success);
}
}
});
Controller
public function store(Request $request)
{
$validator = \Validator::make($request->all(),[
'intitule' => 'unique:themes,intitule'
]);
if ($validator->fails()) {
return response()->json(array('error'=>$validator->getMessageBag()->toArray(),));
}
$theme = new Theme;
$theme->intitule = $request->input('intitule');
$theme->description = $request->input('description');
$theme->categorie = $request->input('categorie');
$request->merge([
'filiere' => implode(',', (array) $request->get('filiere'))
]);
$theme->filiereDesiree = $request->input('filiere');
$theme->save();
return response()->json(array('success'=>'Added new records.',));
}
Oops this is my fault... I've just figured why it was not working. I've placed this in my blade view
#if($errors->any())
<ol style="color: red">
#foreach($errors->all() as $error)
<li>
{{$error}}
</li>
#endforeach
</ol>
#endif
instead of the <ul> </ul> tags that the javascript code is looking for to output the errors. Thank you all
You can use Laravel Request for your validation.
php artisan make:request ThemeCreateRequest
Controller
use App\Http\Request\ThemeCreateRequest
public function store(ThemeCreateRequest $request)
{
$theme = new Theme;
$theme->intitule = $request->input('intitule');
$theme->description = $request->input('description');
$theme->categorie = $request->input('categorie');
$request->merge([
'filiere' => implode(',', (array) $request->get('filiere'))
]);
$theme->filiereDesiree = $request->input('filiere');
$theme->save();
if ($validator->passes()) {
return response()->json(['success'=>'Added new records.']);
}
return response()->json(['error'=>$validator->errors()->all()]);
}
App\Http\Request\ThemeCreateRequest.php
public function authorize()
{
return true;
}
public function rules()
{
return [
'intitule' => 'required|unique',
];
}

Laravel update mysql table return empty data

I am developing an application where i display/edit/delete data from Mysql table using laravel and datatables. I get this error when trying to add or edit data and update it in Mysql table:
Here is code:
<!DOCTYPE html>
<html>
<head>
<title>Datatables Server Side Processing in Laravel</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<br />
<h3 align="center">Datatables Server Side Processing in Laravel</h3>
<br />
<div align="right">
<button type="button" name="add" id="add_data" class="btn btn-success btn-sm">Add</button>
</div>
<br />
<table id="student_table" class="table table-bordered" style="width:100%">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Action</th>
<th><button type="button" name="bulk_delete" id="bulk_delete" class="btn btn-danger btn-xs"><i class="glyphicon glyphicon-remove"></i></button></th>
</tr>
</thead>
</table>
</div>
<div id="studentModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<form method="post" id="student_form">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Data</h4>
</div>
<div class="modal-body">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<span id="form_output"></span>
<div class="form-group">
<label>Enter First Name</label>
<input type="text" name="first_name" id="first_name" class="form-control" />
</div>
<div class="form-group">
<label>Enter Last Name</label>
<input type="text" name="last_name" id="last_name" class="form-control" />
</div>
</div>
<div class="modal-footer">
<input type="hidden" name="student_id" id="student_id" value="" />
<input type="hidden" name="button_action" id="button_action" value="insert" />
<input type="submit" name="submit" id="action" value="Add" class="btn btn-info" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#student_table').DataTable({
"processing": true,
"serverSide": true,
"ajax": "{{ route('ajaxdata.getdata') }}",
"columns":[
{ "data": "first_name" },
{ "data": "last_name" },
{ "data": "action", orderable:false, searchable: false},
{ "data":"checkbox", orderable:false, searchable:false}
]
});
$('#add_data').click(function(){
$('#studentModal').modal('show');
$('#student_form')[0].reset();
$('#form_output').html('');
$('#button_action').val('insert');
$('#action').val('Add');
$('.modal-title').text('Add Data');
});
$('#student_form').on('submit', function(event){
event.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url:"{{ route('ajaxdata.postdata') }}",
method:"POST",
data:form_data,
dataType:"json",
success:function(data)
{
if(data.error.length > 0)
{
var error_html = '';
for(var count = 0; count < data.error.length; count++)
{
error_html += '<div class="alert alert-danger">'+data.error[count]+'</div>';
}
$('#form_output').html(error_html);
}
else
{
$('#form_output').html(data.success);
$('#student_form')[0].reset();
$('#action').val('Add');
$('.modal-title').text('Add Data');
$('#button_action').val('insert');
$('#student_table').DataTable().ajax.reload();
}
}
})
});
$(document).on('click', '.edit', function(){
var id = $(this).attr("id");
$('#form_output').html('');
$.ajax({
url:"{{route('ajaxdata.fetchdata')}}",
method:'get',
data:{id:id},
dataType:'json',
success:function(data)
{
$('#first_name').val(data.first_name);
$('#last_name').val(data.last_name);
$('#student_id').val(id);
$('#studentModal').modal('show');
$('#action').val('Edit');
$('.modal-title').text('Edit Data');
$('#button_action').val('update');
}
})
});
$(document).on('click', '.delete', function(){
var id = $(this).attr('id');
if(confirm("Are you sure you want to Delete this data?"))
{
$.ajax({
url:"{{route('ajaxdata.removedata')}}",
mehtod:"get",
data:{id:id},
success:function(data)
{
alert(data);
$('#student_table').DataTable().ajax.reload();
}
})
}
else
{
return false;
}
});
$(document).on('click', '#bulk_delete', function(){
var id = [];
if(confirm("Are you sure you want to Delete this data?"))
{
$('.student_checkbox:checked').each(function(){
id.push($(this).val());
});
if(id.length > 0)
{
$.ajax({
url:"{{ route('ajaxdata.massremove')}}",
method:"get",
data:{id:id},
success:function(data)
{
alert(data);
$('#student_table').DataTable().ajax.reload();
}
});
}
else
{
alert("Please select atleast one checkbox");
}
}
});
});
</script>
</body>
</html>
Controller:
<?php
namespace App\Http\Controllers;
use Validator;
use Illuminate\Http\Request;
use App\Student;
use Yajra\DataTables\DataTables;
class AjaxdataController extends Controller
{
function index()
{
return view('student.ajaxdata');
//http://127.0.0:8000/ajaxdata
}
function getdata()
{
$students = Student::select('id', 'first_name', 'last_name');
return DataTables::of($students)
->addColumn('action', function($student){
return '<i class="glyphicon glyphicon-edit"></i> Edit<i class="glyphicon glyphicon-remove"></i> Delete';
})
->addColumn('checkbox', '<input type="checkbox" name="student_checkbox[]" class="student_checkbox" value="{{$id}}" />')
->rawColumns(['checkbox','action'])
->make(true);
}
function postdata(Request $request)
{
$validation = Validator::make($request->all(), [
'first_name' => 'required',
'last_name' => 'required',
]);
$error_array = array();
$success_output = '';
if ($validation->fails())
{
foreach($validation->messages()->getMessages() as $field_name => $messages)
{
$error_array[] = $messages;
}
}
else
{
if($request->get('button_action') == "insert")
{
$student = new Student([
'first_name' => $request->get('first_name'),
'last_name' => $request->get('last_name')
]);
$student->save();
$success_output = '<div class="alert alert-success">Data Inserted</div>';
}
if($request->get('button_action') == 'update')
{
$student = Student::find($request->get('student_id'));
$student->first_name = $request->get('first_name');
$student->last_name = $request->get('last_name');
$student->save();
$success_output = '<div class="alert alert-success">Data Updated</div>';
}
}
$output = array(
'error' => $error_array,
'success' => $success_output
);
echo json_encode($output);
}
function fetchdata(Request $request)
{
$id = $request->input('id');
$student = Student::find($id);
$output = array(
'first_name' => $student->first_name,
'last_name' => $student->last_name
);
echo json_encode($output);
}
function removedata(Request $request)
{
$student = Student::find($request->input('id'));
if($student->delete())
{
echo 'Data Deleted';
}
}
function massremove(Request $request)
{
$student_id_array = $request->input('id');
$student = Student::whereIn('id', $student_id_array);
if($student->delete())
{
echo 'Data Deleted';
}
}
}
web.php:
Route::get('ajaxdata', 'AjaxdataController#index')->name('ajaxdata');
Route::get('ajaxdata/getdata', 'AjaxdataController#getdata')->name('ajaxdata.getdata');
Route::post('ajaxdata/postdata', 'AjaxdataController#postdata')->name('ajaxdata.postdata');
Route::get('ajaxdata/fetchdata', 'AjaxdataController#fetchdata')->name('ajaxdata.fetchdata');
Route::get('ajaxdata/removedata', 'AjaxdataController#removedata')->name('ajaxdata.removedata');
Route::get('ajaxdata/massremove', 'AjaxdataController#massremove')->name('ajaxdata.massremove');
Only delete is working. Also i want to use select-checkbox attribute of datatable but it doesn't work, like this one link for the line color on selection but with multiple selections.
Thanks to #Alaksandar Jesus Gene i solved this issue by changing the post request by a get request for the postdata function inside web.php file and inside the view related script code. Now that it works my second concern still unresolved.
Can u try this
$(document).on('click', '.edit', function () {
data = {};
data.id = $(this).attr("id");
data.first_name = "User"; //$('#first_name').val();
data.last_name = "hello"; //$('#last_name').val();
data.student_id = $(this).attr("id");
data.action = 'Edit';
data.button_action = 'update';
$('#form_output').html('');
$.ajax({
url: "{{route('ajaxdata.fetchdata')}}",
method: 'post',
data: data,
dataType: 'json',
success: function (data) {
// $('#studentModal').modal('show');
// $('.modal-title').text('Edit Data');
console.log("data", data);
},
error: function(err){
console.log("err", err);
}
})
});
Route::post('ajaxdata/postdata', 'AjaxdataController#postdata')->name('ajaxdata.postdata');
The router expects post request but you are sending GET request. Please change the method as shown

Laravel + Vue unable to save data to my database

I'm trying to save data from my vue component to database but it will just say 500 (internal server error ) on my dev tools.
I tried one by one deleting my code to see where it fails everything will work fine until the I added the save(); function to my database
Vue Component
<template>
<form #submit.prevent="submit">
<div class="form-group">
<input type="text" class="form-control" name="name" id="name" v-model="fields.name" />
<div v-if="errors && errors.name" class="text-danger">{{ errors.name[0] }}</div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="post" id="post" v-model="fields.post" />
<div v-if="errors && errors.post" class="text-danger">{{ errors.post[0] }}</div>
</div>
<button type="submit" class="btn btn-primary">Send message</button>
<div v-if="success" class="alert alert-success mt-3">
Message sent!
</div>
</form>
Vue COmponent Script
<script>
export default {
data() {
return {
fields: {},
errors: {},
success: false,
loaded: true,
}
},
methods: {
submit() {
if (this.loaded) {
this.loaded = false;
this.success = false;
this.errors = {};
axios.post('/adminquickannc', this.fields).then(response => {
this.fields = {}; //Clear input fields.
this.loaded = true;
this.success = true;
}).catch(error => {
this.loaded = true;
if (error.response.status === 422) {
this.errors = error.response.data.errors || {};
}
});
}
},
},
}
</script>
Controller // My controller code to save it on the database
use App\Post;
use Illuminate\Http\Request;
public function store(Request $request)
{
// Validation
$this->validate($request, [
'name' => 'required',
'post' => 'required|max:500|min:10'
]);
// Variables we needed
$name = $request->input('name');
$post = $request->input('post');
// Saving the post to database
$post = new Post();
$post->name = $name;
$post->post = $post;
$post->save();
}
I expect this code to save data to my database, is this way of saving it safe? and can you guys give me tools where errors like this can be more specific so i can understand where it fails Thank you in advance guys!

How to use returned json response in view - laravel 5.2

I am using Laravel 5.2 + angularjs.
GOAL : Have to submit a form which have only check boxes. Based on the check box selected check box id fetch the data and return to the view. This returned data will be displayed in other div of same page.
For Example : Form is in div1 and returned data should be displayed in div2, div3 and div4. Only one division will be displayed on the view rest are hidden.
FINALLY - I am able to hide and display divisions using angular and I am able to submit the form which is in div1 using ajax. But I am unable to get the data back to the view from controller (data is returned in json format) and display on other divisions.
How can I display the returned response json object on the view ?
Below is my code :
Route :
Route::group(['middleware' => ['web']], function () {
Route::get('/form', 'PublicController#index'); // View will be displayed by using this method
Route::post('/form','PublicController#show'); // Form is submitted and data is returned using this "show" method
});
Controller :
class PublicController extends Controller
{
public function index(){
$crimetypes = crimetype::get();
$step1='';$step2='';$step3='';$step4='';$step5='';
return view('frontend.form')->withCrimetypes($crimetypes)->withStep1($step1)->withStep2($step2)->withStep3($step3)->withStep4($step4)->withStep5($step5);
}
public function show(Request $request, QuestionsRepository $questionsRepository){
$data = $questionsRepository->returnSteps($request);
$step1 = $data[0];
$step2 = $data[1];
$step3 = $data[2];
$step4 = $data[3];
$step5 = $data[4];
// Data is successfully coming till here...
return response()->json(['step1'=>$step1, 'step2'=>$step2, 'step3'=>$step3, 'step4'=>$step4, 'step5'=>$step5],200);
// Here it is not allowing to use any other return type other than response json..
}
}
View :
<div ng-show="div1">
<div>
{!! Form::open(array('method'=>'POST','url'=>'/form','id'=>'formid'))!!}
<div class="col-md-12 row">
<h2>Step - 1</h2>
<hr>
<br><p>Please select the relevant check boxes below.</p>
</div>
#foreach($crimetypes as $crimeType)
<div class="col-md-4">
<ul class="list-unstyled">
<li>
<div class="checkbox">
<label>
<input value="{{$crimeType->id}}" type="checkbox" name="id[]" id="checkid"> {{$crimeType->type}}
</label>
</div>
</li>
</ul>
</div>
#endforeach
<div class="col-md-12 row">
<div class="form-group">
<br>
<hr>
<input type="submit" ng-click="click1()" value="Next" class="btn btn-default">
</div>
</div>
{!!Form::close()!!}
</div>
</div>
<!-- On submitting above form hide the above div and display below div...this is working fine..-->
<div ng-show="div2">
<div class="col-md-12 row">
<h2>Step - 2 : Crime Details</h2>
<hr>
<h3>Can You Tell Us About The Crime</h3>
<br>
<h5><strong>#if (!empty($step1[0])) ? {{$step1[0]->question}} : ''#endif?</strong></h5>
<div class="row">
<div class="control-group">
<div class="form-group col-md-3">
<input type="number" class="form-control nbr" placeholder="xxx-xxx-xxx">
</div>
<div class="col-md-9"></div>
</div>
</div>
<h5><strong>#if (!empty($step1[1])) ? {{$step1[1]->question}} : ''#endif?</strong></h5>
<div class="row">
<div class="control-group">
<div class="form-group col-md-3">
<input type="number" class="form-control nbr" placeholder="xxx-xxx-xxx">
</div>
<div class="col-md-9"></div>
</div>
</div>
<h5><strong>#if (!empty($step1[2])) ? {{$step1[2]->question}} : ''#endif?</strong></h5>
<div class="row">
<div class="control-group">
<div class="form-group col-md-3">
<input type="textarea" class="form-control nbr">
</div>
<div class="col-md-9"></div>
</div>
</div>
<div class="row">
<br>
<hr>
<div class="form-group col-md-2">
<button ng-click="click2()" class="btn btn-default">Next</button>
</div>
<div class="form-group col-md-offset-10">
<button ng-click="click2()" class="btn btn-primary">Skip</button>
</div>
</div>
</div>
</div>
<!-- Similarly there are three more div's where I have to display the fetched data...-->
Script :
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('[name="_token"]').val()
}
});
$(document).ready(function(){
$('#formid').on('submit', function(e){
e.preventDefault();
var id = new Array();
$('input[name="id[]"]:checked').each(function()
{
id.push($(this).val());
});
var $form = $('form');
$.ajax({
url:$form.attr('url'),
type: $form.attr('method'),
data: {id},
dataType:'json',
success: function(data){
var step1 = data.step1;
var step2 = data.step2;
var step3 = data.step3;
var step4 = data.step4;
var step5 = data.step5;
// If I use success, I am able to get data to these variables but unable to make use them on view wherever required. But now I am trying to use the returned object directly on the view without callback in the ajax. Even by using callback if it is possible, please help me out...
}
});
});
});
</script>
I solved my problem, here is the code I changed/added :
AngularJs Files :
formCtrl.js :
angular.module('formCtrl', []).controller('formController', function($scope, $http, Comment){
Comment.get().success(function(data){
$scope.crimeTypes = data[0];
});
$scope.div1 = true;
$scope.div2 = false;
$scope.div3 = false;
$scope.div4 = false;
$scope.div5 = false;
$scope.div6 = false;
$scope.div7 = false;
$scope.selected = {};
$scope.click1 = function(data){
var id = [];
for(var i in data){
if(data[i].selected==true){
id.push(data[i].id);
}
}
$scope.selected = {id};
$http({
method : 'POST',
url : '/index1',
data : $.param($scope.selected),
headers :{'Content-Type':'application/x-www-form-urlencoded'}
})
.success(function(data) {
console.log(data);
});
$scope.div1 = false;
$scope.div2 = true;
$scope.div3 = false;
$scope.div4 = false;
$scope.div5 = false;
$scope.div6 = false;
$scope.div7 = false;
};
$scope.click2 = function(){
$scope.div1 = false;
$scope.div2 = false;
$scope.div3 = true;
$scope.div4 = false;
$scope.div5 = false;
$scope.div6 = false;
$scope.div7 = false;
};
$scope.click3 = function(){
$scope.div1 = false;
$scope.div2 = false;
$scope.div3 = false;
$scope.div4 = true;
$scope.div5 = false;
$scope.div6 = false;
$scope.div7 = false;
};
$scope.click4 = function(){
$scope.div1 = false;
$scope.div2 = false;
$scope.div3 = false;
$scope.div4 = false;
$scope.div5 = true;
$scope.div6 = false;
$scope.div7 = false;
};
$scope.click5 = function(){
$scope.div1 = false;
$scope.div2 = false;
$scope.div3 = false;
$scope.div4 = false;
$scope.div5 = false;
$scope.div6 = true;
$scope.div7 = false;
};
$scope.click6 = function(){
$scope.div1 = false;
$scope.div2 = false;
$scope.div3 = false;
$scope.div4 = false;
$scope.div5 = false;
$scope.div6 = false;
$scope.div7 = true;
};
});
formService.js :
angular.module('formService',[])
.factory('Comment', function($http){
return {
get:function(){
return $http.get('/index1data');
}
}
});
main.js :
var app = angular.module('angularApp', ['mainCtrl','formCtrl','formService'], function($interpolateProvider) {
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
});
No code change in Route and Controller files. In view only changed the div with checkbox class code to as shown below.
Laravel Files :
View :
<div class="checkbox">
<input value="<%crimeType.id%>" type="checkbox" ng-model="crimeType.selected" id="<%crimeType.type%>">
<label for="<%crimeType.type%>"><% crimeType.type %></label>
</div>
NOTE : I didn't used ajax script which I had posted in the question. Controller and Route files are not changed.

Taking post parameters in ajax comment form

I'm trying to customize one comment form from template which I purchased. In short I have 3 files - post.php, comment_post.php and main.js. In post.php is simple html comment form. I'm not that good in ajax part and still trying to learn php so I'll need some help with this.
<form class="row" role="form" id="comments-form" name="comments-form" action="comments-send.php" method="POST">
<input type="text" class="form-control form-name-error" name="comments[form-name]" id="form-name" placeholder="Name">
<input type="email" class="form-control form-email-error" id="form-email" name="comments[form-email]" placeholder="Email">
<input type="hidden" name="comments[post_id]" value="<?php echo $row['post_id'];?>" >
<textarea class="form-control input-row-2 form-review-error" rows="3" id="form-comments" name="comments[form-review]" placeholder="Comment"></textarea>
<div class="form-group text-right btn-submit">
<button type="submit" class="btn btn-dark button-submit">Send</button>
<div class="message-success alert-success alert hidden" style="position: absolute"><i class="fa fa-check"></i></div>
</div>
</form>
I have one hidden field to get post_id..
Here is comment_post.php which is the problem ( I think ). The errors are Undefined variable: comment_author_name, comment_author_image .. etc
if(isset($_POST['comments'])) {
$response = array('status' => '', 'errors'=>array());
foreach($_POST['comments'] as $key => $value) {
if($value == '') {
$response['errors'][$key.'-error'] = 'error';
}
}
if(empty($response['errors'])) {
$_POST['comments']['form-name'] = $comment_author_name;
$_POST['comments']['form-email'] = $comment_author_email;
$_POST['comments']['post_id'] = $post_id;
$_POST['comments']['form-review'] = $comment_text;
$sql = "INSERT INTO comments (comment_author_name, comment_author_email, comment_date, comment_text, post_id)
VALUES (:comment_author_name, :comment_author_email, NOW(), :comment_text, :post_id)";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(":comment_author_name", $comment_author_name);
$stmt->bindValue(":comment_author_email", $comment_author_email);
$stmt->bindValue(":post_id", $post_id);
$stmt->bindValue(":comment_text", $comment_text);
$stmt->execute();
$response['status'] = 'ok';
} else {
$response['status'] = 'error';
}
echo json_encode($response);
}
In original file (comment_post.php) there is nothing for database insertion and this is my code. I'm not sure how to get values from the form when is send to the php part. This is from main.js file for the comment_form.
$("#comments-form").submit(function(e) {
$('#comments-form .form-control').removeClass('#comments-form message-error');
$.post("comments-send.php", $('#comments-form').serialize(), function(data) {
if (data.status === 'ok') {
$("#comments-form .message-success").removeClass('hidden').velocity({ opacity : 1 });
$("#comments-form .button-submit").addClass('button-transparent');
$('#comments-form .form-control').val('');
setTimeout(function() {
$("#comments-form .message-success").velocity({ opacity : 0 }, function() {
$(this).addClass('hidden');
});
$("#comments-form .button-submit").removeClass('button-transparent');
}, 3000);
} else {
$.each(data.errors, function(i, e) {
$('.' + i).addClass('#comments-form message-error');
});
}
}, 'json');
e.preventDefault();
});
$("#comments-form").on('keyup', '.contact-form', function() {
var that = this;
if ($(this).val() !== '') {
$(this).removeClass('message-error');
} else {
$(that).addClass('message-error');
}
});
It looks like you are not setting your variables correctly
update to this
$comment_author_name = $_POST['comments']['form-name'];
$comment_author_email = $_POST['comments']['form-email'];
$post_id = $_POST['comments']['post_id'];
$comment_text = $_POST['comments']['form-review'];
What you want to do is actually get the values from the $_POST and save them to the variables you have created.
Previously you were doing the oposite, therefore the variables did not exist and you were also reseting the values in your $_POST

Categories