0

This is a new area for me.

I've created custom JSON error outputs to alert users if they enter a name and/or an email which already exists. I'm trying to spit out the errors and then if no error exists, continue. Unfortunately I'm getting the following message in Firefox console: "Uncaught SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 2 column 1 of the JSON data." It's weird as I have 3 JSON error variations set up which are working (1 name, 2 email,3 name & email) but only when none of those conditions are met does it fail.

I slimmed down the code as much as possible below. It has been tested multiple times, everything else is working except for the above issue.

THE HTML FORM

<form method='post' id='part03'>
  <input type='text' id='name' placeholder='Enter your name'>
  <input type='email' id='email' placeholder='Enter your email'>
  <input type='button' id='submit'>
</form>

PHP

<?php
header('Content-type: application/json');

// Get name & check if exists
$name = mysqli_real_escape_string($con_usr_pub, $_POST['name']);
$check_name = mysqli_query($con, "select name from table where name='$name'");
if (mysqli_num_rows($check_name) > 0)
{
    $name_error = true;
}
else
{
    $name_error = false;
}

// Get email & check if exists
$email = mysqli_real_escape_string($con_usr_pub, $_POST['email']);
$check_email = mysqli_query($con, "select email from table where email='$email'");
if (mysqli_num_rows($check_name) > 0)
{
    $name_error = true;
}
else
{
    $name_error = false;
}

// JSON name error
if ($name_error == true && $email_error == false)
{
    $response = "Sorry, the name you entered is already in use.";
}
// JSON email error
if ($name_error == false && $email_error == true)
{
    $response = "Sorry, the email you entered is already in use.</p>";
}
// JSON name & email error
if ($name_error == true && $email_error == true)
{
    $response = "Sorry, both the name and email you entered are already in use.";
}
// JSON no error
if ($name_error == false && $email_error == false)
{
    $response = "continue";
}

echo json_encode($response);
?>
 

JS

// AJAX - Name & Email
$(document).on('click', '#submit', function() {
  var name = $("#name").val();
  var email = $("#email").val();
  $.ajax({
    url: "myserverfile.php",
    method: "POST",
    data: {
      name: name,
      email: email
    },
    dataType: "text",
    success: function(response) {
      var json = $.parseJSON(response);
      if (json === "continue") {
        alert("YES");
      } else {
        alert(json);
      }
    }
  });
});

Used: jQuery 3.4.1 PHP 7.4

Vivek Jain
  • 2,730
  • 6
  • 12
  • 27
SJacks
  • 408
  • 3
  • 19
  • 1
    Open up your browser's developer tools and look at the response from the request. See if there are any odd characters there. – aynber Aug 21 '20 at 17:47
  • [Little Bobby](http://bobby-tables.com/) says [you may be at risk for SQL Injection Attacks](https://stackoverflow.com/q/60174/). Learn about [Prepared Statements](https://en.wikipedia.org/wiki/Prepared_statement) with [parameterized queries](https://stackoverflow.com/a/4712113/5827005). – GrumpyCrouton Aug 21 '20 at 17:51

2 Answers2

0

The issue is that you're using dataType: text when you expect a JSON response and are returning strings encoded as json from your backend, instead, use ``dataType: json` and on the backend, JSON encode an array like:

    $response=[];

    // JSON name error
    if ($name_error == true && $email_error == false)
    {
        $response['text'] = "Sorry, the name you entered is already in use.";
    }
    // JSON email error
    if ($name_error == false && $email_error == true)
    {
        $response['text']  = "Sorry, the email you entered is already in use.</p>";
    }
    // JSON name & email error
    if ($name_error == true && $email_error == true)
    {
        $response['text']  = "Sorry, both the name and email you entered are already in use.";
    }
    // JSON no error
    if ($name_error == false && $email_error == false)
    {
        $response['text']  = "continue";
    }

    echo json_encode($response);

And then change your success method to:

dataType: "json",
success: function(response) {
      var json = $.parseJSON(response);
      if (json.text === "continue") {
        alert("YES");
      } else {
        alert(json.text);
      }
    }
Wesley Smith
  • 19,401
  • 22
  • 85
  • 133
  • Thanks for the example, I tried this but there's an error: "Uncaught SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 2 column 1 of the JSON data" same thing is happening when the 3 conditions are not met. Not sure what's going on. – SJacks Aug 21 '20 at 18:29
  • @SJacks ah, please change `dataType: "text",` to `dataType: "json",` – Wesley Smith Aug 21 '20 at 18:47
  • 1
    PS: `var json = $.parseJSON(response);` is not needed when `dataType: "json"` is set, as `response.text` will already exist to use. – IncredibleHat Aug 21 '20 at 19:05
  • @WesleySmith that stopped everything working. I messed around some more after looking at jQuery info on JSON parse and have it working now. Thanks for trying to help :) – SJacks Aug 21 '20 at 19:07
0

Figured it out after looking at jQuery documentation and altering my variable name to "e" instead of "json".

Working JS

 // AJAX - Name & Email
 $(document).on('click','#submit',function() {
 var name=$("#name").val();
 var email=$("#email").val();
 $.ajax({
 url:"myserverfile.php",
 method:"POST",
 data:{name:name,email:email},
 dataType:"text",
 success:function(response) {
 var e = jQuery.parseJSON(response);
 if (e == "continue") {
 // Continue on
 alert("YES");
 } else {
 alert(e);
 }
 }
 });
 });

Note: There was a slight issue with it being a bit slow/unresponsive (pun not intended) - I've fixed this by removing json array in php as it wasn't required.

SJacks
  • 408
  • 3
  • 19