Search code examples
javascriptjqueryajaxputhttp-delete

How to NAVIGATE to address synchronously with PUT or DELETE request with javascript or jQuery?


How to issue request

PUT /user/someuser1

and parse result in browser?

Note that AJAX solution in this answer https://stackoverflow.com/a/2153931/258483 does something different: it passes the answer to closure function, while I need synchronous solution, i.e. pass the answer to entire browser window.

Like the following code

location.href = '/user/someuser1';

does with GET request.

UPDATE

I did the following way:

<script type="text/javascript">
    function execute2() {
        url = '/user/' +$('#screenname2').val();
        $.ajax({
            url: url,
            method: 'GET', // PUT
            converters: {"text json": window.String}
        }).done(
            function(http) {
                document.open();
                document.write(http);
                document.close();
                window.history.pushState(null, "New User", url);
            }
        );

    }
</script>
<p>PUT /user/<input type="text" value="someuser1" id="screenname2"> <input type="button" value="Go" onclick="execute2()"></p>

Used GET for test purposes.

Unfortunately, my service returns JSON and it displays differently than if I get it with location.href: in my case it shows as plain text, while if location.href it displays with indentation.

Also, I can't navigate back to initial page -- it changes address in address bar, but not shows the content of referrer page...


Solution

  • HTML doesn't provide any means to make a PUT request, only GET and POST.

    The only way to make one is with JavaScript and XMLHttpRequest. Then the only way you can handle the response you get is to process it with JavaScript.

    Therefore, the closest you can come is to:

    1. Make the request with XHR
    2. Use the callback to read the response
    3. Replace the content of the current document with the content of the response using DOM
    4. Update the URL using pushState