We have seen how JQuery .load() works when we pass a string (i.e. "movie=birdman") as second parameter. The JQuery .load() method will then turn the string parameter/argument into a query string and append to the "url" to make a HTTP GET to the server.

On the other hand, if we pass an object, instead of HTTP GET, the JQuery .load() method is going to make a HTTP POST to server, and expecting some "content" from server so to load into the selected element.

This page is not about whether you should use GET or POST in a particular circumstance. If you are in doubt, you may check out GET vs POST

Object in Javascript

Let's get into the subject of Javascript "object". Object in Javascript has got two meaning. It can be:-

  1. An associative array (it's also know as hash in other programming language). It stores key-value pairs.
  2. Object as in any object-oriented programming language.
The object that we will be passing to .load() as second parameter/argument is the first one.

I'm going to create an object and name it "movie", my "movie" object will have 3 keys and they are "title","year", and "director". I will also assign a value to each key.

var movie = {}; 
movie.title = "birdman"; 
movie.year = 2014; 
movie.director = "Alejandro González Iñárritu";

That is one way of creating object and assigning key/value pairs, check out another way below.

var movie = { 
    title:"birdman",    
    year:2014,         
    director:"Alejandro González Iñárritu"
};

There are 2 ways to get the value of the key. say "obj" is the object and "prop" is the property name.

  1. obj.prop (example: alert(movie.director)).
  2. obj['prop'] (example: alert(movie["director"])).

Anyway, this topic is not so much about Javascript Object but passing object to JQuery .load() method as second parameter/argument.

I am going to use the same emma.php page as the previous topic. Instead of passing a string ('movie=birdman') as second parameter/argument, $("#content").load('http://www.ajax-tutor.com/demo/emma.php','movie=birdman'); I am going to create a object "movie" and pass it as second parameter.

<input id="demo1" type="button" class="button round" value ="Demo1" />

<script>
    var movie = { 
        title:"birdman", 
        year:2014,  
        director:"Alejandro González Iñárritu"
    };

    $("#demo1").click(function() {$("#content").load('http://www.ajax-tutor.com/demo/emma.php',movie);});
</script>
CONTENT

The emma.php page is not designed to return any meaningful content if I send a POST request instead of url with proper query string. The purpose here is to show case JQuery .load() actually makes a HTTP POST request to the server resource.

When we bring up Developer Tool of Google Chrome to examine what happen when I click "Demo1" button.

We can clearly see it was a HTTP POST instead of HTTP GET as in previous topic. It has also sent form data to the server.

Post Data with JQuery .load()