How to create post using WordPress REST API - javascript

I have created small webpage, I want to create post using WordPress rest api, but I send data but this error displayed How do I pass data could you please check and update.
post.html:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
var ourPostData = {
"title" : "siva",
"content" : "Hi this welcome",
"status": "publish",
'excerpt': 'Read this awesome post',
'password': 'siva',
'slug':'new-test-post'
};
alert(JSON.stringify(ourPostData))
$.ajax({
type:"POST",
url:"http://127.0.0.1/wordpress/wp-json/wp/v2/posts",
data:JSON.stringify(ourPostData),
dataType:"json",
username: "siva",
password: "siva",
headers: {
"Authorization": "Basic " + btoa(username + ":" + password)
},
contentType:"Application/json",
success:function(callback){
console.log(callback)
}
});
});
</script>
</head>
<body>
</body>
</html>

Related

I didn't get required input and output on Azure Cognitive services

Code
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
var params = {
// Request parameters
};
$.ajax({
url: "https://westus.api.cognitive.microsoft.com/linguistics/v1.0/analyzers?" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","fa5a4445a080414d95610f74fa3e5626");
},
type: "GET",
// Request body
data: "{body}",
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>
Documentation Help
https://westus.dev.cognitive.microsoft.com/docs/services/56ea598f778daf01942505ff/operations/56ea59bfca73071fd4b102ba
input json is below
{ "language" : "en", "analyzerIds" : ["4fa79af1-f22c-408d-98bb-b7d7aeef7f04", "22a6b758-420f-4745-8a3c-46835a67c0d2"], "text" : "Hi, Tom! How are you today?" }
required output is below json
[
{
"analyzerId" : "4fa79af1-f22c-408d-98bb-b7d7aeef7f04",
"result" : ["NNP",",","NNP","VBP","PRP","NN","."]
},
{
"analyzerId" : "22a6b758-420f-4745-8a3c-46835a67c0d2",
"result" : ["(TOP (S (NNP Hi) (, ,) (NNP Tom) (. !)))","(TOP (SBARQ (WHADVP (WRB How)) (SQ (VP (VBP are)) (NP (PRP you)) (NN today) (. ?))))"]
}
]
Looks like you're mixing up the 'List Analyzers' and 'Analyze Text' calls. Your input/output combination suggests you want the latter. If so, the code should be roughly as follows:
var request = {
"language": "en",
"analyzerIds": [
"4fa79af1-f22c-408d-98bb-b7d7aeef7f04",
"22a6b758-420f-4745-8a3c-46835a67c0d2"
],
"text": "Hi, Tom! How are you today?"
}
$.ajax({
url: "https://westus.api.cognitive.microsoft.com/linguistics/v1.0/analyze?" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","fa5a4445a080414d95610f74fa3e5626");
},
type: "POST",
// Request body
data: JSON.stringify(request),
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
The four differences are:
The URL is /analyze, not /analyzers
The type is POST, not GET
The Content-Type needs to be specified
The data object needs to contain the request JSON.

jquery json http post - How to convert the post data to json format?

I have this code doing http post, the post is working but the server side expecting data in json format. And it show the data from my post in not in json format. How can I change my code to post the data in json format?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.post("http://www.example.com/post",
dataType: 'json',
{
"userID" :"JohnDoe",
"timeStamp" :""
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
for (var key in data) {
if (data.hasOwnProperty(key)) {
var val = data[key];
console.log(val);
}
}
});
});
});
</script>
</head>
<body>
<button>Send an HTTP POST request to a page and get the result back</button>
</body>
</html>
To post all you need to do is specify the post in a data object like I've done below and specify the dataType: json. (by the way you had a typo, you're missing a ) somewhere)
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<script>
$(document).ready(function() {
$("button").click(function() {
$.post({
type: 'POST',
url: "https://jsonplaceholder.typicode.com/posts",
data: {
"userID": "JohnDoe",
"timeStamp": ""
},
dataType: 'json',
success: function(data, status) {
console.log(data);
alert("Data: " + data + "\nStatus: " + status);
for (var key in data) {
if (data.hasOwnProperty(key)) {
var val = data[key];
console.log(val);
}
}
},
error: function(err) {
console.log(err);
}
});
});
});
</script>
</head>
<body>
<button>
Send an HTTP POST request to a page and get the result back
</button>
</body>
</html>

WordPress OAuth Gets Error 400

