Codeigniter Checkbox - database

Can you guys tell me what i'm doing wrong here in my code? I tried to post the data inside these checkboxes to database
here is the view.php
(more code)
<div class="form-group">
<label class="control-label col-md-3">Infection</label>
<div class="col-md-9">
<input type="checkbox" name="infectionType[]" value="vap"> VAP
<input type="checkbox" name="infectionType[]" value="hap"> HAP
<input type="checkbox" name="infectionType[]" value="isk"> ISK
<input type="checkbox" name="infectionType[]" value="iad"> IAD
</div>
</div>
and this is my controller.php
public function insert_surveilance(){
$data=array(
(more code)
'vap' => $this->input->post('vap'),
'hap' => $this->input->post('hap'),
'isk' => $this->input->post('isk'),
'iad' => $this->input->post('iad'),
(more code)
);
$data[]=
$insert = $this->surveilance_model->insert_surveilance($data);
echo json_encode(array("status"=>TRUE));
}
then this is my model.php
public function insert_surveilance($data){
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}
this is the save function
...
function save(){
var url;
if(save_method == 'add'){
url="<?php echo site_url('surveilance/insert_surveilance')?>";
} else {
url="<?php echo site_url('surveilance/edit_surveilance')?>";
}
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
//if success close modal and reload ajax table
$('#modal_form').modal('hide');
location.reload();// for reload a page
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Failed adding data');
}
});
}

First of all var_dump($this->input->post()) in your controller, if it shows post data then try replacing below code.
public function insert_surveilance(){
$request_params = $this->input->post('infectionType');
$data=array(
(more code)
'vap' => $request_params[0],
'hap' => $request_params[1],
'isk' => $request_params[2],
'iad' => $request_params[3],
(more code)
);
$data[]=
$insert = $this->surveilance_model->insert_surveilance($data);
echo json_encode(array("status"=>TRUE));
}

Related

How to pass JSON Array {{this.row}} to submit() function to get posted using Axios.post

