Laravel + Vue unable to save data to my database - php

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!

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',
];
}

Codeigniter form validation return false on ajax request

Before I start, sorry for my English. i am developing a website using CI on Backend. And i want to make a registration system without refreshing the page. If i try with post form submit i got no error and everything went good. but when I try using with ajax request, I can't use form validation because form validation return false and validation_errors is empty. if I disable form validation, ajax request works well. here is my controller and ajax request. Please help me.
User.php (My Controller)
public function register(){
$this->load->library('form_validation');
$this->form_validation->set_rules('email_kyt', 'Email', 'is_unique[users.email]');
$this->form_validation->set_rules('username_kyt', 'Kullanici', 'is_unique[users.username]');
if($this->form_validation->run() == FALSE) {
$data = json_encode(array('status'=> false,'info'=>validation_errors()));
}else {
if($this -> input -> is_ajax_request()){
$userData = array(
'email' => strip_tags($this->input->get('email_kyt')),
//bla bla,
);
if ($this->User_model->form_insert($userData) == true) { //this method works perfectly.
$data = json_encode(array('status' => true,'info' => 'Successfully Registered'));
} else {
$data = json_encode(array('status' => false,'info'=>'The Error Occurred During Registration'));
}
}else{
$data = json_encode(array('status'=> false,'info'=>'This is not Ajax request'));
}
}
echo $data;
}
}
And here is my ajax request in js
$(document).ready(function(){
$('#btn_register').on('click',function (e) {
$('form[name=register-form]').unbind("submit");
$('form[name=register-form]').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'get',
url: url + 'User/register', //url is correct i tested without form validation
data: $('#register-form').serialize(),
dataType: "json",
success: function (data) {
if (data.status == true) {
alert(data.info);
window.location.reload();
json= [];
} else if (data.status == false) {
$('#span_validate').html(data.info);
json= [];
}
}
});
});
});
});
edit: and here is my form:
<!-- Register Form -->
<?php echo form_open(base_url('index.php/User/register'),array('id' => 'register-form','name' => 'register-form')); ?>
<?php echo form_hidden($this->security->get_csrf_token_name(), $this->security->get_csrf_hash()); ?>
<div class="md-form">
<input type="text" id="name_kyt" name="name_kyt" class="form-control" data-toggle="popover" data-trigger="focus" data-content="...">
<label for="name_kyt" >Name</label>
</div>
<div class="md-form">
<input type="text" id="surname_kyt" name="surname_kyt" class="form-control" data-toggle="popover" data-trigger="focus" data-content="...">
<label for="surname_kyt" >Surname</label>
</div>
<div class="md-form">
<input type="text" id="username_kyt" name="username_kyt" class="form-control" data-toggle="popover" data-trigger="focus" data-content="...">
<label for="username_kyt" > Username </label>
</div>
<div class="md-form">
<input type="email" id="email_kyt" name="email_kyt" class="form-control" data-toggle="popover" data-trigger="focus" data-content="...">
<label for="email_kyt" >Email</label>
</div>
<div class="md-form">
<input type="password" id="password_kyt" name="password_kyt" class="form-control" data-toggle="popover" data-trigger="focus" data-content="...">
<label for="password_kyt" >Password</label>
</div>
<div class="md-form">
<input type="password" id="password_confirm" name="password_onay" class="form-control">
<label for="password_confirm" >Password Confirm</label>
</div>
<div class="form-group text-center">
<div class="row">
<div class="col-sm-10 col-sm-offset-3 mr-auto ml-auto">
<input type="submit" name="btn_register" id="btn_register" tabindex="4" class="btn btn-register mr-auto ml-auto" value="Register">
<p><span id="span_validate" class="label label-default mr-auto ml-auto"></span></p>
</div>
</div>
</div>
<!-- End of Register Form -->
<?php echo form_close(); ?>
Please refer below example to validate a form in CodeIgniter using ajax call.
1. ajax code.
$(document).ready(function(){
$('#btn_register').on('click',function (e) {
$('form[name=register-form]').unbind("submit");
$('form[name=register-form]').submit(function (e) {
e.preventDefault();
var formData = $("#register-form").serialize();
$.ajax({
type: 'get',
url: url + 'User/register',
data: formData,
success: function (data) {
if (data.status == true) {
alert(data.info);
window.location.reload();
json= [];
} else if (data.status == false) {
$('#span_validate').html(data.info);
json= [];
}
}
});
});
});
});
2. Controller code :
Load form_validation library and form helper
$this->load->library('form_validation');
$this->load->helper('form');
Now write your controller as ...
public function register(){
$this->load->library('form_validation');
$this->load->helper('form');
$this->form_validation->set_rules('email_kyt', 'Email', 'is_unique[users.email]');
$this->form_validation->set_rules('username_kyt', 'Kullanici', 'is_unique[users.username]');
if($this->form_validation->run() == FALSE) {
echo $data = json_encode(array('status'=> false,'info'=>validation_errors())); die;
}else {
if($this -> input -> is_ajax_request()){
$userData = array(
'email' => strip_tags($this->input->get('email_kyt')),
//bla bla,
);
if ($this->User_model->form_insert($userData) == true) { //this method works perfectly.
echo $data = json_encode(array('status' => true,'info' => 'Successfully Registered')); die;
} else {
echo $data = json_encode(array('status' => false,'info'=>'The Error Occurred During Registration')); die;
}
}else{
echo $data = json_encode(array('status'=> false,'info'=>'This is not Ajax request')); die;
}
}
}
}
I have solved this problem. Form validation only works with post method. If you use get method it won't work.

Vue form not sending data in request

