jQuery how to load a url into an element

jQuery .load() can be used to make an Ajax call (GET or POST) and load the results into an element by settings result into its html content. Note that Ajax returned value should be an html for this.

syntax:

$(selector).load( url [, data ] [, callback ])

jQuery load – GET request

We’ll pass no data param to jQuery .load()

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

<div id="result" style="background-color:lightgray"></div>

<script type="text/javascript">
$("#result").load("/api/get-dump.php?param1=val1");
</script>
refresh

jQuery load – POST request

We’ll pass data param object to jQuery .load()

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

<div id="result" style="background-color:lightgray"></div>

<script type="text/javascript">
$("#result").load("/api/post-dump.php", {param1: "val1"});
</script>
refresh

Few points to note

  1. .load() method uses GET request when no data is passed. It also use GET request if serialized string (e.g. "param1=val1") is passed as data.
  2. .load() method uses HTTP POST method if data is passed as object or Array. Even for empty object, it uses HTTP POST method.
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments