RSS

Send JSON via AJAX request

04 Jul

This tutorial demonstrates how to make an AJAX request in javaScript and process JSON in PHP. The data sent by the HTTP Post request is used to create a session after JSON decoding finished.

For this, we need following .js file.

https://github.com/douglascrockford/JSON-js/blob/master/json2.js

function abc()
{
var jsonObj = {"lat": 56  ,"long": 78  ,"city": 'Wohiyo' };

// Lets convert our JSON object
var postData = JSON.stringify(jsonObj);

// Lets put our stringified json into a variable for posting
var postArray = {json:postData};

$.ajax({
type: 'POST',
url: "Server.php",
data: postArray,
success: function(data){
alert("success");
}
});
}

Server.php

<?php
 session_start();
 header("Expires: Mon, 26 Jul 2000 05:00:00 GMT");
 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
 header("Cache-Control: no-cache, must-revalidate");
 header("Pragma: no-cache");

if(isset($_POST["json"])){
 $json = stripslashes($_POST["json"]);
 $output = json_decode($json);

$_SESSION['city'] = $output->{'city'};
 }
 ?>

complete source code

<?php session_start();?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
<script src="jquery-1.7.js"></script>
<script src="json2.js"></script>

<script type="text/javascript">
function abc()
{
var jsonObj = {"lat": 56  ,"long": 78  ,"city": 'Wohiyo' };

// Lets convert our JSON object
var postData = JSON.stringify(jsonObj);

// Lets put our stringified json into a variable for posting
var postArray = {json:postData};

$.ajax({
type: 'POST',
url: "Server.php",
data: postArray,
success: function(data){
alert("success");
}
});
}
</script>
</head>

<body onLoad="abc()">
<?php echo $_SESSION['city'];?>
</body>
</html>
Advertisements
 
Leave a comment

Posted by on July 4, 2012 in JavaScript, PHP

 

Tags: ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: