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]
Subscribe to:
Post Comments (Atom)
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...
-
< Requirements Java Development Kit (JDK) NetBeans IDE Apache Axis 2 Apache Tomcat Server Main Topics Setup Development Environ...
-
Download Sourcecode [sourcecode language="csharp"] using System; using System.Collections.Generic; using System.Linq; using System...
No comments:
Post a Comment