Angular - post a comment to database - angularjs

I am trying post a comment from an input form to my database. The comment I am passing in currently logs as undefined. The service doesn't log and I get a 500 server error: user_id violates not null constraint. What am I doing incorrectly?
HTML(updated)
<div ng-controller="CommentsCtrl as commentsCtrl">
<div ng-show="makeComment" class="collapsible-header">
<input ng-model="comment" type="text" name="comment" id="comment_content" class="col s11 m11 l11" placeholder="Make a comment.">
<i class="material-icons">check_circle</i>
</div>
Controller - CommentsCtrl(Updated)
this.comment = '';
createComment(comment, userId, postId) {
return this.commentsService.createComment(comment, userId, postId);
}
}
Service - CommentsService(Updated)
this.createcomment = $http;
this.commentContent = '';
this.postId;
this.userId;
createComment(comment, userId, postId) {
this.createcomment.post('/comments', { comment: this.commentContent, userId: this.userId, postId: this.postId })
.then((res) => {
this.comment = res.data;
})
.catch((err) => {
return err;
});
}

You are not passing any values for userId or postId:
this.commentsService.createComment(comment);
They are null.

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

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

I push an object to my Array in mongoose, array only stores its length

I try to push an object into an Array in mongoose, but whenever i do it, it puts its length like this(mongoose, the attribute is schoolComment at the bottom), I am using mlab.com for database.
{
"_id": {
"$oid": "58e17ee3e24dfb1f70d76460"
},
"schoolName": "Koc Universitesi",
"schoolIlce": "Sariyer",
"schoolSehir": "Istanbul",
"schoolId": 981299,
"__v": 5,
"schoolComments": [
3
]
}
this is my code in node JS (The comments are not appearing in html because of this reason)
app.post('/comment', function(req, res){
if(req.session.user && req.session){
User.findOne({email: req.session.user.email}, function(err, user){
if(err) {
res.send('error');
}
if(user){
if(req.session.user.password === user.password){
var thisID = user.userid;
Universite.findOne({schoolName: req.body.collegeName}, function(err, college){
if(err) res.send('error');
if(college){
college.set({schoolComments: college.schoolComments.push({thisID: req.body.comment})}).save(function(err){
if(err){
res.render('errors', {error:'Error'});
}else{
res.locals.college = college;
res.locals.user = user;
res.render('universiteinfoUser');
}
});
}
});
}else{
res.render('login', {});
}
}
});
}
});
and this is HTML DOM Form for it. The comments are not appearing because of this reasons.
<form onkeypress="enterPress();" action="/comment" method="post">
<textarea maxlength="100" style="font-size: 25px;" name="comment" rows="3" cols="50" placeholder="Yorumunuzu yazin..."></textarea><br>
<input style="display: none; visibility: hidden;" type="text" name="collegeName" value="<%=college.schoolName%>"></input>
<button type="submit" name="commentSubmit">Comment Submit</button>
</form>
<div class="userCommentDisplay">
<ul>
<%college.schoolComments.forEach(function(item, i){%>
<%var k = college.schoolComments[i]%>
<%for(key in k){%>
<%if(key === user.userid){%>
<li><%=k[key]%> Same</li>
<%}else{%>
<li><%=k[key]%></li>
<%}%>
<%}%>
<%})%>
</ul>
</div>
You may want to use findOneAndUpdate and build your comment item dynamically (to set the dynamic field name) :
var item = {};
item[user.userid] = req.body.comment;
Universite.findOneAndUpdate({
schoolName: req.body.collegeName
}, {
$push: {
"schoolComments": item
}
}, { new: true }, function(err, college) {
if (err) {
res.render('errors', { error: 'Error' });
} else {
res.locals.college = college;
res.locals.user = user;
res.render('universiteinfoUser');
}
});
Note that I've aded { new: true } in order to return the modified document college instead of the unaltered one.
FYI, in your code, you have used JS method Array.prototype.push() that will return the new length of the array by using college.schoolComments.push

manipulate data fetched from remote api angular 2

Im receiving data from the Marvel api and use ngFor to display the data.
Before displaying the data I need to make some changes to it.
If the name doesn't exist or the description is empty I want to show a message.
Where is the best place to manipulate data and how can I do this?
I tried something like this in my comic view after the subscribe but it didnt work.
If (stuff.data.results['0'].title == ''){
stuff.data.results['0'].title == 'try gain'}
my service.ts
getComics(searchterm): Observable<any> {
const search: URLSearchParams = new URLSearchParams();
search.set('titleStartsWith',searchterm);
search.set('ts', '1'); // time stamp
search.set('apikey', 'key');
search.set('hash', 'key');
let obs: Observable<any> = this.http
.get(ComicService.BASE_URL, new RequestOptions({search}))
.map( (res) => res.json());
console.log("obj " + obs)
return obs;
}
my comic-view.ts
searchComics(event): boolean {
this.error = 'fout'
this._comicService.getComics(this.searchterm)
.subscribe(
stuff => {
this.stuff = stuff; console.log('title: ' + stuff.data.results['0'].title + ' description:' +
stuff.data.results['0'].description);
},
error => { this.error = error; }
);
return false;
}
comis.html
<ul>
<li *ngFor=" let x of stuff?.data?.results ">
<label> Title:</label> {{x.title}}
<br>
<label> description: </label> {{x.description}}
<br>
</li>
</ul>

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

Resources