Ajax status 0, success not firing, no info with the errors thrown - node.js

I'm working on an app where the user enters info into a form, the form passes the info to my route, the route passes the info to the db, and then when done, it's supposed to update the page accordingly.
The issues I am having is that when you hit submit, the info does land on the database and gets saved but then on the callback/success/complete part of ajax, they dont fire and you have to hit a manual reload for the info to show up. I'm going to assume that this is because of the readystate of 0.
I've tried many solutions other people here on SO have gotten but to no avail.
Here is my code.
HTML:
<div id="createTodoFormW">
<form method="post" id="createTodoForm">
<input type="text" name="todoCompanyName" id="todoCompanyName" placeholder="Enter a Company name or leave empty if its a personal ToDo "><br>
<input type="text" name="todoTitle" id="todoTitle" placeholder="Enter a Title for this note"><br>
<input type="text" name="todoIsFor" id="todoIsFor" placeholder="Who is this ToDo for? ( If left empty, ToDo will be assigned to [ YOU ] )"><br>
<input type="hidden" name="todoPostedBy" id="todoPostedBy" value="LOGGED IN USER HERE">
<input type="hidden" name="todoCompleted" id="todoCompleted" value="no">
<input type="text" name="todoFirstMessage" id="todoFirstMessage" placeholder="Enter your ToDo message"><br>
<select name="todoPriority" id="todoPriority">
<option id="todoPriorityDefaultSelected" >Please select your ToDo priority</option>
<option id="todoPrioritySelected" selected>green</option>
<option id="todoPrioritySelected">yellow</option>
<option id="todoPrioritySelected">red</option>
</select><br>
<input type="submit">
</form>
</div><!-- createTodoFormW ender -->
express/node route:
app.post("/notesapi", (request, response) =>{
//mongoose.connect(databaseLoc);
const newNoteToAdd = new NotesModel({
todoCompany : request.body.todoCompany,
todoIsFor : request.body.todoIsFor,
todoPostedBy : request.body.todoPostedBy,
todoCompleted : request.body.todoCompleted,
todoPriority : request.body.todoPriority,
todoMessages : request.body.todoMessages,
todoTitle : request.body.todoTitle,
todoDate : currDate
});
newNoteToAdd.save((err, data)=>{
if(err){
console.log("There was an error uploading your data " + err);
}else{
//mongoose.connection.close();
console.log("Data upload success.");
}
});
});
front end js:
$("#createTodoForm").submit(function(evt){
evt.preventDefault();
$.ajax({
type : "POST",
cache : false,
dataType : "json",
contentType : "application/json; charset=utf-8",
url : "/notesapi",
data : JSON.stringify({
todoCompany : $("#todoCompanyName").val(),
todoTitle : $("#todoTitle").val(),
todoPostedBy : $("#todoPostedBy").val(),
todoIsFor : $("#todoIsFor").val(),
todoMessages : $("#todoFirstMessage").val(),
todoPriority : $("#todoPriority").val(),
todoCompleted : false
}),
success : function(){
console.log("did ajax fire and comlete?");
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
if (XMLHttpRequest.readyState == 4) {
console.log("HTTP error (can be checked by XMLHttpRequest.status and XMLHttpRequest.statusText");
}
else if (XMLHttpRequest.readyState == 0) {
console.log("Network error (i.e. connection refused, access denied due to CORS, etc.");
console.log(textStatus);
console.log(errorThrown)
console.log(XMLHttpRequest.readyState);
}
else {
console.log("something weird is happening");
}
}
}); //ajax end
});
I need help. Been on this for days and cant figure it out. The main question i guess is, where is this state coming from and why doesnt my success function run?
thanks in advance for any assistance given.

Related

Search Data not working Angular NodeJS API

i am created the search part using angular and node js. i have tested through the postman it is working fine. when connect with frond end anqular application is it not working error displayed
Failed to load resource: the server responded with a status of 404 (Not Found)
what i tried so far i attached below please check.
i tried on the url http://localhost:9001/user/findOne?first_name=kobinath
this is working well on postman but tested through the anqular didn't work. i attached the code what i tried so far.
employee.component.ts
search()
{
let name= {
"first_name" : this.first_name
};
this.http.post("http://localhost:9001/user/findOne",name).subscribe((resultData: any)=>
{
console.log(resultData);
});
}
employee.component.html
<form>
<div class="form-group">
<label>First Name</label>
<input type="text" [(ngModel)]="first_name" [ngModelOptions]="{standalone: true}" class="form-control" id="name" placeholder="Enter Name">
</div>
<button type="submit" class="btn btn-primary mt-4" (click)="search()" >Search</button>
</form>
</div>
What I noticed: With Postman you send first_name as a query parameter, but in your Angular-code you attach it to the request-body.
To achieve the equivalent of what you do in Postman, you could use the following code:
search(firstName: string) {
const params = new HttpParams().set('first_name', firstName);
const body = {
first_name : firstName
};
this.http.post("http://localhost:9001/user/findOne", body, { params: params })
.subscribe((resultData: any)=>
{
console.log(resultData);
});
}
Btw: Why don't you use GET instead of POST?