I have a form in one component, and I am trying to send data on submit with Ajax request:
<form>
<div class="control">
<input class="input is-large" type="email" v-model="email" required>
<label>E-post</label>
</div>
<div class="control">
<input class="input is-large" type="password" v-model="password" required>
<label>Passord</label>
</div>
<div #click="save" type="submit" class="button hero-button is-medium is-primary">
Logg in
</div>
</form>
This is the method for post request, I am using axios library for Ajax requests:
methods: {
save() {
const form = new FormData();
form.append('email', this.email);
form.append('password', this.password);
this.$backend.post('/user/login', form, {
}).then(() => {
console.log('success');
}, (err) => {
console.log(err);
});
}
}
But, when I check on the backend side, built with laravel, I get an empty request:
{"request":[]}
This is the function in the controller on the backend side:
public function login(Request $request)
{
//testing $request object
return ['request' => $request->all()];
$authenticatedUser = $this->authenticate($request->email, $request->password);
if (!$authenticatedUser) {
$remoteAuthenticated = $this->checkWplUser($request->email, $request->password);
if (!$remoteAuthenticated) {
return $this->response->errorUnauthorized();
}
}
return $this->issueToken($request->email, $request->password);
//return $this->returnUserResponse();
}
This is how the request header looks like:
How can I fix this?

UserFrosting forms - Invalid or missing CSRF token

I am trying to submit a simple form in UserFrosting and as a test only display the success message, with no data modification. I followed the guidance from Lesson 2 but I ran into the CSRF issue:
UserFrosting returns the following error:
Invalid or missing CSRF token.
What am I missing? Up until this point UserFrosting was very easy to digest :(
The form:
<form class="form-horizontal" role="form" name="requestDescription" action="{{site.uri.public}}/soap/requests/desc/edit/{{ keyname }}" method="post">
<div class="form-group">
<label for="input_group" class="col-md-2 control-label">Name</label>
<div class="col-md-10">
<input type="text" id="input_name" class="form-control" name="lgname" placeholder="{{ name }}">
</div>
</div>
<div class="form-group text-center">
<button type="submit" class="btn btn-success text-center">Update</button>
</div>
</form>
with added script part to the bottom of the twig file:
<script>
$(document).ready(function() {
// Load the validator rules for this form
var validators = {{validators | raw}};
ufFormSubmit(
$("form[name='requestDescription']"),
validators,
$("#userfrosting-alerts"),
function(data, statusText, jqXHR) {
// Reload the page on success
window.location.reload(true);
}
);
});
</script>
Here are my two functions from the controller:
public function soapRequestDescriptionEditPage($keyname){
if (!$this->_app->user->checkAccess('uri_soap_requests')){
$this->_app->notFound();
}
$requestDetails = $this->soapRequestReadMeta($keyname);
$schema = new \Fortress\RequestSchema($this->_app->config('schema.path') . "/forms/soap-request-description-edit.json");
$this->_app->jsValidator->setSchema($schema);
$this->_app->render('soap/soap-request-description-edit.twig', [
"name" => $requestDetails['name'],
"description" => $requestDetails['description'],
"keyname" => $keyname,
"validators" => $this->_app->jsValidator->rules()
]);
}
public function test(){
if (!$this->_app->user->checkAccess('uri_soap_requests')) {
$this->_app->notFound();
}
$post = $this->_app->request->post();
$ms = $this->_app->alerts;
$requestSchema = new \Fortress\RequestSchema($this->_app->config('schema.path') . "/forms/soap-request-description-edit.json");
$rf = new \Fortress\HTTPRequestFortress($ms, $requestSchema, $post);
$ms->addMessageTranslated("success", "Everyone's title has been updated!", $post);
$rf->sanitize();
if (!$rf->validate()) {
$this->_app->halt(400);
}
$data = $rf->data();
}
Entries from the index.php file:
$app->post('/soap/requests/desc/edit/:request_id/?', function () use ($app) {
$controller = new UF\SoapController($app);
return $controller->test();
});
$app->get('/soap/requests/desc/edit/:request_id/?', function ($request_id) use ($app) {
$controller = new UF\SoapController($app);
return $controller->soapRequestDescriptionEditPage($request_id);
});
Finally, the schema:
{
"lgname" : {
"validators" : {
"length" : {
"min" : 1,
"max" : 150,
"message" : "The new title must be between 1 and 150 characters long."
}
},
"sanitizers" : {
"raw" : ""
}
}
}
As of UserFrosting 4, you should explicitly add the hidden CSRF input fields to your form. There is a partial template forms/csrf.html.twig that contains these fields, which you can insert using Twig's include tag:
<form class="form-horizontal" role="form" name="requestDescription" action="{{site.uri.public}}/soap/requests/desc/edit/{{ keyname }}" method="post">
{% include "forms/csrf.html.twig" %}
<div class="form-group">
<label for="input_group" class="col-md-2 control-label">Name</label>
<div class="col-md-10">
<input type="text" id="input_name" class="form-control" name="lgname" placeholder="{{ name }}">
</div>
</div>
<div class="form-group text-center">
<button type="submit" class="btn btn-success text-center">Update</button>
</div>
</form>
For requests that are made without a form (for example, if it has been constructed purely in Javascript), you can grab the CSRF token name and value from the global site.csrf variable:
var userName = 'luke';
var fieldName = 'lgname';
var data = {
'value': fieldValue
};
data[site.csrf.keys.name] = site.csrf.name;
data[site.csrf.keys.value] = site.csrf.value;
var url = site.uri.public + '/api/users/u/' + userName + '/' + fieldName;
return $.ajax({
type: "PUT",
url: url,
data: data
}).done(function (response) {
window.location.reload();
});
It turned out that my code was fine. There were unrelated javascript errors on the page affecting UserFrosting form processing. Fixing these errors allowed UserFrosting to handle the form.
Note to self... make it a habit to look into the console for javascript errors :)

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

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;
};

Categories