$.ajax()

AJAX - with .ajax() - EasyProgramming.net

by nicolas tenorio

HTML

<!-- Easy jQuery - Learn AJAX - how to use .ajax() - #15 -->
<p>
    Welcome to the 15th Easy jQuery Tutorial, part of <a href="http://www.easyprogramming.net">EasyProgramming.net</a>. Today we take a step forward and learn about $.ajax() which I believe will give you more control. We will build on the last tutorial and get our Heroes data and output into a table. 
</p>

<p>
$.ajax() example:</p>
<pre>
  $.ajax({
		url: 'easyprogramming.net',
		method: 'GET',
		dataType: 'json',
		data: {
		  testData: 'testdata'
		},
		success: function(result) {
		  //do something with result
    }
  });
</pre>
<p>
The method can be changed to any of the HTTP methods. The dataType can be JSON, Text, HTML, XML, or simply left out. The data is in json format, something that gets passed through the URL on GET requests and through the body on other requests. And the success function is to catch the returning data. 
</p>
<p>
We'll get our Heroes data again and store it into a table.
</p>

<h2>
    Let's practice:
</h2>
<table id="heroesTable">
	<thead>
		<th>Name</th>
		<th>Superhero Name</th>
		<th>City</th>
	</thead>
	<tbody id="heroesBody"></tbody>
</table>

<br><br><br><br><br><br><br>

CSS

#heroesTable {
	border: 1px solid #dddddd;
	width: 100%;
    margin-bottom: 20px;
}

JavaScript

$.getJSON('http://wsmio.siur.com.co:8083/apiMIO/jaxrs/pevrs', function(data){
	/* console.log(data); */
  $(data).each(function(i, hero){
  	$('#heroesBody').append($("<tr>")
    	.append($("<td>").append(hero.name))
      .append($("<td>").append(hero.superheroName))
      .append($("<td>").append(hero.city)));
  });
})
	.done(function(){
		alert("Completed");
	})
	.fail(function(e){
		console.log('error:');
		console.error(e);
	})
	.always(function(){
		alert("always runs");
	});


$.ajax({
	url: 'https://www.easyprogramming.net/heroes.json',
	method: 'get',
	dataType: 'json',
	data: {
		test: 'test data'
	},
	success: function(data) {
		/* console.log(data); */
		$(data).each(function(i, hero){
			$('#heroesBody').append($("<tr>")
									.append($("<td>").append(hero.name))
									.append($("<td>").append(hero.superheroName))
									.append($("<td>").append(hero.city)));
		});
	}
});

/* 	.done(function(){
		alert("Completed");
	})
	.fail(function(e){
		console.log('error:');
		console.error(e);
	})
	.always(function(){
		alert("always runs");
	}); */