1

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.");
    }
?>
5
  • might not be exactly the problem, but you should get rid of the extra linefeed at the top -> remove ?> til <?php. and the trailing ?> Commented Nov 15, 2018 at 16:48
  • echo json_encode("No data."); will not be valid json, but only a string Commented Nov 15, 2018 at 16:48
  • 1
    json_encode("No data."); will give you "No data.", which JSON.parse will accept with no problem and give you No data. back. Commented Nov 15, 2018 at 17:01
  • $(document).on( 'submit', $("#login") should be $(document).on( 'submit', "#login" Commented Nov 15, 2018 at 17:05
  • validate.php was expecting normal form data, not a JSON object. Commented Nov 15, 2018 at 17:14

3 Answers 3

2

There are several issues I see there

Firstly the data you're sending is in the wrong format and also creating a json string then parsing it to an object is unnecessary when you can just create the object in the first place.

var formData = {
                 "username": $('input[name="username"]').val(), 
                 "password": $('input[name="password"]').val()
               };

And secondly, since your data is in the wrong format $validation->passed() is going to be false and you will return no data in the request, which expects json and will give the error you see when it doesn't get any.

    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(array('loggedIn'=>false), JSON_PRETTY_PRINT );
    }

Also, the selector for you form submit handler is wrong, it should be something like

$(document).on( 'submit', "[name=login]", function(event){
Sign up to request clarification or add additional context in comments.

1 Comment

"creating a json string then parsing it to an object is unnecessary"... I'd go further and say it was just bonkers :-)
0

You may want to send a content-type header at the top of your script inside the php tags

header('content-type: application/json');

you maybe outputting extra characters you can try to output buffer like this:

<?php

ob_start();
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);
        ob_clean();
        echo json_encode($response, JSON_PRETTY_PRINT );
        ob_flush();
    }
}
else
{
    ob_clean();
    echo json_encode("No data.");
    ob_flush();
}

1 Comment

If there were extra characters in the output you would get a different error like Uncaught SyntaxError: Unexpected token . in JSON at position 10
-1

validate.php was not expecting a JSON object, but rather just form data in a POST.

<html>
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<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();


    // 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: {"username":$('input[name="username"]').val(),
            "password":$('input[name="password"]').val()
    },

    // 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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.