0

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

Ajax Header Screenshot

I tried everything I found online as a solution but no luck yet. Here is some solution that I tried to solve this.

  1. https://www.html5rocks.com/en/tutorials/cors/
  2. https://stackoverflow.com/a/3506306/3967385
  3. https://zinoui.com/blog/cross-domain-ajax-request
  4. http://www.ajax-cross-origin.com/
  5. 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:

  1. 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 )
  2. If it possible then how ? please share at-least a example with REST API
Community
  • 1
  • 1
mlimon
  • 606
  • 8
  • 17

2 Answers2

0

Server has to respond with Allow-Control-Allow-* headers and not your web application.

Access-Control-Allow-Origin : https://www.yourowndomain.com

When browser does not receive above header from server, request will be blocked by browser.

I do not have any experience with Medium but I believe your account has not been given access to their API yet.

Zamrony P. Juhara
  • 4,834
  • 2
  • 22
  • 37
  • I already did that task with `php` & `ajax` and without having any issue. Here I just want to use `jquery` that's all. anyway I already tried with `Access-Control-Allow-Origin : https://www.yourowndomain.com` and also tried now but no luck. – mlimon Oct 21 '16 at 01:18
  • your php script do not run in browser. That is why. – Zamrony P. Juhara Oct 21 '16 at 01:18
  • Please see my post. I didn't want to use php here. is it possible to do this without php help ? – mlimon Oct 21 '16 at 01:20
  • You need to contact administator I believe. – Zamrony P. Juhara Oct 21 '16 at 01:21
  • Thanks, anyway I don't think it's the problem of the access if so then why it's work when I used php ? let's see what other thought about it. Actually I already did this project with using php but now I just want to learn that is it possible to do this with only jQuery or not ? – mlimon Oct 21 '16 at 01:24
  • It works because your php just ignore any `Allow-Control-` header. If you develop your own non-standard web browser and ignore any `Allow-Control-` header, you can too. It is all about obey standard – Zamrony P. Juhara Oct 21 '16 at 01:28
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/126282/discussion-between-mlbd-and-zamrony-p-juhara). – mlimon Oct 21 '16 at 01:47
0

Try this:

add_filter( 'wp_headers', 'send_cors_headers', 11, 1 );
function send_cors_headers( $headers ) {
    $headers['Access-Control-Allow-Origin'] = $_SERVER[ 'HTTP_ORIGIN' ];
    return $headers;
}

Note that this will allow access from ANY source. For security you should try to do something like set an array of allowed domains that can make the request to your WordPress site and short-circuit the allow CORS if the domain making the request is not in the allowed list:

add_filter( 'wp_headers', 'send_cors_headers', 11, 1 );
function send_cors_headers( $headers ) {
    $allowed_domains = array( 'https://my.okdomain.com' , 'http://anothergoodone.com');
    if ( ! in_array( $_SERVER[ 'HTTP_ORIGIN' ] , $allowed_domains ) ) return $headers;
    $headers['Access-Control-Allow-Origin'] = $_SERVER[ 'HTTP_ORIGIN' ];
    return $headers;
}
Lance Cleveland
  • 2,950
  • 1
  • 29
  • 34