When we pass the Object using fetch api in Fakeapi , obj doesn't add in 101 id - fetch-api

I am a trying to pass the object using fetch api in JsonPacehoder Post api and print the value of then method but then methods returns blank object . this object only carry id not holdes my values. so i am dont understand what kind of problem in this code please help me....
<body>
<h1>i am a heading</h1>
<input type="text" id="title" title="title" >
<input type="text" id="body">
<input type="text" id="userId">
<button onclick="myFunction()">ok</button>
<script>
async function myFunction(){
let title_Value = document.getElementById("title").value;
let body_Value = document.getElementById("body").value;
let userId_Value = document.getElementById("userId").value;
let obj = {
title: "title_Value",
body: "body_Value",
userId: "userId_Value",
}
await fetch('https://jsonplaceholder.typicode.com/posts' ,
{
method: "POST",
body : JSON.stringify(obj),
headers: {
'Accept': 'application/json',
"contentType" : "application/json; charset=UTF-8",
},
})
.then((resolve)=> resolve.json())
.then((result)=> console.log(result))
}
Here the output
>{id: 101}
id: 101
>[[Prototype]]: Object

Related

Vue.js: How to fill a form prepopulated with data from a get request?

I want to load data with a GET request and fill the data to the input data attributes at vue.js 3 like
<input id="name" type="text" v-bind:placeholder="$t('message.NamePlaceholder')" value="{{ name }}" required>
and this is my script part
<script>
export default {
data () {
return {
userInformation: {},
name: "",
}
},
mounted () {
this.getUserInformation();
},
methods () {
getUserInformation() {
this.$axios({
method: 'get',
url: 'http://127.0.0.1:8000/api/get_user_information',
}).then(response => {this.userInformation = response.data});
this.name = this.userInformation.Name;
}
},
}
But the input field contains only {{ name }}. I tried also v-bind:value, but this didn't solve the problem.
Whenever you need to bind values to attributes {{}} are unnecessary. You can just write v-bind:value="name" or :value="name"
E.g.:
<input id="name" type="text" :placeholder="message.NamePlaceholder" :value="name" required></input>
The mistake was that I have to set the variable this.name at the axios command:
this.$axios({
method: 'get',
url: 'http://127.0.0.1:8000/api/get_user_information',
}).then(response => {
this.userInformation = response.data;
this.name = this.userInformation.Name;
});

How to create folders on SharePoint 2019 using REST calls via postman? Getting 403: Forbidden error

I am using the below call to create a folder on SharePoint2019:
POST http://<site>/_api/web/folders
{
"__metadata": {
"type": "SP.Folder"
},
"ServerRelativeUrl": "/Shared Documents/Folder"
}
But I am getting the following error:
403 Forbidden: The security validation for this page is invalid and might be corrupted. Please use your web browser's Back button to try your operation again.
Please check if you have got the valid form digest value in your side.
For example, if the site url is http://sp/sites/dev/
Then do a Post Request to this url http://sp/sites/dev/_api/contextinfo
Then use this form digest value in Request Header:
Here is a sample request to create folder using Rest:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(function () {
bindButtonClick();
});
function bindButtonClick() {
$("#btnSubmit").on("click", function () {
createFolder();
});
}
function createFolder() {
var folderName = $("#txtFolderName").val();
var siteUrl = _spPageContextInfo.webAbsoluteUrl;
var fullUrl = siteUrl + "/_api/web/folders";
$.ajax({
url: fullUrl,
type: "POST",
data: JSON.stringify({
'__metadata': { 'type': 'SP.Folder' },
'ServerRelativeUrl': 'Shared Documents/' + folderName
}),
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: onQuerySucceeded,
error: onQueryFailed
});
}
function onQuerySucceeded() {
$("#divResults").html("Folder created successfully !!!");
}
function onQueryFailed() {
alert('Error!');
}
</script>
<div>
<strong>Enter FolderName:</strong><br />
<input type="text" id="txtFolderName" /><br />
<input type="button" id="btnSubmit" value="Create Folder" />
</div>
<div id="divResults"></div>
Reference:
Some Help for Authorization Problems in SharePoint 2013 REST API