MeanStack: conflict on editing feature'_id' would modify the immutable field '_id'

I've seen solutions in this post and in others, but I did follow the instructions and I'm still getting the error. I understand all the logic, id's can't be replaced, they are immutable, but in my mean stack app, the error persists. The code:
Node route
router.put("/:id" ,(req, res, next) => {
const note = new Note({
_id:req.body.id,
project: req.body.project,
note: req.body.note,
date:req.body.date,
});
Note.updateOne({ _id: req.params.id }, note).then(result => {
console.log(result)
res.status(200).json({ message: "Update successful!" });
});
});
Front End edit component:
ngOnInit(): void {
this.notesForm=this.fb.group({
note:['', Validators.required],
project:['', Validators.required],
date:[null,Validators.required]
})
this.route.paramMap.subscribe((paraMap:ParamMap)=>{
if(paraMap.has('noteId')){
this.mode='edit';
this.noteId= paraMap.get('noteId');
this.note=this.notePadService.getNote(this.noteId)
.subscribe(noteData=>{
this.note = {id: noteData._id, note: noteData.note, date: noteData.date, project: noteData.project};
})
}else{
this.mode='create';
this.noteId=null;
}
})
this.getProjects();
}
onSubmit(){
if(this.mode==='create'){
this.notePadService.submitNotes(this.notesForm.value)
console.log(this.notesForm.value);
this.router.navigate(['/notes-listing'])
}else{
this.notePadService.updateNote(
this.noteId,this.notesForm.value
)
}
}
Service:
getNote(id:string){
return this.http.get<any>('http://localhost:3000/api/notes/'+id)
}
updateNote(id:string,note:Notes){
this.http.put('http://localhost:3000/api/notes/'+id,note)
.subscribe(response=>console.log(response))
}
Also I cant pre-populate the reactive form with the values to edit:
<label>Select a Project</label>
<select (change)="test($event.target.value)" formControlName="project"
class="form-control">
<option
*ngFor="let p of projects"
[value]="p.name">{{ p.name }}</option>
</select>
<!------->
<label for="notes">Note</label>
<textarea class="form-control" formControlName="note" type="text" rows="4"></textarea>
<div class="input-group">
<mat-form-field appearance="fill">
<mat-label>Choose a date</mat-label>
<input formControlName="date" matInput [matDatepicker]="picker">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>
</div>
<button mat-raised-button color="warn">Submit</button>
</form>
When I click the edit button (in another component), I get the correct URL but no values, and onsubmit, the backend crashes:
http://localhost:4200/edit/601ec21882fa6af20b454a8d
Can someone help me out? I'm very confused and I cant understand the error since I've done everything the other posts suggest...
when you call updateOne you already pass as the first argument the id that should be updated. As second argument you pass note that should contain only the properties that will be updated, but not _id itself:
const note = {
project: req.body.project,
note: req.body.note,
date:req.body.date,
};

Angular : [Object Object]

I'm working on a NodeJS/Angular project and while trying to do a simple CRUD, I'm blocked when I try to get an element by ID.
I would like to retrieve all the info of a "Member" based on its ID and display the info in a table. I manage to get my JSON with the API call but when trying to display it in the table, it doesn't show anything.
My service, with the API call :
public getMember(id: number) {
return new Promise((resolve, reject) => {
this.http.get(this.config.apiServer + `astreintes/member/get/${id}`)
.subscribe((res) => {
resolve(res as Member);
console.log(res);
}, err => {
reject(err);
});
});
}
Result of the console.log: My correct JSON with the info of the member
My component.ts :
public search(){
this.memberService.getMember(this.id).then((data) => {
if(data){
this.member = (data as any).recordset;
console.log("Get member :"+ data);
this.indice = true;
}else{
}},
(error) => {
console.log(error);
}
);
}
Result of the console.log: "Get member : [Object Object]"
For the interface, I just have a dropdown list of all my members, and when I select one and click on the button "Search", it gets the info of my member correctly in the console. Then, I want to display it in my table below. My html code:
<form (submit)='search()' #searchMemberForm="ngForm" class="form-horizontal">
<select [(ngModel)]="id" name="member">
<option *ngFor="let member of membersList"
[value]="member.Id_OnCall_Member">{{member.Oncall_Member_Name}}</option>
</select>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-save btn-primary">Search</button>
</div>
</div>
</form>
<div *ngIf="indice">
<h1 style="text-align: center">
Informations
</h1>
<table class="table table-striped" *ngIf="indice">
<th>ID</th>
<th>Nom</th>
<th>Numéro de téléphone</th>
<th>Statut d'activité</th>
<tr *ngFor="let m of member">
<td>{{m.Id_OnCall_Member}}</td>
<td>{{m.Oncall_Member_Name}}</td>
<td>{{m.OnCall_Member_Phone}}</td>
<td>{{m.OnCall_Member_Status}}</td>
</tr>
</table>
</div>
Thanks for your help !
you used "+" in console.log: console.log("Get member :"+ data);
it means javascript is trying to convert the output to one type (string), but data is object. Below you can find how to get the correct output.
const res = {
memberId: 1
}
console.log(res) // {memberId: 1}
console.log('Member: '+ res); //Member: [object Object]
console.log('Member: ', res); // Member: {memberId: 1}
console.log('Member: '+ JSON.stringify(res)); // Member: {memberId: 1}
thanks for your answers.
My problem wasn't the console.log though, it was just an indication.
My real problem was that it didn't show anything in my table. But I solved it, here's how in case it might help other people.
In my component.ts, I replaced:
this.member = (data as any).recordset;
By this, simply:
this.member = data;

