jQuery JSON - Send JSON Data Using The AJAX Function


So you want to send and receive JSON data via jQuery? Not a problem. We will cover all the basic info needed to get you up and running with JSON data transfers. If you're new to jQuery and need to know what it is, how to download it or how to add it to your page simply visit the websites listed below.

Official jQuery Site:  jquery.com
jQuery Intro:             learn.jquery.com/about-jquery/how-jquery-works/
Download jQuery:     jquery.com/download/


During this tutorial you may want to refer to the jQuery documentation for the .ajax() method so the link has been provided below.

AJAX API Documentation:   api.jquery.com/jQuery.ajax/




Now that we have the boring stuff out of the way let's dive into the code.


1. The first thing we need to do is create the basic structure of the AJAX call. The reason we use the curly braces inside the parentheses is because we're building a PlainObject which will tell the AJAX method what to do.


$.ajax({

});



2. Next we need to tell jQuery that we want to use the POST method for transferring the data.


$.ajax({
    type: "POST",
});



3. Now that jQuery knows how to send the data we need to specify where to send the data. Let's assume there is a generic script called "json_data.php" that will handle all the data we send and will then return more JSON data. Basic information regarding JSON data manipulation in PHP is listed in the "PHP Notes" section at the end of this tutorial.


$.ajax({
    type: "POST",
    url: "http://www.example.com/json_data.php",
});



4. Before we add our actual data we have to let jQuery know what type of data we plan on getting back from the server. In this case we will use the "json" dataType.


$.ajax({
    type: "POST",
    url: "http://www.example.com/json_data.php",
    dataType: "json",
});



5. At this point we can add our data. Since we're sending JSON data we need to make sure it's in the JSON format. Simply wrap the data in curly braces and make key/value pairs separated by commas. In this example I created a key called "cmd" and assigned it the value "High Five". I also created a key called "username" and assigned it the value of a variable called "username". This was done to demonstrate how to pull data from inside your JavaScript code. The username variable is initialized outside the ajax() call with the string value "Jessica".

var username = "Jessica";
$.ajax({
    type: "POST",
    url: "http://www.example.com/json_data.php",
    dataType: "json",
    data: {
        "cmd": "High Five",
        "username": username
    }
});



6. If we only wanted to send data, the code above would work just fine but for this tutorial we also want to receive data. To receive JSON data from the server we need to assign some code to the "success" event handler. This is done by adding the "success" keyword and creating an unnamed function to the right. It is very important that we add a parameter to the function which jQuery will use to pass the returned data to our code. Let's keep it simple and call the parameter "data".


var username = "Jessica";
$.ajax({
    type: "POST",
    url: "http://www.example.com/json_data.php",
    dataType: "json",
    data: {
        "cmd": "High Five",
        "username": username
    },
    success: function( data ){
     
    }
});



7. At this point the data parameter will contain the returned JSON data if the ajax() call was successful. To access the JSON values we just type "data" followed by the "." operator and add the key at the end. For the sake of simplicity, let's assume the server just echos back the same JSON data that we had sent. If we want to get the returned value of "cmd" we would type "data.cmd" and content would be equal to "High Five". Likewise, "data.username" would contain the string "Jessica". Both of these examples are shown below as comments.


var username = "Jessica";
$.ajax({
    type: "POST",
    url: "http://www.example.com/json_data.php",
    dataType: "json",
    data: {
        "cmd": "High Five",
        "username": username
    },
    success: function( data ){
        //data.cmd
        //data.username
    }
});


8. Debug: Let's say we want to make sure that the correct data is getting returned. To do this we can wrap the content with "console.log()" to send the values to the JavaScript console which is located in the browser's developer console (Press F12 in Firefox and Chrome to open the developer console). If you don't feel like using the developer console you can also use the  JavaScript "alert()" function.


var username = "Jessica";
$.ajax({
    type: "POST",
    url: "http://www.example.com/json_data.php",
    dataType: "json",
    data: {
        "cmd": "High Five",
        "username": username
    },
    success: function( data ){
        console.log( data.cmd );
        console.log( data.username );
        //or
        alert( data.cmd );
        alert( data.username );
    }
});


9. There are many other ways to customize your ajax() call to suit your needs. For example, you can add error handling, headers, JSONP, mimeTypes, passwords, dataFilters...etc. All of these are optional and will not be covered in this tutorial. For more information please refer to the official API documentation.


AJAX API Documentation:   api.jquery.com/jQuery.ajax/



Congrats! You have just made a simple JSON data transaction using jQuery's ajax() function call. I hope you enjoyed this tutorial and I look forward to all the comments/suggestions! For all reference material please use the links located at the bottom of this article.



PHP Notes:
What happens on the server side is outside the scope of this tutorial but I think it's important to make a few notes to tie everything together. If you recall, we used "POST" to send the data so we can use  PHP's $_POST[] array inside the PHP script to access all of our JSON data (shown below). In the jQuery example above we return the same data back to the ajax "success" event handler. To accomplish this we would create an array using the $_POST data and "echo" the results returned by the PHP "json_encode()" function (shown below).

//To access the JSON data sent to the server, use the $_POST array. $_POST["cmd"];//Contains the string "High Five".
$_POST["username"];//Contains the string "Jessica".

//Create an array, parse it as encoded JSON data and echo it back to the browser.
$ReturnData = array(
"cmd" => $_POST["cmd"],
"username" => $_POST["username"]
);

echo json_encode( $ReturnData );

For more details regarding the PHP $_POST[] array and the encode_json() function please refer to the following links.

PHP $_POST[] Documentation:   php.net/manual/en/reserved.variables.post.php
PHP encode_json() Documentation:   php.net/manual/en/function.json-encode.php






References

Comments

  1. 1. many peoples want to join random whatsapp groups . On this website you can join unlimited groups . click and get unlimited whatsapp group links

    ReplyDelete
  2. you want girls mobile numbers then this website is best for you . you can visit on this website and get their information and you also can meet with thrm and go for a date . click here to use our website --- 100% free online dating website

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. This information really amazing thanks for share this article thank you..

    good morning shayari

    ReplyDelete
  5. Coinratecap just launched a new modern and faster way to trade and predict price change of bitcoin within 15 secs & win 50% of your stake instantly.In Btc-predict, user predicts price change (LOW or HIGH) by staking any amount within 15secs and win 50% of its stake as price changes.
    REGISTER HERE

    ReplyDelete
  6. There are two paddle rests which keeps your hands free without losing your paddles. A rear cargo area with bungee chord can be used to store your gears or clothing and tie up with a bungee. There are multiple carrying handles makes it easy to transport to or from the water.

    Vibe Skipjack 12oT

    ReplyDelete
  7. Wow! this is Amazing! Do you know your hidden name meaning ? Download CCC Certificate

    ReplyDelete

Post a Comment

Popular posts from this blog

How to Fix RigidBody Stacking Issue - Unity Object Stacking Issue

How to Install Unity Hub QUICKLY - Unity Hub 2020 - Unity Game Engine Tutorial

Get URL Variables With JavaScript