Every time I attempt to send a PUT request using AJAX, I encounter an error

After developing HTML and AJAX code to update a camera password within my network, I encountered an issue upon form submission.

"error" (net::ERR_EMPTY_RESPONSE)

Surprisingly, the PUT request functions perfectly when tested with POSTMAN, showing a status of OK(200). Interestingly, the code also executes flawlessly in Local mode using Internet Explorer. However, upon deployment to the server, it fails to work with Internet Explorer as well, displaying errors like "pending" and "access denied."

function myFunction() {
    var settings = {
        "async": true,
        "crossDomain": true,
        "url": "http://192.168.1.64/Security/users?auth=YWRtaW46MTEK",
        "method": "PUT",
        "headers": {
            "cache-control": "no-cache",
            "postman-token": "fda97359-6164-70d0-2896-8ca4804ac06c"
        },
        "data": "<UserList xmlns=\"http://www.hikvision.com/ver10/XMLSchema\" version=\"1.0\"><User xmlns=\"http://www.hikvision.com/ver10/XMLSchema\" version=\"1.0\"><id>1</id><userName>admin</userName><password>TT.123456</password></User></UserList>"
    }

    $.ajax(settings).done(function (response) {
        console.log(response);
    });
}

The error persists in Chrome. Please refer to the attached screenshot for more details.

Here is a screenshot from "POSTMAN":

Answer №1

To execute a cross-domain request on the client-side, it's advisable to opt for a POST request instead of utilizing a PUT method. According to the MDN documentation regarding HTTP access control (CORS):

Simple requests

Some types of requests don't prompt a CORS preflight. These are referred to as "simple requests" in this context, although the Fetch specification doesn't employ that term. A request that avoids triggering a CORS preflight—labelled as a "simple request"—must fulfill certain criteria outlined below:

1

After running your code locally and switching the method to POST, I had to include the following headers on the endpoint:

access-control-allow-headers: cache-control,postman-token
access-control-allow-origin: *

Although the Access-Control-Allow-Origin header could be specifically set to a particular domain rather than using *. For instance:

Access-Control-Allow-Origin: https://intranetHost

In the figure below, the initial XHR request serves as the pre-flight request (with method being OPTIONS) while the subsequent one is the factual request (involving the method POST)

https://i.stack.imgur.com/WFZ9A.png

If a PUT request is still necessary, an alternative approach would involve sending a request to a server-side endpoint responsible for executing the PUT request (e.g. via cURL).


1https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Simple_requests

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Wrap the json response in HTML elements

I'm currently learning about AJAX, and I've encountered a major issue that I can't seem to resolve. I pass several variables to PHP, perform various checks there, and then return string values to AJAX. Strangely, I am able to display these r ...

Load jQuery core asynchronously with a backup plan

Exploring performance optimization and non-blocking scripts in the header, my focus has been on asynchronously loading jQuery itself. In my search, I came across a jQuery Loader script that can async load jQuery and then handle and queue jQuery document r ...

What is the best way to monitor the quantity of server-side requests being made while utilizing jQuery Validate's remote feature?

Currently, I am implementing jQuery Validate to handle form validation on my website. In this process, I'm utilizing an Ajax call to verify certain data and I find the need to keep track of the number of attempts or calls made to the server. For inst ...

What is the best way to determine the ideal scrollTop value?

When loading content through ajax into #list, I am determining the necessary scroll based on the height of #list, but I want to reduce it by 200px. After the ajax call is complete, I execute: var pos = jQuery("#list").innerHeight() - 200; Once the height ...

Rearrange the sequence of numbers using JQuery when an HTML element is deleted

I'm currently working on a simple functionality where I have 5 rows, each with its own number. So initially, the rows are numbered from 5 to 1. If I remove a value like 3, the sequence should adjust to 4, 2, 1, indicating that I now have only 4 rows ...

PHP encountered an issue when retrieving a value from a URL and passing it to a JavaScript variable

