Custom JSON error response fails when no error

♀尐吖头ヾ 提交于 2021-01-29 18:00:28

问题


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


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/63527595/custom-json-error-response-fails-when-no-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!