Laravel - Validation errors - javascript

I want to return the $validator->errors() and include another element "message" to hold the status of the project.
for example:
if ($validator->fails()) {
$response = array('data' => $validator->errors());
$status = 'failed';
// I tried this but it didn't work
// $response = array('data' => $response, 'status' => 'failed')
} else {
$status = (Phone::create($post_data)) ? "success" : 'failed';
$response = array('status' => $status);
}
return Response::json($response);
So in javascript side I would load something like:
if (data.status == 'success') { console.log('success'); }
else {
$.each(data, function(index, value) {
message += '<div class="text-warning"> <span class="glyphicon glyphicon-exclamation-sign"></span> ' + (data[index]) + '</div>';
});
}

The method errors() returns a MessageBag instance, you need to retrieve an array:
if ($validator->fails())
{
$response = array(
'data' => $validator->errors()->all(),
'status' => 'failed'
);
}
else
{
$status = (Phone::create($post_data)) ? "success" : 'failed';
$response = array('status' => $status);
}
return Response::json($response);

Related

How to reload window after success case

I'm using ReactJS with Laravel API and I don't know why the window won't reload, and I didn't get the success message. even the status is correct
this my frontend code :
const addUnit = (e) => {
e.preventDefault();
const formData = new FormData();
formData.append('unit_name', unit_name);
formData.append('building_id', building_id);
formData.append('floor_id', floor_id);
formData.append('type_id', type_id);
formData.append('user_id', user_id);
formData.append('unit_status', unit_status);
formData.append('unit_roomnumber', unit_roomnumber);
formData.append('unit_added_date', unit_added_date);
formData.append('unit_rent_per_month', unit_rent_per_month);
formData.append('frais_percent', frais_percent);
for (let i = 0; i < unit_pictures.length; i++) {
formData.append('unit_pictures[]', unit_pictures[i])
}
axios.post(`${API_ENDPOINT}/api/addUnite`, formData).then(response => {
if (response.data.status === 200) {
window.location.reload();
}
else if (response.data.status == 400) {
new Swal("warning", response.data.errors, "Warning");
}
})}
this is backend code :
public function addUnite(Request $request)
{
$validator = Validator::make($request->all(), [
'unit_name' => 'required|max:191',
'unit_status' => 'required',
'unit_roomnumber' => 'required',
'unit_added_date' => 'required',
'unit_rent_per_month' =>'required'
]);
if ($validator->fails()) {
return response()->json([
'status' => 422,
'errors' => "All Fields Are required !",
]);
}
else {
$exist = Unite::where('type_id', '=', Input::get('type_id'))
->where('unit_roomnumber', '=', Input::get('unit_roomnumber'))
->where('building_id', '=', Input::get('building_id'))
->exists();
if ($exist) {
return response()->json([
'status' => 400,
'errors' => "This Unit already exist !",
]);
}
else {
$unit = new Unite();
$unit->unit_name = $request->input('unit_name');
$unit->building_id = $request->input('building_id');
$unit->unit_id = $request->input('unit_id');
$unit->user_id = $request->input('user_id');
$unit->frais_percent = $request->input('frais_percent');
$unit->floor_id = $request->input('floor_id');
$unit->type_id = $request->input('type_id');
$unit->unit_status = $request->input('unit_status');
$unit->unit_roomnumber = $request->input('unit_roomnumber');
$unit->unit_added_date = $request->input('unit_added_date');
$unit->unit_rent_per_month = $request->input('unit_rent_per_month');
// $unit->unit_pictures = $request->file('unit_pictures');
$allUploadApiReponse = array();
foreach ($unit->unit_pictures = $request->file('unit_pictures') as $imagefile) {
$uploadedFileUrl = cloudinary()->upload(
($imagefile)->getRealPath(),
[
'folder' => 'Units',
'discard_original_filename' => true,
]
)->getSecurePath();
array_push($allUploadApiReponse, $uploadedFileUrl);
}
// To check content
print_r($allUploadApiReponse);
$unit->unit_pictures = $allUploadApiReponse;
if($unit->save()){
return response()->json([
'message' => "Unit Added Successfully",
'status' => 200,
]);}
}
PS: the unit is added successfully but I didn't get the success message
I think maybe issue from your react-router when trying routing from browser.
Not sure but you can try:
history.go(0);
or
window.location.href = window.location.href;

node.js add array of images into corresponding array

I'm new in node.js and I'm getting some data from database (actions). Every action has a number of images registered in another table so that I can get them by action id.
I'm trying to add an array of these images to the correponding action so that I can loop through them in the frontend.
In php I use to do like this:
$return = array();
$images = array();
$image = array();
$select = "SELECT id, title, description FROM actions WHERE id = ? order by id DESC";
$stmt = $mysqli->prepare($select);
$stmt->bind_param('s', $id);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($id, $title, $description);
while ($stmt->fetch()) {
$registers = array(
"id" => $id, "title" => $title, "description" => $description, "images" => $image
);
$selectImages = mysqli_query($mysqli, "SELECT id, image FROM action_images WHERE action_id = '" . $id . "' ");
while ($row = $selectImages->fetch_array(MYSQLI_BOTH)) {
$images = array("imageID" => $row['id'], "image" => $row['image']);
array_push($registers["images"], $images);
}
$return[] = $registers;
}
Is there something similar in javscript/node.js? I tried some things described in the code below but nothing worked as expected.
This is my controller:
async selectActions(req, res) {
let actionData = [];
conn.execute('SELECT * FROM actions',
function (err, results, fields) {
// console.log(err);
// console.log(results);
if (err == null) {
results.forEach(action => {
conn.execute('SELECT * FROM actions_images WHERE actionID = ?',
[action.id],
function (imagesError, imagesResults, ImagesFields) {
// I've tried some things like:
actionData = [results, imagesResults];
// and
actionData = [...results, ...imagesResults]
// and
results.push(imagesResults)
// but nothing had the expected results displayed in the image below
console.log(actionData);
}
);
});
return res.json(results);
} else {
return res.json('error fetching actions from database: ' + err);
}
});
},
Action images array must be another item in each action item:
Try this...
Promise.all(results.map((action, index) => {
return Promise(resolve => {
conn.execute('SELECT * FROM actions_images WHERE actionID = ?',
[action.id],
function(imagesError, imagesResults, ImagesFields) {
results[index].action_images = imagesResults;
resolve(true);
}
);
})
}))
console.log(results);

How to migrate from laravel fractal to laravel resource and not repeating my self

I have been trying to find a way to migrate from laravel fractal to laravel API resource due to its direct usage installing laravel but I'm having an issue migrating functions to API resource. I have functions to filter, sort, get actual responses and cache relating to all my model which avoids me not to repeat myself.
trait ApiResponser
{
private function successResponse($data, $code)
{
return response()->json($data, $code);
}
protected function errorResponse($message, $code)
{
return response()->json(['error' => $message, 'code' => $code], $code);
}
protected function showAll(Collection $collection, $code = 200)
{
if ($collection->isEmpty()) {
return $this->successResponse(['data' => $collection], $code);
}
$transformer = $collection->first()->transformer;
$collection = $this->filterData($collection, $transformer);
$collection = $this->sortData($collection, $transformer);
$collection = $this->paginate($collection);
$collection = $this->transformData($collection, $transformer);
$collection = $this->cacheResponse($collection);
return $this->successResponse($collection, $code);
}
protected function showOne(Model $instance, $code = 200)
{
$transformer = $instance->transformer;
$instance = $this->transformData($instance, $transformer);
return $this->successResponse($instance, $code);
}
protected function AuthErrorResponse($message, $code)
{
return response()->json(['errors' => ['root' => $message]], $code);
}
protected function AuthSuccessResponse(Model $model, $token, $code = 200)
{
return response()->json(['data' => $model, 'meta' => ['token' => $token]], $code);
}
protected function showMessage($message, $code = 200)
{
return $this->successResponse(['data' => $message], $code);
}
protected function filterData(Collection $collection, $transformer)
{
foreach (request()->query as $query => $value) {
$attribute = $transformer::originalAttribute($query);
if(isset($attribute, $value)){
$collection = $collection->where($attribute, $value);
}
}
return $collection;
}
protected function sortData(Collection $collection, $transformer)
{
if (request()->has('sort_by')) {
$attribute = $transformer::originalAttribute(request()->sort_by);
$collection = $collection->sortBy->{$attribute};
}
return $collection;
}
protected function paginate(Collection $collection)
{
$rules = [
'per_page' => 'integer|min:2|max:50',
];
Validator::validate(request()->all(), $rules);
$page = LengthAwarePaginator::resolveCurrentPage();
$perPage = 15;
if (request()->has('per_page')) {
$perPage = (int) request()->per_page;
}
$result = $collection->slice(($page - 1) * $perPage, $perPage)->values();
$paginated = new LengthAwarePaginator($result, $collection->count(), $perPage, $page, [
'path' => LengthAwarePaginator::resolveCurrentPath(),
]);
$paginated->appends(request()->all());
return $paginated;
}
protected function transformData($data, $transformer)
{
$transformation = fractal($data, new $transformer);
return $transformation->toArray();
}
protected function cacheResponse($data)
{
$url = request()->url();
$queryParams = request()->query();
ksort($queryParams);
$queryString = http_build_query($queryParams);
$fullUrl = "{$url}?{$queryString}";
return Cache::remember($fullUrl, 30/60, function() use($data){
return $data;
});
}
}

error: VM2713:1 Uncaught SyntaxError: Unexpected token U in JSON at position 0

Why I've got this error VM2713:1 Uncaught SyntaxError: Unexpected token U in JSON at position 0 but i've successfully updated the database table?The error was Uncaught SyntaxError: Unexpected token U in JSON at position 0 in my console. I insert some data but at the same time i'm updating some data from database table. Can you help me with this guys? thank you in advance.
Here's my code
$larea = $proloc_larea." ".$_POST['areatype'];
$rpu = $_GET['rpudata'];
$rpu_id = $_GET['rpu_id'];
$arr = explode(",",$rpu_id);
$property_array2 = array(
'view_flag' => 0,
);
$c = '';
$barcode = time();
$property_array = array('sitio' => $proloc_sitio,
'loc_street' => $proloc_street,
'loc_province' => $add_provz,
'view_flag' => 1
);
if(($property_array['land_area']!= " ") || !empty($property_array['land_area'])){
foreach($arr as $r){
$b = trim($r);
$c = $b;
$con2 = "OCPC_ID='".$c."'";
$result2 = $db->update('property_information',$property_array2,$con2);
//echo $c;
}
$result = $db->insert('property_information',$property_array);
//echo $result;
if ($result) {
$response = array(
'result2' => $result2,
'error' => false,
'message' => 'Successfully inserted',
'barcode' => $barcode
);
echo json_encode($response,true);die();
}
else{
$response = array(
'error' => true,
'message' => 'error',
'barcode' => $barcode
);
echo json_encode($response,true);die();
}
}else {
$response = array(
'error' => true,
'message' => 'some fields are not filled.'
);
echo json_encode($response,true);die();
}
Here's my success in ajax
success: function(resback){
var res = $.parseJSON(resback);
if(res.error==false) {
$('#property').hide();
var modal = $('#blabla');
modal.modal('show');
modal.find('input[name="cs_barcode"]').val(res.barcode);
} else {
alert(res.message);
}
}
The error was Uncaught SyntaxError: Unexpected token U in JSON at position 0 in my console. I insert some data but at the same time i'm updating some data from database table. Can you help me with this guys? thank you in advance.

I am getting this json error and ajax submit form is not getting closed

this is the json error i am getting
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
if (e.which == 9) {
here is my controller method
// To add fabric and colour data in order entry form of 'Combos' product type..
function add_ajax_combos($newFabricName = '', $fabricSavedCallback = '', $product_type_id = '', $field = '') {
if (!empty($this->data)) {
$this->autoRender = false;
$this->layout = 'ajax';
$name = $this->data['FabricRange']['name'];
$product_id = $this->data['FabricRange']['product_id'];
$chk_range_exists = $this->FabricRange->find('count', array('conditions' => array('FabricRange.name' => $name, 'FabricRange.product_id' => $product_id)));
if ($chk_range_exists == 0) {
$chk_same_name_already_exist = $this->FabricRange->find('first', array('conditions' => array('FabricRange.name' => $name), 'fields' => array('range_id')));
$update_flag = false;
if ($chk_same_name_already_exist) {
$this->data['FabricRange']['range_id'] = $chk_same_name_already_exist['FabricRange']['range_id'];
} else {
$update_flag = true;
}
$name = $this->data['FabricRange']['colour'];
$usable_width = $this->data['FabricRange']['usable_width'];
$range_id= $this->data['FabricRange']['range_id'];
$chk_range_color_exists = $this->FabricRangeColour->find('count', array('conditions' => array('FabricRangeColour.name' => $name, 'FabricRangeColour.usable_width' => $usable_width)));
}
if ($chk_range_color_exists == 0) {
$usable_width = $this->data['FabricRange']['usable_width'];
$purchase_wizard_code = $this->data['FabricRange']['purchase_wizard_code'];
$can_turn = $this->data['FabricRange']['can_turn'];
$pattern_repeat = $this->data['FabricRange']['pattern_repeat'];
$deleted = $this->data['FabricRange']['deleted'];
$discontinued = $this->data['FabricRange']['discontinued'];
$ds = $this->FabricRange->getDataSource();
$ds->begin($this->FabricRange);
$this->FabricRange->create();
if ($this->FabricRange->save($this->data)) {
if ($update_flag) {
$id = $this->FabricRange->id;
$this->FabricRange->saveField('range_id', $id);
$fabric_ranges_id = $id;
} else {
$fabric_ranges_id = $this->data['FabricRange']['range_id'];
}
$fabricColourId = 0;
if (isset($this->data['FabricRange']['colour_id']) == false || strlen(trim($this->data['FabricRange']['colour_id'])) == 0) {
// new colour
$this->FabricRangeColour->create();
if ($this->FabricRangeColour->save(array('FabricRangeColour' => array('name' => $name, 'fabric_ranges_id' => $fabric_ranges_id, 'usable_width' => $usable_width, 'purchase_wizard_code' => $purchase_wizard_code
, 'can_turn' => $can_turn, 'pattern_repeat' => $pattern_repeat, 'deleted' => $deleted, 'discontinued' => $discontinued))) == false) {
$ds->rollback($this->FabricRange);
return json_encode(array("status" => "FAILURE"));
}
$fabricColourId = $this->FabricRangeColour->id;
} else {
$fabricColourId = $this->data['FabricRange']['colour_id'];
}
$ds->commit($this->FabricRange);
return json_encode(array("status" => "SUCCESS", 'fabric' => $this->data['FabricRange']['name'], 'id' => $this->FabricRange->id, 'colour_id' => $fabricColourId, 'colourname' => $this->data['FabricRange']['colour'], 'fabric_category_id' => $this->data['FabricRange']['fabric_categories_id']));
} else {
$ds->rollback($this->FabricRange);
return json_encode(array("status" => "FAILURE"));
}
} else {
return json_encode(array("status" => "FAILURE"));
}
}
$this->layout = 'ajax';
$fabricCategories = $this->FabricCategory->getFabricCategoryList('list');
$fabricColours = $this->FabricRangeColour->getAllAsList();
$this->set('fabric_name', $newFabricName);
$result_pr = $this->ProductType->find('first', array(
'fields' => array('product_id'), 'conditions' => array('id' => $product_type_id)
));
$product_id_title = $result_pr['ProductType']['product_id'];
$this->set('product_id', $product_id_title);
$this->set('field', $field);
$this->set(compact('fabricCategories', 'fabricColours', 'fabricSavedCallback'));
}
here is my ctp
function ajaxSubmit(field) {
var requestUrl = '<?php echo $this->Html->url(array('controller'=>'fabric_ranges','action'=>'add_ajax_combos'),true);?>';
if (validateForm()) {
$.post(requestUrl, $('#FabricRangeAddAjaxCombosForm').serialize(),
function(data) {
data = JSON.parse(data);
console.log(data);
if (data.status == 'SUCCESS') {
if (typeof <?php echo $fabricSavedCallback;?> != 'undefined') {
<?php echo $fabricSavedCallback;?>(data.id, data.fabric, data.colour_id, data.colourname, data.fabric_category_id);
if (field == 1) {
$("#fabricsAutoComplete").val(data.fabric);
$("#OrderEntryItemRollerBlindComboFabricFrontBlind").val(data.id);
$("#OrderEntryItemRollerBlindComboColours").val(data.colourname);
$("#OrderEntryItemRollerBlindComboFabricColourFrontBlind").val(data.colour_id);
$("#OrderEntryItemRollerBlindComboFabricCategoriesId").val(data.fabric_category_id);
}
else {
$("#fabricsAutoCompleteBack").val(data.fabric);
$("#OrderEntryItemRollerBlindComboFabricBackBlind").val(data.id);
$("#OrderEntryItemRollerBlindComboColoursBack").val(data.colourname);
$("#OrderEntryItemRollerBlindComboFabricColourBackBlind").val(data.colour_id);
$("#OrderEntryItemRollerBlindComboFabricCategoriesId2").val(data.fabric_category_id);
}
}
} else {
alert('An error occured while adding the fabric. The new fabric wasn\'t saved.');
}
}
);
}
}
here is the method that calls for closeandupdatefabrics
function closeAndUpdateFabrics(fabricId, fabric,color, colourId) {
$('#addFabricDialog').dialog('close');
$("#fabricsAutoComplete").val(fabric);
$("#OrderEntryItemRollerBlindComboFabricFrontBlind").val(fabricId);
$("#OrderEntryItemRollerBlindComboColours").val(color);
var fabricsIdBox = document.getElementById('OrderEntryItemRollerBlindComboFabricFrontBlind');
setFabriCategory(fabricsIdBox);
loadFabricColours(fabricsIdBox, 'OrderEntryItemRollerBlindComboFabricColourFrontBlind', function() {
$("#OrderEntryItemRollerBlindComboFabricColourFrontBlind").val(colourId);
});
}
My problem is the ajax box is not getting closed and give me a json error in console.

Categories

Resources