Wednesday, July 4, 2012

Send JSON via AJAX request

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

[sourcecode language="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");
}
});
}
[/sourcecode]

Server.php

[sourcecode language="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'};
}
?>

[/sourcecode]

complete source code

[sourcecode language="html"]
<?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>
[/sourcecode]

No comments:

Post a Comment

How to enable CORS in Laravel 5

https://www.youtube.com/watch?v=PozYTvmgcVE 1. Add middleware php artisan make:middleware Cors return $next($request) ->header('Acces...