Here I tried to create new post on my Medium profile from my WordPress fronted form with Medium API.
jQuery(document).ready(function ($) {
function get_tinymce_content(){
if (jQuery("#wp-mediumcontenteditor-wrap").hasClass("tmce-active")){
return tinyMCE.activeEditor.getContent();
}else{
return jQuery('#mediumcontenteditor').val();
}
}
function formToJSON() {
return JSON.stringify({
"title": $('#m_title').val(),
"contentFormat": 'html',
"content": get_tinymce_content(),
"tags": ["football", "sport", "Liverpool"],
"publishStatus": 'public'
});
}
// Perform AJAX
$('form#medium').on('submit', function(e){
$('p.status', this).show().text(ajax_magic_kuira.loadingmessage);
ctrl = $(this);
$.ajax({
xhrFields: {
withCredentials: true
},
type: 'POST',
url: 'https://api.medium.com/v1/users/xxxuserID/posts',
dataType: 'json',
crossDomain: true,
contentType: "application/json; charset=utf-8",
data: formToJSON(),
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Bearer xxxxToken");
},
headers: {
"Access-Control-Allow-Headers": 'Origin',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE',
'Access-Control-Allow-Credentials': true,
'Access-Control-Allow-Origin': 'http://demopress.xyz' // my domain where I make the ajax request.
},
success: function(data, textStatus, jqXHR){
alert('Successfully Request Send!!');
},
error: function(jqXHR, textStatus, errorThrown){
alert('Sorry -- Error');
}
});
e.preventDefault();
return false;
});
});
But couldn't send data via ajax. After submit my form every time I get error back Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.medium.com/v1/users/xxxuserID/posts. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
I tried everything I found online as a solution but no luck yet. Here is some solution that I tried to solve this.
- https://www.html5rocks.com/en/tutorials/cors/
- https://stackoverflow.com/a/3506306/3967385
- https://zinoui.com/blog/cross-domain-ajax-request
- http://www.ajax-cross-origin.com/
- ETC
When I used those solution for GET
(Retrieve data from server) data via REST API it's work and also GET
work without using any tricks. Means If I want to retrieve data from another domain it's work fine but when I used POST/PUT
Method to create or send new data to another server the it's not working and replay back with same error.
Note: I can send data successfully by using
php
but I didn't want to use here php and also core javascript. I just want did this task using jQuery/ajax only.
Here is my Question:
- Is possible to post another server using only jquery/ajax with REST API ( Like I want to create a new post on my Medium Profile )
- If it possible then how ? please share at-least a example with REST API