Currently, I cant access the return data from my jquery ajax. Actually, I dont even know if I am sending any data at all? I just need to send data from a form with JSON to php, and get the response as an array.
Thanks for the help.
HTML/JS/jQuery
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<title>Hello World</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="https://github.com/douglascrockford/JSON-js/blob/master/json2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("form").submit(function () {
var uname = document.getElementById("username").value;
var pword = document.getElementById("password").value;
var postData = {
username: uname,
password: pword
};
alert(uname);
$.ajax({
url: "test.php",
type: "GET",
data: postData,
dataType: 'json',
contentType: 'json',
cache: false,
success: function (data) {
alert(data);
}
});
});
});
</script>
</head>
<body>
<form action="">
<input type='text' id="username" name="username" placeholder="Username" />
<br />
<input type='password' id="password" name="password" placeholder="password" />
<br />
<input type="submit" id="submit" value="Login" />
</form>
</body>
PHP
echo json_encode(array(
'username' => $_GET['username'],
'password' => $_GET['password']
));
You are creating a handler for the submit event but it seems that you forgot to return false in order to stop the basic submit process.
A form with an empty action will POST data in the same page (your initial PHP page), so the AJAX call back is sent but just after, you are posting again with basic way.
Add a
return falseat the end of the function (just after your AJAX call) and then your form will not be submitted, the AJAX will be sent and you will see the response.If you are using Firefox, install Firebug and look at the Network tab to see your request sent by the Ajax call and check your JSON response.
Good luck.