Reputation: 5800
I am trying to post data and receive response using jQuery Ajax Post and I am not sure why my code is not working.
<script>
$(document).ready(function(){
$('#login').click(function(){
$.ajax({
type: 'POST',
url: 'http://code.com/backend/test3',
dataType: 'json',
data: {"username":"akllkkj","password":"kljjkjkl"},
cache: false,
success: function(data){
console.log(data.stack);
console.log(data.key);
},
error:function(){
alert("failure");
}
});
return false;
});
});
</script>
<form autocomplete="off" class="ui fluid form segment" method="post">
<div class="ui fluid form segment">
<div class="two fields">
<div class="field">
<label>Email/Username</label>
<input placeholder="Email/Username" name="username" id="username" type="text">
</div>
<div class="field">
<label>Password</label>
<input placeholder="Password" name="password" id="password" type="password">
</div>
</div>
<input type="button" class="ui fluid submit button" name="dosubmit" value="Submit" id="login" />
</div>
</form>
And my test3
page contains:
<?php
if(isset($_POST['username']) && isset($_POST['password'])) {
$arr = array(
'stack'=>'overflow',
'key'=>'value'
);
echo json_encode($arr);
}
?>
Upvotes: -1
Views: 67
Reputation: 1508
Try this. It will work.
<script type="text/javascript">
$(document).ready(function(){
$('#login').click(function(){
$.ajax({
type: 'POST',
url: 'http://code.com/backend/test3.php',
dataType: 'json',
data: {"username":"akllkkj","password":"kljjkjkl"},
async: true,
success: function(data){
var obj = jQuery.parseJSON(data);
if(obj)
{
for(i=0;i<obj.length;i++) {
console.log(obj[i].stack);
console.log(obj[i].key);
}
} else {
console.log("Empty Result");
}
},
error:function(){
alert("failure");
}
});
});
});
<script>
And you test3.php script will be:
<?php
$arr=array();
if(isset($_POST['username']) && isset($_POST['password'])) {
$arr[] = array(
'stack'=>'overflow',
'key'=>'value'
);
}
echo json_encode($arr);
?>
Upvotes: 0
Reputation: 708
This has worked for me:
$('#form').submit(function (event) {
event.preventDefault();
var data = $('#form').serialize();
$.ajax({
type: 'post',
dataType: 'json',
data: data
}).done(function (resp) {
console.log(resp);
});
});
And on the php side of things, you may need something like this:
header('Content-Type: application/json');
echo json_encode($arr);
Upvotes: 1