Problems using ajax with PHP

I am trying to use a script for uploading images to TinyMCE and have the code below as part of the tinymcs.init function but it is not working - doesn’t even seem to reach the php method. How can I debug this?

images_upload_handler: function(blobInfo, success, failure) {
            var xhr, formData;

            xhr = new XMLHttpRequest();
            xhr.withCredentials = false;
            xhr.open('POST', '<?= BASE_URL ?>blogs/upload');

            xhr.onload = function() {
                var json;

                if (xhr.status != 200) {
                    failure('HTTP Error: ' + xhr.status);
                    return;
                }

                json = JSON.parse(xhr.responseText);

                alert(json);

                if (!json || typeof json.file_path != 'string') {
                    failure('Invalid JSON: ' + xhr.responseText);
                    return;
                }

                success(json.file_path);
                //console.log(json.file_path);

            };

            formData = new FormData();

            formData.append('file', blobInfo.blob(), blobInfo.filename());

            //console.log('HI THERE');

            xhr.send(formData);
        },

First of all XHRRequest is a very old way and not state of the Art. If you want to write more modern and clean Code you should use the fetch request.
Nevertheless XHRRequest is still working.

What looks strange for me is this line

xhr.open('POST', '<?= BASE_URL ?>blogs/upload');

For my understanding

= BASE_URL

is not a valid PHP command and should throw an error. Must it not be more like?


xhr.open('POST', '<? echo BASE_URL; ?>blogs/upload');

Also I would not expect the base url to contain a slash (this might be a personal thing).

Add a

let url = '<?= BASE_URL ?>blogs/upload';
console.log(url);

Before the xhr.open() line. Then the browser developer console should show you how the called url looks like

<?=... is a shortcut for <?php echo... supported even if short tags are off.

2 Likes

Thanks, Yet learned another thing even if I do not use PHP for some ages now :slight_smile:

2 Likes

I can assure you that the url has been inspected is correct. BASE_URL is defined in the framework.

Define “doesnt even seem to reach the php method”.

Does the XHR request actually fire? Do you see the request going out to the PHP page in your Network tab? If so, what response do you see in the network tab to the request?

@msheath, do you know how to access the network tab? Would you like some guidance?

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.