how make checkbox stay checked and reset in node js

I am working on a small project with checkbox and node js. I need the checked box stay on the screen after I click submit button and reset the form after clicking reset button.How can do that?
ejs code
<form method="post" action="/">
<input type="checkbox" name="preference" value="A">A
<input type="checkbox" name="preference" value="B">B
<input type="checkbox" name="preference" value="C">C
<input type="submit" value="Click to Submit">
<input type="reset" value="Erase and Restart">
</form>
node js
express.get('/', (req, res) => {
res.render('form');
});
express.post('/', (req, res) => {
console.log(req.body);
let checkedValue =req.body.preference;
let output = checkedValue==undefined?`You didn' make selection.`:`The preference iterm on menu is ${checkedValue}`;
res.render('form',{
output:output,
});
});
What's going on is that when you submit your form, the webpage is reloaded, so you lose your checked state. You can either save the values on your server and have them pre-checked using an optional checked flag in your ejs template or you can add some client side javascript to handle the form submission for you by writing and event handler for the submit event on the form.
if you expand your ejs template with a conditional checked value on your inputs, your returned page will have them pre-checked
<input type="checkbox" name="preference" <% if (submittedValue === "A") { %>checked<% } %> value="A">A
Or, here's a super simple bit of javascript that would send the values to your server
document.forms[0].addEventListener('submit', function (e) {
e.preventDefault(); // prevent the form from submitting with a page refresh
const data = { values: [] };
e.target.elements.forEach((formEl) => {
if (formEl.checked) data.values.push(formEl.value);
});
fetch('/urlToProcessYourForm', { method: 'POST', body: JSON.stringify(data) });
});

Upload image to database using angular

I got stuck while uploading updating user avatar on my website. I'm using angular and need to upload image using form and get base64 encoding of this image to pass as a parameter into my backend.
onUploadFinished(event){
const avatar ={
avatar:event.file
}
console.log(avatar)
//validate avatar
if(!this.validateService.validateAvatarUpdate(avatar.avatar)){
this.flashMessage.show('Please, select a new avatar', {cssClass: 'alert-danger', timeout:3000});
return false;
}
this.updateService.updateAvatar(avatar).subscribe(data=>{
console.log()
if(data/*.success*/){ //commented cause response doesnt have property success but still registering user without displaying the flash message
this.flashMessage.show('You successfuly changed your avatar', {cssClass: 'alert-success', timeout:3000});
this.router.navigate(['/profile'])
this.authService.getProfile().subscribe(profile=>{
this.user = profile.user;
},
err=>{
console.log(err);
return false;
});
}else{
this.flashMessage.show('Something went wrong', {cssClass: 'alert-danger', timeout:3000});
this.router.navigate(['/profile'])
}
});
}
I was trying to use ng2-image-upload here is html
<h6>Upload new photo...</h6>
<!-- <form (submit)="onUserAvatarSubmit()" enctype="multipart/form-data">
<input type="file" name="avatar" class="text-center center-block well well-sm">
<p></p>
<input class="btn btn-primary" value="Upload" type="submit">
</form> -->
<image-upload name="avatar" [class]="'customClass'"
[headers]="{Authorization: this.authToken}"
[buttonCaption]="'Choose an Image'"
[dropBoxMessage]="'or just drop them here'"
(uploadFinished)="onUploadFinished($event)"
[url]="''">
</image-upload>
Maybe anyone had such experience with uploading images, so give me some tips how to deal with it. Thanks here is a screenshot So you see when displaying this image we can see its base64 but I cant take it.

Resources