I was playing around with the WordPress Rest API, and I was downloading this plugin called WP OAuth Server (by Justin Greer), and I have built my own OAuth connection.
I have one problem: I get Error 400, and it says: The grant type was not specified in the request.
Here is my code so far:
HTML:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="assets/css/app.css" type="text/css">
</head>
<body>
<div id="result"></div>
<!--<script src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false&libraries=places"></script>-->
<script type="text/javascript" src="assets/js/app.js"></script>
</body>
</html>
JavaScript:
/**
* OAUTH 2 LOGIN
*/
+function () {
var $CLIENT_CODE = 'fc8uhbwlo4niqhngrjsdl3tbp3cndpidfs61w77g';
var $CLIENT_ID = 'llsfdwZzO7qVHBzM4nhfcq1jFW2L8O';
var $CLIENT_SECRET = 'auaCKn8JWXQmSyYrl3PDi23klIhotp';
var $AUTHORIZATION_ENDPOINT = 'http://domain.dev/oauth/authorize';
var $TOKEN_ENDPOINT = 'http://domain.dev/oauth/token';
$.ajax({
url: $AUTHORIZATION_ENDPOINT + '?client_id=' + $CLIENT_ID + '&client_secret=' + $CLIENT_SECRET + '&response_type=code',
}).done(function (url) {
$('#result').html(url);
fetchSomething();
}).fail(function (errorThrown) {
console.log("Error" > errorThrown.responseText);
})
function fetchSomething() {
$.ajax({
type: 'POST',
url: $TOKEN_ENDPOINT + '?grant_type=authorization_code&code=' + $CLIENT_CODE,
}).done(function (success) {
console.log(success);
}).fail(function (error) {
console.log(error);
});
}
}();
CodePen
This was my solution
$.ajax({
url: 'http://' + domain + '?oauth=token',
type: 'POST',
data: {
grant_type: grantType,
code: code,
client_id: clientID,
client_secret: clientSecret,
redirect_uri: redirect
}
}).done(function (token) {
console.log(token);
}).fail(function (fail) {
console.log(fail.responseJSON.error);
});

How can I get the results of a JSON POST back

I'm posting this JSON from a form page
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.7.1/dojo/dojo.js" type="text/javascript"></script>
<script type="text/javascript">
function poster()
{
var dataToPost = {grant_type: "password", username: dojo.byId("username").value, password: dojo.byId("password").value, redirect_uri: "http://localhost/default.html"};
var xhrArgs =
{
url: "https://localhost/api/did/authenticate?client_id=12345",
handleAs: 'json',
postData: dojo.toJson(dataToPost),
headers: { "Content-Type": "application/json; charset=UTF-8", "Accept" : "application/json" },
load: function(data, args)
{
alert("Data = " + data);
},
error: function(error, args)
{
alert("Error! " + error);
}
}
dojo.rawXhrPost(xhrArgs);
}
</script>
But I'm not able to get the JSON results from said POST. How can I get those results? Please help. The data I get on the load function is null
The script at https://localhost/api/did/authenticate needs to print or echo or write or otherwise return the JSON as text as it exits.
Turns out that what I was trying to do is not possible in JavaScript since I'm trying to do it from one domain into another... so the cross-domain implementation is not possible, unless I use an embedded flash object, or a proxy pass in my server. thanks for the help though...

How to get FB.api('/me/feed', 'post', ... to work?

I've tried to use FB.api to post something to my feed for hours now. I can't get it to work for me. I gave the permissions to the app. I can post to my feed with the PHP SDK but I have to use JavaScript.
<button onclick="doPost()">Post to Stream</button>
<script>
window.doPost = function() {
FB.api(
'/me/feed',
'post',
{ body: 'Trying the Graph' },
Log.info.bind('/me/feed POST callback')
);
};
</script>
Can someone give me the example of a simple HTML page that uses FB.api to post to a feed?
Well, I got it working myself. I'm not sure what was wrong the first time as I started from scratch with a new HTML file. I hope it will help someone:
<!DOCTYPE html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
</head>
<body>
Post to Facebook
<script>
function postToFacebook() {
var body = 'Reading Connect JS documentation';
FB.api('/me/feed', 'post', { body: body, message: 'My message is ...' }, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response);
}
});
}
</script>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR APP ID GOES HERE',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
};
(function() {
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
</script>
</body>
</html>
I use this code on fb game-app
and looks like this http://trupa.files.wordpress.com/2012/04/prscreenan.jpg
<br><font style="color:#FFF; text-decoration:none;padding-left:27px;">post to wall</font><br>
<script>
function publishStory() {
FB.ui({
method: 'feed',
name: 'message name',
caption: 'message caption ',
description: 'description goes here',
link: 'the url current page',
picture: 'if you want to add an image'
},
function(response) {
console.log('publishStory response: ', response);
});
return false;
}
</script>
In first example you forgot "message" property. With out "message" you can post everyone, but not self.

Categories

Resources