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 of 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 parameter 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, the server side and the client side. The server side is implemented by Node JS, the client side is implemented by jQuery. You can read the article Node JS HTTP Server Get Post Example to learn more about Node JS server side source code. You can view the demo video through the youtube URL https://youtu.be/Prte2K1hmls.

Below is the source code for this example, the http-server.js file will implement the Node.JS web server and the jquery-ajax.html file will implement the ajax request client web page.

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 the http-server.js saved folder and run node http-server.js then you can see the below 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 the page is rendered.

3. How to fix invalid JSON primitive error.

  1. I use jQuery ajax to send a JSON object to a web service through the HTTP POST method. Below is the jQuery ajax javascript source code and the JSON object content. When I run the below source code, it returns an error with the error message Invalid JSON primitive, how can I fix this, thanks.
    // jQuery ajax javascript that send HTTP POST request to a web service.
    $.ajax({
            // Request method is POST.
            type: "POST",
    
            // The web service URL.
            url: "/webservices/AddUsers", 
    
            // The post data.
            data: users, 
    
            // The contentType http header value.
            contentType: "application/json; charset=utf-8", 
    
            // Post data format.
            dataType: "json", 
    
            // The callback function when the web service return success.
            success: function(data){alert(data);}, 
    
            // The callback function when the web service return fail.
            failure: function(errMsg) {
                alert(errMsg);
            }
      });
    
    // Below is the JSON data that will be sent to the web service.
    var users = { "users": [
      { "user_name": "jerry", "password": "123456789", "email": "[email protected]" },
      { "user_name": "tom", "password": "abcdefg", "email": "[email protected]"  },
      { "user_name": "richard", "password": "qwert", "email": "[email protected]"  }
    ]};
  2. The invalid JSON primitive error is caused usually because of an invalid post JSON string, you should pass a JSON string to the jQuery ajax data parameter. But in your source code, you pass a javascript object to the jQuery ajax data parameter. When you pass the javascript object to the data parameter, jquery will URLEncode the post data. You can use the firebug to find that the posted data has been encoded. So you should change the jQuery ajax data parameter value to JSON.stringify({ Users: users }) to fix this error.
    // jQuery ajax javascript that send HTTP POST request to a web service.
    $.ajax({
            // Request method is POST.
            type: "POST",
    
            // The web service URL.
            url: "/webservices/AddUsers", 
    
            // The post data.
            data: JSON.stringify({ Users: users }), 
    
            // The contentType http header value.
            contentType: "application/json; charset=utf-8", 
    
            // Post data format.
            dataType: "json", 
    
            // The callback function when the web service return success.
            success: function(data){alert(data);}, 
    
            // The callback function when the web service return fail.
            failure: function(errMsg) {
                alert(errMsg);
            }
      });

Leave a Comment

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.