“Uncaught SyntaxError: Unexpected token <” in load-scripts.php

Out of curiosity, I’m implementing AJAX in saving post. I didn’t know where to start until I found this Q&A. It looks something I can grab and build on. It works but something on the WordPress part that’s stopping it from publishing the post; it just stays as a Draft. Here’s a screenshot of the outputted error in the browser console

enter image description here

Read More

Here’s my code

function my_post_type_xhr(){
    global $post;
    if(POST_TYPE === $post->post_type){
        $post_url = admin_url('post.php'); #In case we're on post-new.php
        echo "
        <script>
            jQuery(document).ready(function($){
                //Click handler - you might have to bind this click event another way
                $('#post').bind('submit', function(e){
                    //Post to post.php
                    var postURL = '$post_url';

                    //Collate all post form data
                    var data = $('form#post').serializeArray();

                    //Set a trigger for our save_post action
                    data.push({foo_doing_ajax: true});

                    //The XHR Goodness
                    $.post(postURL, data, function(response){
                        var obj = $.parseJSON(response);
                        if(obj.success)
                            alert('Successfully saved post!');
                        else
                            alert('Something went wrong. ' + response);
                    });

                    e.preventDefault();
                    return false;
                });
            });
        </script>";
    }
}

function save_my_post_type($post_id){
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;

    #If this is your post type
    if(POST_TYPE === $_POST['post_type']){
        //Save any post meta here

        #We conditionally exit so we don't return the full wp-admin load if foo_doing_ajax is true
        if(isset($_POST['foo_doing_ajax']) && $_POST['foo_doing_ajax'] === true){
            header('Content-type: application/json');
            #Send a response
            echo json_encode(array('success' => true));
            exit;
            #You should keep this conditional to degrade gracefully for no JS
        }
    }
}

Could anyone please tell me what’s going on?

Related posts

Leave a Reply