How can I pass a PHP variable from the URL using $_REQUEST to JavaScript in order to send it through Ajax? Here is the code snippet at the top of my page: <?php include_once('../php/connection.php'); include_once('../php/getDiagnosi ...

if a condition is not being properly assessed

Currently, I am working on a $.ajax call to retrieve data in JSON format. Within this JSON data, there is an element called "status." My code snippet checks if the value of `data.status` is equal to "success" and performs some actions accordingly. Despite ...

The jQuery Modal Dialog functions properly on the initial page load, but fails to work on subsequent pages unless manually refreshed

So, I've encountered an issue with my jQuery modal dialog. It's set up to remind non-registered users to sign up when they try to access user-only actions. Oddly enough, the dialog functions perfectly after a page refresh on THAT specific page. H ...

JSON - The challenge of incorporating single quotes within double quotes

In my current scenario, I am using the following code to populate form fields. The code is designed to handle a JSON dataset that has been encoded with PHP's json_encode function. Everything works smoothly when dealing with either single or double qu ...

The challenge with linking within Layerslider

Having some trouble with an external link to a specific layerslider slide (html version, NOT wordpress). Here is the webpage in question: After reaching out in the support forum, I was advised to use this javascript: <a href="javascript:void(0);" onc ...

The module "jquery" in jspm, jQuery, TypeScript does not have a default export

Having some trouble setting up a web app with TypeScript and jspm & system.js for module loading. Progress is slow. After installing jspm and adding jQuery: jspm install jquery And the initial setup: <script src="jspm_packages/system.js"></scri ...

Error encountered: index.html:17 - An InvalidStateError was thrown when attempting to execute the 'send' function on the XMLHttpRequest object. The object's state must be OPENED in order to send the Ajax request

When attempting to run index.html on a local host with xampp, an error is encountered: index.html:17 Uncaught InvalidStateError: Failed to execute 'send' on 'XMLHttpRequest': The object's state must be OPENED.sendAjax @ index.html: ...

Using jQuery to iterate through an array and reverse its order

Is there a way to loop through an array and change the CSS background color chronologically rather than randomly? Additionally, is it possible to reverse through the same array when the back button is clicked? http://jsfiddle.net/qK2Dk/ $('#right&a ...

Enhancing data with Django REST framework through AJAX requests

I'm encountering an issue where attempting to send data from the frontend to the serializer results in a HTTP 400 error. Strangely, when I make the same request directly via the DRF browsable API, it works perfectly fine: Here's my model setup: ...

Is there a way to navigate to the "Error" view page following an AJAX request?

Currently, I am utilizing an Ajax function to call an HTTP Post Action method located in the controller. During this process, the action method is producing a basic exception message. To address this issue, I have applied my own personalized handler attr ...

Change the websocket origin to localhost in a javascript setting

My server is hosting the domain example.com. Every time a user loads a page on this server, it utilizes a WebSocket client in JavaScript to connect to another WebSocket server. However, the other server has CORS enabled, which prevents the connection bec ...

Real-time drop down options change depending on selection in another drop down menu

Seeking guidance in the right direction, I am currently working with a file called data.php. Inside this file, I have the following data: $sports_arr = array(); $sports_arr[] = "Basketball"; $sports_arr[] = "Baseball"; $sports_arr[] = "Football"; Additio ...

How to retrieve 'data' attributes from an object that was dynamically loaded?

I'm currently facing an issue with accessing the data attributes of a dynamically loaded file using AJAX. For instance, I load a file containing: <div id="blah" class="hello" data-something="or_other" /> Then, I use jQuery to access the data: ...

What is the proper way to indicate "if the value is anything other than a, b, or c"?

$(this).attr('id') == 'zipcode' && $this.value()!=(3, 4, 5) In this snippet of code, I attempted to target the text input field with an id of "zipcode" and implement a condition that checks whether the value of zipcode is not e ...

Extracting Json data with Jquery

My JSON data format is as follows - I've been struggling to find a way to retrieve the photo reference value. Can anyone help me with this? { "debug_info" : [], "html_attributions" : [ "Listings by \u003ca href=\"http://www.yellowpages. ...