AJAX POST request in JSON login
I'm trying to create a very simple login form using AJAX for server
comunication and PHP as a server-side script. As a starting point I was
just trying to send the login data to the server via JSON, but it already
gave me issues.
Problem is, when I send the data with a POST request in AJAX my server
doesn't seem to get anything and returns no data at all. Here's the HTML
for the request:
<!DOCTYPE HTML>
<html>
<head>
<title> Login experiment </title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(
function AjaxJSON(){
$("form#loginForm").submit(function() {
var username = $('#username').val();
var password = $('#password').val();
var jsonlogin = "{\"username\" : \"" + username + "\" , \"password\" : \""
+ password + "\"}";
var str='json='+jsonlogin;
$.ajax({
type: 'POST',
url: 'login.php', // URL of my PHP script
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: str,
success:function(data){alert("Data received!"+data);}
}); // ajax
}
)
}
)
</script>
</head>
<body>
<h1> LOGIN: </h1>
<form id="loginForm" name="loginForm" method="post" action="">
<input type="text" id="username" name="username"> USERNAME <br>
<input type="password" id="password" name="password"> PASSWORD <br>
<input type="submit" class="button positive">
</form>
</body>
</html>
This HTML code should simply send the request form (username+password)
coded in a JSON string to the PHP script. The script is something like
this:
<?php
$result = json_decode($_POST['json']);
echo $result->username;
echo " ";
echo $result->password;
?>
Why doesn't it show me any reply? Thank you in advance for your help :)
No comments:
Post a Comment