JQuery Ajax with ajax

From CoderLearner
Jump to: navigation, search

Example 1

greeting.php

<?php

if ($_GET) {
	if (!empty($_GET['name']) && !empty($_GET['location'])) {
		printf("%s is from %s", $_GET['name'], $_GET['location']);
	} else {
		echo 'Please try again';
	}
} else {
	echo 'Error Processing!';
}
?>

hello_greeting.html

<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>User Profile List</title>
		<script 
			type="text/javascript" 
			src="jquery.min.js">
		</script>
		<script type="text/javascript" language="javascript">
			$(document).ready(function() {
				$.ajax({
					url: 'greeting.php',
					type:'GET',
					data:'name=Bob Maat&location=Huntsville,Tx',
					success:function(data){
						$('#content').html(data);
					}
				});
			});
		</script>
	</head>
	<body>
		<div id="content"></div>
	</body>
</html>

$.get() vs. $.ajax()

  • $.get() and $.ajax() get the same result.
  • $.get() is the short-cut of $.ajax({type:'GET'....}).
$.get('SOMEURL.php',
  {name:'Bob Maat',location:'Huntsville,Tx'}
  ,function(data){
  $('#content').html(data);
});
$.ajax({
  url: 'SOMEURL.php',
  type:'GET',
  data:'name=Bob Maat&location=Huntsville,Tx',
  success:function(data){
	$('#content').html(data);
  }
});

$.post() vs. $.ajax()

  • $.post() and $.ajax() get the same result.
  • $.post() is the short-cut of $.ajax({type:'POST'....}).
$.post('SOMEURL.php',
  {name:'Bob Maat',location:'Huntsville,Tx'}
  ,function(data){
   $('#content').html(data);
});
$.ajax({
  url: 'SOMEURL.php',   
  type:'POST',
  data:'name=Bob Maat&location=Huntsville,Tx',
  success:function(data){
  $('#content').html(data);
  }
});

$.post() vs. $.ajax() for json data

  • $.post(URL,{},function(){},'json') and $.ajax({URL,type:'POST',data:,dataType:'json',success:function(data){}}) get the same result.
  • $.post(URL,{},function(){},'json') is the short-cut of $.ajax({type:'POST',dataType:'json'....}).
$.post('SOMEURL.php',
  {name:'Bob Maat',location:'Huntsville,Tx'}
  ,function(data){
   // json data response
   $('#content').html(data);
},'json');
$.ajax({
  url: 'SOMEURL.php',   
  type:'POST',
  dataType:'json',
  data:'name=Bob Maat&location=Huntsville,Tx',
  success:function(data){
  // json data response
  $('#content').html(data);
  }
});

$.getJSON() vs. $.ajax()

  • $.getJSON() is the short-cut of $.ajax({type:'JSON'....}).
  • Expect the response data is JSON data.
$.getJSON('SOMEURL.php',
    {name:'Bob Maat',location:'Huntsville,Tx'}
    ,function(data){
    // json data response
    $('#content').html(data);
});
$.ajax({
  url: 'SOMEURL.php',   
  dataType:'JSON',
  type:'GET',
  data:'name=Bob Maat&location=Huntsville,Tx',
  success:function(data){
  // json data response
  $('#content').html(data);
  }
});