How to get all survey answer by current user with REST Api Sharepoint?

In sharepoint survey API:
Get all question: https://site/_api/Web/Lists/getByTitle('Survey')/fields?$filter=(CanBeDeleted eq true)
Get all answer: https://site/_api/Web/Lists/getByTitle('Recognition%20Awards%202019')/items
Get all answer by current user login: ???
Please help me.
We can use _spPageContextInfo.userId to get the current login user Id, then using $filter=AuthorId eq UserId to get all the answer by current user login.
<script src="https://code.jquery.com/jquery-1.12.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
function getItems() {
var listTitle="Recognition Awards 2019";
var currentUserId=_spPageContextInfo.userId;
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('"+listTitle+"')/items?$filter=AuthorId eq "+currentUserId,
type: "GET",
headers: { "ACCEPT": "application/json;odata=verbose" },
success: function (data) {
//
},
error: function (err) {
//alert(err);
}
});
}
</script>
<input id="Button1" type="button" value="Get Items" onclick="getItems()" />

Angular 2 : How to make POST call using form

I am completely new to Angular 2 and form concept. I am trying to POST form data to a POST API call. like this
POST API : http://localohot:8080/**********
Component :
user: any = {
id: null,
gender: null,
mstatus: null,
birthdate: null,
bloodgroup: null
}
userName: any = {
id: null,
personId: null,
displayName: '',
prefix: null,
givenName: null
}
userAddressJSON: any = {
id: null,
personId: null,
address1: null,
address2: null,
cityVillage: null
}
var form = new FormData();
form.append('userid', new Blob(['' + uid], { type: 'application/json' }));
form.append('user', new Blob([JSON.stringify(this.user)], { type: 'application/json' }));
form.append('userName', new Blob([JSON.stringify(this.userName)], { type: 'application/json' }));
form.append('userAddress', new Blob([JSON.stringify(this.userAddressJSON)], { type: 'application/json' }));
Here, I don't know how to make API call.
In our old application they used form data POST in jQuery. Now I am trying to do the same in Angular 2. When I do the form POST in old application they are sending like this
------WebKitFormBoundarybAWvwmP2VtRxvKA7
Content - Disposition: form - data; name = "userid"; filename = "blob"
Content - Type: application / json
------WebKitFormBoundarybAWvwmP2VtRxvKA7
Content - Disposition: form - data; name = "user"; filename = "blob"
Content - Type: application / json
------WebKitFormBoundarybAWvwmP2VtRxvKA7
Content - Disposition: form - data; name = "userName"; filename = "blob"
Content - Type: application / json
------WebKitFormBoundarybAWvwmP2VtRxvKA7
Content - Disposition: form - data; name = "userAddress"; filename = "blob"
Content - Type: application / json
Can any one help me how to do that form POST in Angular 2.
Here is how I currently make a POST call in my Angular 2 app, because it sounds like you could use a simple example of how to setup a form. Here is the Angular 2 documentation on How to Send Data to the Server.
For even more high level documentation on making AJAX requests in Angular 2 visit this URL.
in my app/app.module.ts
...
import { HttpModule } from '#angular/http';
...
#NgModule({
imports: [
...
HttpModule
...
],
declarations: [
...
],
providers: [ ... ],
bootstrap: [AppComponent],
})
export class AppModule { }
app/system-setup/system-setup.ts
export class SystemSetup {
system_setup_id: number;
name: string;
counter: number;
}
app/form-component/form.component.html (Notice the [(ngModel)], that is what binds the property of the object to the html input element)
<form class="form" (ngSubmit)="saveEdits()" #editSystemSetupForm="ngForm">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="theName" name="name" [(ngModel)]="selectedItem.name" #itemsName="ngModel" required minlength="3"/>
<div [hidden]="itemsName.valid || itemsName.pristine" class="alert alert-danger">Name is required! Min length of 3.</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="">Counter</label>
<input type="number" step=0.01 class="form-control" name="counter" [(ngModel)]="selectedItem.counter" />
</div>
</div>
</div>
<div class="row">
<div class="col-md-4 col-md-offset-8">
<button type="submit" class="btn btn-success" style="float: right; margin-left: 15px;" [disabled]="!editISystemSetupForm.form.valid" >Save</button>
<button type="button" class="btn btn-danger" style="float: right;" (click)="cancelEdits()">Cancel</button>
</div>
</div>
</form>
in my app/form-component/form.component.ts
import { Component, OnInit, Input, Output, EventEmitter } from '#angular/core';
import { Headers, RequestOptions, Http, Response } from '#angular/http';
import { SystemSetup } from '../system-setup/system-setup';
#Component({
selector: 'app-setup-form',
templateUrl: 'setup-form.component.html',
styleUrls: ['setup-form.component.css']
})
export class SetupFormComponent implements OnInit {
#Input() selectedItem: SystemSetup; // The object to be edited
#Output() finishedEditing = new EventEmitter<number>(); // When the POST is done send to the parent component the new id
// Inject the Http service into our component
constructor(private _http: Http) { }
// User is finished editing POST the object to the server to be saved
saveEdits(): void {
let body = JSON.stringify( this.selectedItem );
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this._http.post('http://localhost:8080/**********', body, options)
.map(this.extractData)
.do(
data => {
this.finishedEditing.emit(data.system_setup_id); // Send the parent component the id if the selectedItem
})
.toPromise()
.catch(this.handleError);
}
/**
* Gets the data out of the package from the AJAX call.
* #param {Response} res - AJAX response
* #returns SystemSetup - A json of the returned data
*/
extractData(res: Response): SystemSetup {
let body = res.json();
if (body === 'failed') {
body = {};
}
return body || {};
}
/**
* Handles the AJAX error if the call failed or exited with exception. Print out the error message.
* #param {any} error - An error json object with data about the error on it
* #returns Promise - A promise with the error message in it
*/
private handleError(error: any): Promise<void> {
// In a real world app, we might use a remote logging infrastructure
// We'd also dig deeper into the error to get a better message
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Promise.reject(errMsg);
}
}
This URL is the link to the official Angular 2 documentation site, which is a very good reference for anything an Angular 2 developer could want.

