jQuery Ajax Get, Post With JSON Example

Besides use XMLHttpRequest to implement http get, post request in ajax web application, jQuery also provide some methods which wrap XMLHttpRequest to achieve http get, post ajax request also. This article will show you examples about how to use them.

1. jQuery Ajax Http Get Post Methods.

jQuery provide below methods to implement get or post http request in ajax web application.

  1. .ajax( settings ) : This is the base method that all other get, post method will invoked. The settings is a JSON object, it’s content is name:value pair such as {type:”POST”, url:”login.html”, data:”…”, success:function(data, status){}} etc.
  2. .get(url, queryStringJSONObject, callback_function) : Invoke http get request to url, the query string parameters can be set in the second JSON object parameter. The third parameter is the callback function when get request complete.
  3. .post(url, postDataJSONObject, callback_function) : Similar with .get method, but use http post method.
  4. .getJSON(url, postDataJSONObject, callback_function) : Similar with .get method, but the return data is a JSON object.

2. jQuery Ajax Get Post Use JSON Example.

This example has two sides, serve side and client side. The server side is implemented by Node JS, the client side is implemented by jQuery. You can read article Node JS Http Server Get Post Example to learn more about Node JS server side source code.

Below is the source code for this example.

jquery ajax get post json example source code

2.1 Server Side Node JS Source Code.

http-server.js

// Include http ,url module.
var http = require('http');
var url = require('url');
var queryString = require('querystring');


// This function is used to verify username and password and return related message back to client.
function verifyUserAccount(userName, password, resp, reqMethod){
    // Create an empty JSON object to return.
    var retJson = {};

    retJson.reqMethod = reqMethod;

    var message = '';

    retJson.userName = userName;

    retJson.password = password;

    if('jerry' == userName && '666666' == password)
    {
        message = 'User name and password is correct. ';
    }else if(''==userName && ''==password){
        message = 'User name and password can not be empty. ';
    }else {
        message = 'User name and password is not correct. ';
    }

    // Set return message.
    retJson.message = message;

    /* Set Access-Control-Allow-Origin http header will fix No 'Access-Control-Allow-Origin' header is present on the requested resource error
       when use XMLHttpRequest object to get this server page via ajax method. */
    resp.writeHead(200, {'Access-Control-Allow-Origin':'*'});

    resp.end(JSON.stringify(retJson));
}

// Create http server.
var httpServer = http.createServer(function (req, resp) {

    // Get request method.
    var method = req.method;

    // If post.
    if("POST" == method)
    {
        var postData = '';

        // Get all post data when receive data event.
        req.on('data', function (chunk) {
            postData += chunk;
        });

        // When all request post data has been received.
        req.on('end', function () {

            console.log("Client post data : " + postData);

            var postDataObject = null;

            try
            {
                // Parse the post data and get client sent username and password.
                postDataObject = JSON.parse(postData);
            }catch(error)
            {
                // Parse data from query string.
                postDataObject = queryString.parse(postData);
            }

            userName = postDataObject.user_name;

            password = postDataObject.password;

            verifyUserAccount(userName, password, resp, method);
        })
    }else if("GET" == method)
    {
        // Get and parse client request url.
        var reqUrlString = req.url;

        var urlObject = url.parse(reqUrlString, true, false);

        // Get user name and password.
        var userName = urlObject.query.user_name;

        var password = urlObject.query.password;

        verifyUserAccount(userName, password, resp, method);
    }


});

// Http server listen on port 8888.
httpServer.listen(8888);

console.log("Http server is started and listen on port 8888.");

2.2 Client Side jQuery Source Code.

jquery-ajax.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jQuery Ajax Get, Post, JSON Example</title>

    <script type="text/javascript" src="../lib/jquery-3.3.1.min.js"></script>

    <script type="text/javascript">

        $(function () {

            //When click get button.
            $("#getButton").click(function () {

                var url = 'http://localhost:8888/login';

                // Send get request use jquery ajax.
                $.get(url, function (data) {
                   alert(data);
                });
            });

            // Click this button to send get request with parameter.
            $("#getSendParamButton").click(function () {

                var url = 'http://localhost:8888/login';

                var params = {user_name:'jerry', password:'666666'};

                $.get(url, params, function (data) {
                    alert(data);
                });

            });

            // Click this button to send post request with data.
            $("#postButton").click(function () {

                var url = 'http://localhost:8888/login';

                var postData = {user_name:'jerry', password:'666666'};

                // jQuery .post method is used to send post request.
                $.post(url, postData, function (data, status) {
                    alert("Ajax post status is " + status);
                    alert(data);
                });

            });

            // Click this button to send http get request and return a JSON object.
            $("#jsonButton").click(function () {

                var url = 'http://localhost:8888/login';

                var postData = {user_name:'jerry', password:'888888'};

                // .getJSON method is used to send get request which return a JSON data.
                $.getJSON(url, postData, function (data) {

                    var content = "User Name : ";

                    content += data.userName;

                    content += "<br/>Password : ";

                    content += data.password;

                    content += "<br/>Request Method : ";

                    content += data.reqMethod;

                    content += "<br/>Message : ";

                    content += data.message;

                    // Display the string in a div html tag.
                    $("#jsonData").html(content);

                });

            });

            /* Click this button to invoke fundamental jQuery .ajax method.
               All above methods are based on this method. */
            $("#ajaxButton").click(function () {

                var url = 'http://localhost:8888/login';

                var queryString = "user_name=jerry&password=666666";

                $.ajax({
                    type:"GET",
                    url:url,
                    data:queryString,
                    async:false,
                    success: function (data) {
                        alert(data);
                    }
                });

            });

        });

    </script>

    <style type="text/css">

        .center{
            text-align: center;
            margin-top: 30px;
        }

    </style>
</head>
<body>

<div class="center">

    <button id="getButton">jQuery .get method</button>

    <button id="getSendParamButton">jQuery .get with parameter</button>

    <button id="postButton">jQuery .post method</button>

    <button id="jsonButton">jQuery .getJSON method</button>

    <button id="ajaxButton">jQuery .ajax method</button>

    <div id="jsonData" style="display: block;margin-top: 30px"></div>

</div>
</body>
</html>

2.3 How To Run Above Example.

  1. Open a terminal and go to http-server.js saved folder and run node htt-server.jsthen you can see bellow output in the console.
    /usr/local/bin/node /Users/zhaosong/Documents/WorkSpace/dev2qa.com-example-code/JavaScriptExampleWorkspace/jQueryWorkspace/jQueryProject/ajax/http-server.js
    Http server is started and listen on port 8888.
    Client post data : user_name=jerry&password=666666
  2. Open a web browser and copy and paste jquery-ajax.html absolute file path into the web browser address input box and click each button when page is rendered.
(Visited 1,255 times, 28 visits today)
READ :   Difference Between Native Dom And jQuery Object

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.