Languages
[Edit]
EN

JavaScript - how to make ajax request?

1 points
Created by:
JustMike
26150

In JavaScript it is possible to make AJAX requerst in following ways.

1. Pure JavaScript (Vanilla JS) AJAX request with XMLHttpRequest object example

Browser site GET and POST methods example:

<!doctype html>
<html lang="en">
<body>
<script>

    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function () {
        // if request done
        if (xhr.readyState == XMLHttpRequest.DONE) {
            // if 200 http status received
            if (xhr.status == 200)
                // server response as text
                document.body.innerText = 'Response: ' + xhr.responseText;

            else
                // error status
                document.body.innerText = 'Error: ' + xhr.status;
        }
    };

    // initialize or re-initialize GET request
    xhr.open('GET', '/echo', true);
    // send request without any data
    xhr.send(null);

/*
    // POST method example:

    var data = 'This is my data...';

    // initialize or re-initialize GET request
    xhr.open('POST', '/echo', true);
    // send request with data
    xhr.send(data);
*/

</script>
</body>
</html>

SpringMVC server site GET and POST methods example:

package com.dirask.ckeditor4.remake.spring.boot.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
public class EchoController {

    @RequestMapping(value = "/echo", method = RequestMethod.GET)
    @ResponseBody
    public String makeGetEcho()
    {
        return "Echo...";
    }

/*
    // Alternative POST method example:

    @RequestMapping(value = "/echo", method = RequestMethod.POST)
    @ResponseBody
    public String makePostEcho(@RequestBody String data)
    {
        return data;
    }
*/
}

Note: run both logics on same server.

Result:

XMLHttpRequest with GET request method usage example run on localhost.
XMLHttpRequest with GET request method usage example run on localhost.

2. jQuery AJAX request example 

Browser site GET and POST methods example:

<!doctype html>
<html lang="en">
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<script>

    $.ajax({
        type: 'GET',
        url: '/echo',
        success: function (data) {
            document.body.innerText = 'Response: ' + data;
        },
        error: function(jqXHR) {
            document.body.innerText = 'Error: ' + jqXHR.status;
        }
    });

/*
    // POST method example:

    $.ajax({
        type: 'POST',
        url: '/echo',
        data: 'This is my data...',
        success: function (data) {
            document.body.innerText = 'Response: ' + data;
        },
        error: function(jqXHR) {
            document.body.innerText = 'Error: ' + jqXHR.status;
        }
    });

    // or
 
    $.get('/echo')
        .done(function(data) {
            document.body.innerText = 'Response: ' + data;
        })
        .fail(function(jqXHR) {
            document.body.innerText = 'Error: ' + jqXHR.status;
        });

    // or 

    $.post('/echo', 'This is my data...')
        .done(function(data) {
            document.body.innerText = 'Response: ' + data;
        })
        .fail(function(jqXHR) {
            document.body.innerText = 'Error: ' + jqXHR.status;
        });

 */

</script>
</body>
</html>

SpringMVC server site GET and POST methods example:

package com.dirask.ckeditor4.remake.spring.boot.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
public class EchoController {

    @RequestMapping(value = "/echo", method = RequestMethod.GET)
    @ResponseBody
    public String makeGetEcho()
    {
        return "Echo...";
    }

/*
    // Alternative POST method example:

    @RequestMapping(value = "/echo", method = RequestMethod.POST)
    @ResponseBody
    public String makePostEcho(@RequestBody String data)
    {
        return data;
    }
*/
}

Note: run both logics on same server.

Result:

jQuery AJAX GET request method usage example run on localhost.
jQuery AJAX GET request method usage example run on localhost.

3. fetch method example

Browser site GET and POST methods example:

<!doctype html>
<html lang="en">
<body>
<script>

    fetch('/echo')
        .then(data => {
            data.text()
                .then(text => {
                    document.body.innerText = 'Response: ' + text;
                });
        })
        .catch(error => {
            console.log('Error:', error);
        });

/*
    // POST method example:

    var config = {
        method: 'POST',
        body: 'This is my data...'
    };

    fetch('/echo', config)
        .then(data => {
            data.text()
                .then(text => {
                    document.body.innerText = 'Response: ' + text;
                });
        })
        .catch(error => {
            console.log('Error:', error);
        });
*/
</script>
</body>
</html>

SpringMVC server site GET and POST methods example:

package com.dirask.ckeditor4.remake.spring.boot.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
public class EchoController {

    @RequestMapping(value = "/echo", method = RequestMethod.GET)
    @ResponseBody
    public String makeGetEcho()
    {
        return "Echo...";
    }

/*
    // Alternative POST method example:

    @RequestMapping(value = "/echo", method = RequestMethod.POST)
    @ResponseBody
    public String makePostEcho(@RequestBody String data)
    {
        return data;
    }
*/
}

Note: run both logics on same server.

Result:

GET request method usage example with fetch method run on localhost.
GET request method usage example with fetch method run on localhost.

4. fetch method with ES7 async/await example

Browser site GET and POST methods example:

<!doctype html>
<html lang="en">
<body>
<script>

    async function doRequest() {
/*
        // Uncomment this source code for POST request method

        var config = {
            method: 'POST',
            body: 'This is my data...'
        };
*/

        try {
            const response = await fetch('/echo'/*, config*/);
            const text = await response.text();

            document.body.innerText = 'Response: ' + text;
        } catch (error) {
            console.log('Error:', error);
        }
    }

    doRequest();

</script>
</body>
</html>

SpringMVC server site GET and POST methods example:

package com.dirask.ckeditor4.remake.spring.boot.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
public class EchoController {

    @RequestMapping(value = "/echo", method = RequestMethod.GET)
    @ResponseBody
    public String makeGetEcho()
    {
        return "Echo...";
    }

/*
    // Alternative POST method example:

    @RequestMapping(value = "/echo", method = RequestMethod.POST)
    @ResponseBody
    public String makePostEcho(@RequestBody String data)
    {
        return data;
    }
*/
}

Note: run both logics on same server.

Result:

GET request method usage example with fetch method and ES7 async/await run on localhost.
GET request method usage example with fetch method and ES7 async/await run on localhost.

References

  1. Ajax (programming) - Wikipedia
  2. XMLHttpRequest.prototype.send method - MDN Docs
  3. jQuery.ajax method - jQuery Docs
  4. Using Fetch - MDN Docs
Native Advertising
50 000 ad impressions - 449$
ūüöÄ
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

‚̧ԳŹūüíĽ ūüôā

Join