skip to Main Content

The goal of my project is a website that can show a list of addresses that updates without refreshing which means I have to use AJAX. I hope to include Javascript. the current code I have is the following:

<script src="https://code.jquery.com/jquery-3.1.1.min.js">
jQuery(document).ready(function ($) {
    $('#get-data').click(function () {
        var showData = $('#show-data');
        $.ajax({
            type: 'GET',
            url: 'json.json',

        })
    })
})

while looking at the $.ajax() I’ve seen the data parameter often used but I have no clue what it’s purpose is or what I should insert into it. I’ve read multiple documentations yet I still don’t understand what I’m supposed to write in the data parameter. I’ve looked at different StackOverflow questions aswell but they haven’t brought me any further.

It’d be helpful if someone could help me with this. I’m having quite some problems just trying to figure out AJAX Calls in general.

2

Answers


  1. From https://api.jquery.com/jquery.ajax/ :

    Data to be sent to the server. It is converted to a query string, if
    not already a string. It’s appended to the url for GET-requests.
    Object must be Key/Value pairs. If value is an Array, jQuery
    serializes multiple values with same key based on the value of the
    traditional setting.

    Depending on your backend, you can then access this data while processing the request.
    For example if your backend was Laravel (PHP) you could do:

    $request->input('yourDataParameterGoesHere')
    

    And that would give you the data you passed in the ajax.

    Login or Signup to reply.
  2. Here an example

    var par={
             key: value,
             key2: value2,
             key3: [value0of4, value1of4, value2of4]
    };
    $.ajax({
             type: "POST", // GET(Request) or POST(Submit) 
                url: 'https://www.google.it/', //Where your data will go 
                data:JSON.stringify(par), //data parameter
                contentType: "application/json; charset=utf-8",
                dataType: "json", //identify output
                success: function (response) {
                    //This function will run if the ajax call goes on success
                    alert("OK!");
                    //if your function provides a return:
                    var ris = response.d;
                    console.log(ris)//just for a check
                },
                failure: function (response) {
                    alert("failure");
                    var ris = response.d;
                    console.log(ris)
                },
                error: function (response) {
                    alert("error");
                    var ris = response.d;
                    console.log(ris)
                }
            });
    

    If something goes wrong, always check the console

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search