Insert array using codeigniter - arrays

I try to insert multiple arrays into database using codeigniter and ajax. After click the submit, database insert to mysql but all the value is blank. What did I miss?
My view:
<input type="hidden" name="iduser[]" id="iduser[]" value="<?php echo $rowmyuser->iduser; ?>"/>
<input type="hidden" name="idproduk[]" id="idproduk[]" value="<?php echo $rowproduk->idproduct; ?>"/>
<input type="text" class="form-control input-sm" name="settarget[]" id="settarget[]"/>
Save
My controller:
public function inserttarget()
{
$this->target_m->inserttarget_m();
}
My model:
function inserttarget_m() {
$iduser = $this->input->post("iduser");
$idproduk = $this->input->post("idproduk");
$settarget = $this->input->post("settarget");
$temp = count($this->input->post("iduser"));
$datatarget = array();
for($i=0; $i < 3; $i++)
{
$datatarget[]=array(
"iduser"=>$iduser[$i],
"idproduct"=>$idproduk[$i],
"target"=>$settarget[$i],
);
}
$this->db->insert_batch("tbl_targetsales",$datatarget);
}
The Ajax code:
function insert_target()
{
var DataString=$("#frm_target").serialize();
document.getElementById("save_target").innerHTML = "<i class='fa fa-cog fa-spin fa-lg fa-fw'></i> Saving...";
$.ajax({
type: 'POST',
url: '<?php echo base_url();?>target/inserttarget',
data: DataString,
success: function (data) {
//jQuery("#attendence_report_holder").html(response);
swal({
text: 'success'
});
$("#frm_target")[0].reset();
document.getElementById("save_target").innerHTML = "<i class='fa fa-save'> </i>Save";
window.location='<?php echo base_url(); ?>target';
},
error:function(data){
swal({
text: 'error',
});
document.getElementById("save_target").innerHTML = "<i class='fa fa-save'> </i>Save";
}
});
}
I need advice please, what is the problem in the code. Thanks in advance

first you call wrong the inputs in your html for the inputs name are
iduser[]
idproduk[]
settarget[]
and in your model you call with, and in the array you make to insert you call different variables that you save it
iduser
idproduct
target
replace all you madel with (using the correct names from form and variables names)
function inserttarget_m() {
$iduser = $this->input->post("iduser");
$idproduct = $this->input->post("idproduk");
$target = $this->input->post("settarget");
$temp = count($iduser);
$datatarget = array();
for($i=0; $i < $temp; $i++){
$datatarget[] = array(
"iduser" => $iduser[$i],
"idproduct" => $idproduct[$i],
"target" => $target[$i],
);
}
$this->db->insert_batch("tbl_targetsales", $datatarget);
}

Related

How to get checkbox checked from database array using Laravel and Ajax

I'm trying to get data from database to checkboxes as checked. The checkbox data in database are as array that have been inserted with json and they are dynamic data based on insert function.
My tasks table:
id |employee_id | startDate | endDate | ...
---|------------|------------|-----------|--------
1 |["1","2"] | .......... | ..........| ....
My TasksController.php
function fetchdata(Request $request)
{
$id = $request->input('id');
$task = Task::find($id);
$output = array(
'employee_id' => $task->employee_id,
'name' => $task->name,
'description' => $task->description,
'startDate' => $task->startDate,
'endDate' => $task->endDate,
'percentage' => $task->percentage
);
echo json_encode($output);
}
public function getEmployeesList()
{
$employeesList = Employee::all();
return view('adminlte::tasks', ['employeesList' => $employeesList]);
}
My tasks.blade.php
#foreach($employeesList as $emplist)
<label class="checkbox-inline">
<input type="checkbox" id="employee_id" name="employee_id[]" class="chck" value="{{$emplist->id}}" >{{ $emplist->name }}</label>
#endforeach
My Ajax function inside blade:
$(document).on('click', '.edit', function(){
var id = $(this).attr("id");
$('#form_output').html('');
$.ajax({
url: "{{route('tasks.fetchdata')}}",
method: 'get',
data: {id:id},
dataType: 'json',
success:function(data)
{
$('#id').val(data.id);
$('#employee_id').val(data.employee_id);
$('#name').val(data.name);
.......................
..................
}
})
});
So, how can I retrieve data from database to checkboxes as checked, because for now I'm getting null "employee_id" value when I try to update a record.
Thank you in advance
Since you're encoding the data on the server side, you must decode it in the client side like :
...
success:function(data)
{
console.log( data );
data = JSON.parse(data);
$('#id').val(data.id);
$('#employee_id').val(data.employee_id);
$('#name').val(data.name);
...
}

Codeigniter Checkbox

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

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