I am using AJAX to make a call to a validation script. On return of $response I keep getting the error SyntaxError: Unexpected end of JSON input. I wouldn't be surprised if I am not returning my data properly formatted as JSON, but now I've run the response { "loggedIn": false } in a JSON parser and it seems valid. What am I doing wrong?
ajaxexample.php
<form method="post" name="login">
<input type="text" name="username" > Email/Username: <br>
<input type="password" name="password" > Password: <br>
<input type="submit">
</form>
<div id="content"></div>
</body>
</html>
<script>
$(document).on( 'submit', $("#login"), function(event){
event.preventDefault();
var formData = '{"login":[ {'+
'"username":"'+$('input[name="username"]').val()+'",'+
'"password":"'+$('input[name="password"]').val()+'"'+
'}]}';
var formData = JSON.parse(formData);
// Using the core $.ajax() method
$.ajax({
// The URL for the request
url: "users/validate.php",
// The data to send (will be converted to a query string)
data: formData,
// Whether this is a POST or GET request
type: "POST",
// The type of data we expect back
dataType : "json",
})
// Code to run if the request succeeds (is done);
// The response is passed to the function
.done(function( data ) {
$( "<div class=\"content\">").html( JSON.stringify(data) ).appendTo( "body" );
})
// Code to run if the request fails; the raw request and
// status codes are passed to the function
.fail(function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem!" );
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr.responseText );
})
// Code to run regardless of success or failure;
.always(function( xhr, status ) {
});
});
</script>
validate.php
<?php require_once '../users/init.php';?>
<?php
if(isset($_POST))
{
$username = $_POST['username'];
$password = $_POST['password'];
$validate = new Validate();
$validation = $validate->check($_POST, array(
'username' => array('display' => 'Username','required' => true),
'password' => array('display' => 'Password', 'required' => true)));
if ($validation->passed())
{
$user = new User();
$login = $user->loginEmail($username, $password, $remember);
$response = array('loggedIn'=>$login);
echo json_encode($response, JSON_PRETTY_PRINT );
}
}
else
{
echo json_encode("No data.");
}
?>
?>til<?php. and the trailing?>echo json_encode("No data.");will not be valid json, but only a stringjson_encode("No data.");will give you"No data.", whichJSON.parsewill accept with no problem and give youNo data.back.$(document).on( 'submit', $("#login")should be$(document).on( 'submit', "#login"validate.phpwas expecting normal form data, not a JSON object.