this.row is Generating form input into JSON Array which I'm trying to post via submit function using Axios but unable to the value please help what's wrong ??
Axios postcode
axios.post('/submit', this.rows).then(response => {
this.rows; //Clear input fields.
this.loaded = true;
Here is my complete code
<template>
<form #submit.prevent="submit">
{{ /* These are 3 buttons which are calling 3 different function to create input boxes */ }}
<div class="d-flex mt-5"><div>
<label>Add A</label>
<button type="button" #click="addRow">01</button>
</div>
<div> <label>Add B</label>
<button type="button" #click="addRow1">02</button>
</div>
<div> <label>Add c</label>
<button type="button" #click="addRow3">03</button>
</div>
</div>
{{ /* this section calls button-counter template from script code */ }}
<div v-for="row in rows" :key="row.id">
<button-counter :name ="row.name" :id="row.id" :value.sync="row.value"></button-counter>
</div>
<div>
<button type="submit" class="btn btn-primary">Add Points</button>
</div>
<div v-if="success" class="alert alert-success mt-3">
Message sent!
</div>
</form>
</template>
<script>
Vue.component("button-counter", {
props: {
value: {
default: "",
}
},
/* This is my template which gets called fro the addition of new inputs ...guess here I need to add v-model so that dynamically generated fields will be posted but I'm unable to get it posted */
template: '<input class="form-control" id= id.row name=row.name type="number" style="margin-top: 10px;" :value="value" #change="$emit(\'update:value\', $event.target.value)">'
});
export default {
props: ['gameId','userId'],
mounted() {
console.log('Component mounted.')
},
data() {
return {
gamex: this.gameId,
rows: [],
count: 0,
fields: {},
errors: {},
success: false,
loaded: true,
};
},
computed: {
total() {
if (this.rows.length) {
return this.rows.reduce((acc, row) => acc += parseInt(row.value), 0);
}
return 0;
}
},
methods: {
addRow: function() {
var txtCount = 1;
let id = "txt_" + txtCount;
this.rows.push({ name:'zero',value:100, description: "textbox1", id });
},
addRow1: function() {
var txtCount = 1;
let id = "txt2_" + txtCount;
this.rows.push({name:'one',value:200, description: "textbox2", id });
},
addRow3: function() {
var txtCount = 1;
let id = "txt3_" + txtCount;
this.rows.push({name:'two',value:300, description: "textbox3", id });
},
submit: function() {
if (this.loaded) {
this.loaded = false;
this.success = false;
this.errors = {};
axios.post('/submit', this.rows).then(response => {
this.rows; //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 || {};
}
});
}
},
followUser() {
axios.post('/chklet/' + this.userId)
.then(response => {
return response.data ;
});
}
},
mounted () {
this.followUser();
}
};
</script>
You can use JSON.stringify(array_to_convert_in_string_to_send_in_ajax) but you will have to json_decode it also in backend server
In server section for example laravel:
$result = json_decode($request->your_array);

How to use Tuple in JavaScript MVC5?

I'm trying for example: when selecting from the first dropdown list "Kia brand" I want to view just "kia models" in the second dropdown list (not to view all cars models), but it does not work. This is the code in cshtml :
#model Tuple< Dalili_2018.Models.Car_Model ,Dalili_2018.Models.Car_Brand >
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_EmployeeLayout.cshtml";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Car</h4>
<hr />
<div class="form-group">
#if (ViewBag.CarBrandList != null)
{
#Html.DropDownListFor(Model => Model.Item2.ID, ViewBag.CarModelList
as SelectList, "---------", htmlAttributes: new { #class = "form-control" })
}
</div>
<div class="form-group">
#Html.DropDownListFor(Model => Model.Item1.ID, new SelectList(" "),
"---------", htmlAttributes: new { #class = "form-control" })
</div>
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function () {
$("#Item2.ID").change(function () {
$.get("/CarsController/GetModelCar", { ID_car_brand:
$("#Item2.ID").val() }, function (data) {
$("#item1.ID").empty();
$.each(data, function (Create, row) {
$("#item1.ID").append("<option value='" + row.ID
+ "'>" + row.ModelName + "</option>")
});
});
})
});
</script>
Controller code is:
public ActionResult Create()
{
List<Car_Model> CarBrandList = db.Car_Brand.ToList();
ViewBag.CarBrandList = new SelectList(CarBrandList, "ID",
"BrandName");
}
public JsonResult GetModelCar(int ID_car_brand)
{
db.Configuration.ProxyCreationEnabled = false;
List<Car_Model> CarModelList = db.Car_Model.Where(x =>
x.ID_car_brand == ID_car_brand).ToList();
return Json(CarModelList, JsonRequestBehavior.AllowGet);
}

How to use CodeIgniter Form Validation using AngularJS?

In my HTML :
<input type="text" ng-model="data.price" placeholder="Position" required/>
<button type="submit" ng-click="validate(data)">Save</button>
In my controllers.js :
$scope.validate = function(data){
$http.post(
'http://mysitename.com/folder/controller/method',
{
price: data.price
}
)
.success(function(res){
console.log(res);
})
.error(function(res){
console.log("Error: " + res);
});
}
In my Controller.php :
public function method() {
if($postdata = file_get_contents("php://input")) {
$this->form_validation->set_rules(??????, 'Price', 'required|is_money|trim');
if ($this->form_validation->run() == FALSE)
{
echo json_encode(validation_errors());
} else {
echo json_encode("working");
}
}
}
What should I put in my $this->form_validation->set_rules(??????, ' Price', 'required|is_money|trim'); ?
Any help is highly appreciated. Thanks :)

could not upload properly using ng-file-upload and laravel

I am trying to implement a feature so that the user will be able to upload a profile photo for our company page. I am using ng-file-upload plugin in angular: https://github.com/danialfarid/ng-file-upload
I followed one example in the documentation for uploading a photo:
function uploadPic ( file ) {
file.upload = Upload.upload( {
url: 'api/companyprofile/upload_logo',
method: 'POST',
sendFieldsAs: 'form',
headers: {
'my-header': 'my-header-value'
},
file: file,
fileFormDataName: 'myLogo.png'
} );
file.upload.then( function ( response ) {
$timeout( function () {
file.result = response.data;
} );
}, function ( response ) {
if ( response.status > 0 )
logger.error( response )
} );
file.upload.progress( function ( evt ) {
// Math.min is to fix IE which reports 200% sometimes
file.progress = Math.min( 100, parseInt( 100.0 * evt.loaded / evt.total ) );
} );
}
and this is it's html
<form name="myForm" enctype="multipart/form-data">
<fieldset>
<legend>Upload on form submit</legend>
<br>Photo:
<input type="file" ngf-select ng-model="picFile" name="cp_logo" accept="image/*" ngf-max-size="2MB" required>
<i ng-show="myForm.file.$error.required">*required</i>
<br>
<i ng-show="myForm.file.$error.maxSize">File too large
{{picFile.size / 1000000|number:1}}MB: max {{picFile.$errorParam}}</i>
<img ng-show="myForm.file.$valid" ngf-src="!picFile.$error && picFile" class="thumb">
<br>
<button ng-click="vm.uploadPic(picFile)">Submit</button>
<span class="progress" ng-show="picFile.progress >= 0">
<div style="width:{{picFile.progress}}%"
ng-bind="picFile.progress + '%'"></div>
</span>
<span ng-show="picFile.result">Upload Successful</span>
<span class="err" ng-show="errorMsg">{{errorMsg}}</span>
</fieldset>
<br>
</form>
The problem is that I get a status code of 200 telling me that it had uploaded the photo successfully but in reality it did not. Giving me an empty response. What am I doing wrong?
Disclaimer: I don't know php but this is the backend code from our backend developer. This might help
/**
* Upload a Company Logo (Synchronous).
* #route GET - prefix/companyprofile/upload_logo
*
* #return json
*/
public function uploadLogo()
{
// get the company profile object
$cProfile = CompanyProfile::first();
// get all inputs from the form
$input = Input::all();
// needs validation
$validator = Validator::make(Input::all(), ['cp_logo' => 'image|max:'.$this->max_filesize]);
if ($validator->fails()) {
return array('error' => $validator->messages());
}
// if there is a cp_logo store in $file variable
if($file = array_get($input,'cp_logo')) {
// delete old company logo
$this->deleteOldCompanyLogo($cProfile);
// concatenate the filename and extension
$input['filename'] = $this->generateFileName($file);
// save the company logo filename in the database
$this->saveCompanyLogo($cProfile, $input['filename']);
try {
// upload the files to the file server
Storage::disk(env('FILE_STORAGE'))->put($input['filename'], File::get($file));
return response()->json(['status' => 'Upload successful', 'filename' => $input['filename']]);
} catch(\Exception $e) {
return response()->json(['error' => $e->getMessage()], 400);
}
}
}
your backend expecting input named "cp_logo"
function uploadPic(file) {
if (!file || file.$error) {
logger.error(file);
return;
}
file.upload = Upload.upload({
url: 'api/companyprofile/upload_logo',
method: 'POST',
sendFieldsAs: 'form',
headers: {
'my-header': 'my-header-value'
},
file: file,
fileFormDataName: 'cp_logo' //<-- here is your POST data key send to server
});
and since in your html input named "cp_logo"
<input type="file" ngf-select ng-model="picFile" name="cp_logo" accept="image/*" ngf-max-size="2MB" required>
your validation expression should be.. myForm.cp_logo.$error or myForm.cp_logo.$valid
also double check upload input before send
HTML
<img ng-show="myForm.cp_logo.$valid" ngf-src="!picFile.$error && picFile" class="thumb">
<br>
<button ng-click="vm.uploadPic(picFile)" ng-disabled="!myForm.$valid" >Submit</button>
^ if this button is disabled obviously something wrong with inputs
BTW: the backend could return a status 200 (OK) when validation failed
you could check json response
file.upload.then(function(response) {
$timeout(function() {
logger.log(response.data);
if(response.data.error){
//something went wrong?
}
file.result = response.data;
});
}, function(response) {
if (response.status > 0)
logger.error(response)
});

Laravel blade: How do you delete prepoulated form field data (save in db as null)

I'm building some forms where fields are populated with database data or defaults to Placeholder text if there is no data.
What I can't seem to figure out is: When a user deletes all data in form it wont save it back to the database as blank/null, it just carried the same value in the field...
Input:
<div class="form-group #if($errors->has('username')){{ 'has-error' }}#endif">
<div class="col-md-6">
<label for="username">Username</label>
#if($errors->has('username'))<span class="label-has-error">{{ $errors->first('username') }}</span>#endif
<input type="text" name="username" class="form-control" tabindex="1" #if($info->username) value="{{ e($info->username) }}" #else placeholder="Username" #endif>
</div>
</div>
Controller:
public function postSettings() {
$validator = Validator::make(Input::all(),
array(
'username' => 'required_without_all:location,fullname|min:3',
'fullname' => 'required_without_all:location,username',
'location' => 'required_without_all:fullname,username'
)
);
if($validator->fails()) {
return Redirect::route('settings')->withErrors($validator);
} else {
$user = User::find(Auth::user()->id);
if(Input::get('username')) {
$user->username = Input::get('username');
}
if(Input::get('fullname')) {
$user->fullname = Input::get('fullname');
}
if(Input::get('location')) {
$user->location = Input::get('location');
}
$user->save();
Flash::success('Settings have been updated');
return Redirect::route('settings');
}
Flash::error('Update was unsecessful, please try again!');
return Redirect::route('settings');
}
Any ideas on how I can achieve this?
Thanks, Jack.
The problem are if statements.
You should try to change:
if(Input::get('username')) {
$user->username = Input::get('username');
}
if(Input::get('fullname')) {
$user->fullname = Input::get('fullname');
}
if(Input::get('location')) {
$user->location = Input::get('location');
}
into
$user->username = Input::get('username');
$user->fullname = Input::get('fullname');
$user->location = Input::get('location');
Now if those inputs are empty if statement will return false, so assignment won't be done and finally you save into database exactly you got from it.

Resources