Skip to content Skip to sidebar Skip to footer

Custom Json Error Response Fails When No Error

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 th

Solution 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 errorif ($name_error == true && $email_error == false)
    {
        $response['text'] = "Sorry, the name you entered is already in use.";
    }
    // JSON email errorif ($name_error == false && $email_error == true)
    {
        $response['text']  = "Sorry, the email you entered is already in use.</p>";
    }
    // JSON name & email errorif ($name_error == true && $email_error == true)
    {
        $response['text']  = "Sorry, both the name and email you entered are already in use.";
    }
    // JSON no errorif ($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);
      }
    }

Solution 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 onalert("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.

Post a Comment for "Custom Json Error Response Fails When No Error"