Top community members
All Wiki Articles Create Wiki Article

Many years me and my friends we were volunteers on my university doing programming classes for young people.

I got main conclusion: Young people are awesome, especially students, because they always bring new and fresh ideas :)
* I loved to do it but my time is limited

  I decided to create something that will help millions of students

Now I am here

co-founder

JavaScript - how to make ajax request?

0 contributions
1 points

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
0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more