-1

I'm expecting the following piece of code to execute the Ajax call. However, I see a 405 error which says

The requested resource does not support http method 'GET'.

If I use type = 'json' I get

The requested resource does not support http method 'JSON'.

Here is the relevant portion of my content script code

$(document).ready(function() {
            var imgSrcArr = [];
            $('img').each(function(e) {
                var s = this.src;
                imgSrcArr.push(s);

                $.ajaxSetup({cache: false});

                var formData = new FormData();
                formData.append("apikey", "xxxxxxxxxxxxxxx"); 
                formData.append("isOverlayRequired", false);
                formData.append("url", s);              
                //console.log(formData);

                //console.log($.support.cors);
                $.ajax({
                    url: "https://api.ocr.space/parse/image",
                    data: {apikey: "xxxxxxxxxxxxxxx", url: s},
                    //method: 'GET',
                    dataType: 'json',
                    async: false,
                    cache: false,
                    contentType: "application/json; charset=utf-8",
                    processData: false,
                    type: 'GET',
                    crossDomain: true,
                    xhrFields: {
                        // The 'xhrFields' property sets additional fields on the XMLHttpRequest.
                        // This can be used to set the 'withCredentials' property.
                        // Set the value to 'true' if you'd like to pass cookies to the server.
                        // If this is enabled, your server must respond with the header
                        // 'Access-Control-Allow-Credentials: true'.
                        withCredentials: true
                    },
                    headers: {
                        // Set any custom headers here.
                        // If you set any non-simple headers, your server must include these
                        // headers in the 'Access-Control-Allow-Headers' response header.
                    },
                    success: function(ocrParsedResult, textStatus, jqXHR) {
                        //Get the parsed results, exit code and error message and details
                        var parsedResults = ocrParsedResult["ParsedResults"];
                        var ocrExitCode = ocrParsedResult["OCRExitCode"];
                        var isErroredOnProcessing = ocrParsedResult["IsErroredOnProcessing"];
                        var errorMessage = ocrParsedResult["ErrorMessage"];
                        var errorDetails = ocrParsedResult["ErrorDetails"];

                        var processingTimeInMilliseconds = ocrParsedResult["ProcessingTimeInMilliseconds"];

                        //If we have got parsed results, then loop over the results to do something
                        if (parsedResults!= null) {
                            //Loop through the parsed results
                            $.each(parsedResults, function (index, value) {
                                var exitCode = value["FileParseExitCode"];
                                var parsedText = value["ParsedText"];
                                var errorMessage = value["ParsedTextFileName"];
                                var errorDetails = value["ErrorDetails"];

                                var textOverlay = value["TextOverlay"];

                                var pageText = '';
                                switch (+exitCode) {
                                    case 1: 
                                        pageText = parsedText;
                                        break;
                                    case 0:
                                    case -10:
                                    case -20:
                                    case -30:
                                    case -99:
                                    default: 
                                        pageText += "Error: " + errorMessage;
                                        break;
                                }

                                console.log(parsedText);


                                var bazExtract = extractEmails1(parsedText);
                                if(bazExtract !== null) {
                                    extractEmails2(bazExtract);
                                }
                            });
                        }
                    },
                    error: function(err) {
                        console.log(err);
                    }
                });
            });
            //console.log(imgSrcArr);
        });

A note: Other sections of the content script code are running as expected but there's no Server response (in the developer console) to the Ajax request.

If this is a CORS issue, is there a workaround for this kind of an error? I tried a handful of answers to similar questions on SO but I'm unable to move forward with any of those.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
  • Possible duplicate of [jQuery .ajax() POST Request throws 405 (Method Not Allowed) on RESTful WCF](http://stackoverflow.com/questions/17333013/jquery-ajax-post-request-throws-405-method-not-allowed-on-restful-wcf) – Martin Hučko Jul 09 '16 at 08:11
  • you can't use an object as the `data:` parameter if you use `contentType: "application/json"` and `processData: false`. The `processData` option says not to convert the object to a string, and `$.ajax` doesn't know how to send JSON. – Barmar Jul 09 '16 at 08:26
  • You should only use `processData: false` if you do `data: formData`. And then you should use `contentType: 'multipart/form-data'`. – Barmar Jul 09 '16 at 08:28
  • @Barmar Hey I changed `contentType` to `'multipart/form-data'` and `data` to `formData` and `type` to `POST` and now I see no error or any server response in the console. I should at least be able to see `console.log(parsedText)`. Why is it so? –  Jul 09 '16 at 09:36
  • Do you see the request and response in the Network tab of the console? – Barmar Jul 09 '16 at 09:38
  • @Barmar I'm not that familiar with the Network tab. However, in the XHR part of the Network tab I see only _1 red line_ with _Initiator_ as _VM20787:4_. Does it have anything to do with my code? –  Jul 09 '16 at 09:58
  • I don't think so. Names like that come from code that's created on the fly with `eval()`. – Barmar Jul 09 '16 at 10:00
  • Your code is running when the page is first loaded. Make sure you have the Network tab open before you reload the page, otherwise it won't capture this. – Barmar Jul 09 '16 at 10:01
  • @Barmar Did that but no noticeable changes :(. Network tab shows only `DOMContentLoaded: 11.53s` and `Load: 29.66s`. –  Jul 09 '16 at 10:09
  • Put a breakpoint inside the `.each()` function to make sure it's running. – Barmar Jul 09 '16 at 10:12
  • @Barmar You mean the **second** occurrence of `.each()` right? Can you suggest a suitable line that I can add 'cause `console.log` is not showing anything. –  Jul 09 '16 at 10:28
  • No, I mean the first occurrence. If you're not seeing anything in the Network tab, then it means none of the `$.ajax` calls are being done. Put the breakpoint on the `$.ajax` line. – Barmar Jul 09 '16 at 10:34
  • @Barmar I typed `debugger;` right before the occurrence of `$.ajax()` and when I reload the page the Developer Tools takes me to the `debugger;` line. How do I proceed from here? –  Jul 09 '16 at 10:42
  • Why do you do that instead of setting the breakpoint in the source viewer? Just click on a line to add or remove a breakpoint. Anyway, now you can open the Network tab to make sure it's recording AJAX request, then go back to the Source tab and click the arrow button to continue. – Barmar Jul 09 '16 at 10:47

1 Answers1

1

The title "Post Parameters" in the documentation of the API suggests that you should do a POST, not a GET. That is, use: type: POST

rsanchez
  • 14,467
  • 1
  • 35
  • 46
  • And get rid of the `contentType` and `processData` options as well. – Barmar Jul 09 '16 at 08:27
  • @Barmar When I remove `contentType` and `processData` keeping `type` is 'POST' I'm getting `jQuery.Deferred exception: Illegal invocation TypeError: Illegal invocation` which points to `$.ajax` line and `$('img')` line. FYI I changed `$('img')` to `$('img[src *= "mail"]')` and that shouldn't affect my existing code right? –  Jul 09 '16 at 09:43
  • @SunandoSamaddar What do you have as the `data` option when you do that? Your comment above says you changed to `data: formData`, and in that case you DO need `processData: false`. – Barmar Jul 09 '16 at 09:45
  • @Barmar Sorry about that. This time I'm doing `data: formData` and `processData: false` but again can't see the `console.log(parsedText)` output in the console. –  Jul 09 '16 at 10:03