I am new to PHP and JavaScript development, I am trying to execute this code but it fails:
<?php
if(isset($_POST['username']) and isset($_POST['password'])) {
// do logic for logining in (usually query your db)
if ($_POST['username'] == 'test' && $_POST['password'] == 'test') {
$data['success'] = true;
$data['message'] = 'Login succesful';
} else {
$data['success'] = false;
$data['message'] = 'Login failed';
}
// return json
echo json_encode($data);
}
?>
Here is the JavaScript file:
<script>
$(document).ready(function() {
alert("dddd");
$('#loginForm').submit(function() {
$('#output').html('Connecting....');
var postTo = 'http://localhost/Login/login.php';
alert(postTo);
$.post(postTo,{username: $('[name=username]').val() , password: $('[name=password]').val()} ,
function(data) {
if(data.message) {
alert(data);
} else {
$('#output').html('Could not connect');
}
},'json');
return false;
});
});
</script>
Please help.
Funnily enough it works for me in Firefox. I had the problem with IE a while back and the solution was to add the correct headers to the top of the php script:
EDIT: Reproduced it by calling it from another machine. try to change
var postTo = 'http://localhost/test/test.php';tovar postTo = 'test/test.php';.here’s what I tested with ( I woud recommend you use firebug and console.log() instead of alert()):