Form OnClick ReferenceError: comment is not defined

I'm trying to update my comment system and have run in to a snag. This is the error firebug is showing : ReferenceError: comment is not defined : comment(1000);
I'm at a loss to what the issue is - any ideas?
<div class="comment_heading">Leave a Comment</div>
<div class="post_comment">
<textarea name="txtpostcomment" id="txtpostcomment-1000" class="txtpostcomment"></textarea>
<button class="btnpostcomment" id="btnpostcomment-1000" onclick="comment(1000);" type="button">Send</button>
<input type="hidden" name="token" id="token" value="19vtyWh5iOpeKamXAQl3udqU9mMjnfKv/LnWr70M2jE=">
</div>
<script>
function comment(postid1)
{
var txt = $('#txtpostcomment-'+postid1);
var btn = $('#btnpostcomment-'+postid1);
var comment1 = $(txt).val();
var token = $("#token").val();
$(btn).css('background-image', 'url(/comments/submit-busy.gif)');
$(btn).attr('disabled', true);
var dataString = 'commenting=1&postid=' + postid1 + '&comment=' + comment1 + '&name=' + name + '&token=' + token;
.ajax({
url: "/comments/submit.php",
type: "POST",
data: dataString,
cache: false,
success: function()
{
$('.post_comment .error_msg').remove();
$('.comment-list-'+postid1).prepend(msg.html);
$(txt).val('');
},
error: function()
{
$('.post_comment .error_msg').value = 'Error - Please try again';
}
});
$(btn).css('background-image', 'none');
$(btn).attr('disabled', false);
$(txt).attr('disabled', false);
}
</script>
Solved .. all I needed to change was :
.ajax({
To :
$.ajax({