JSON encode stopped working?

I tried consolidating code and apparently my ajax login stopped working. When I disable JS, it works perfectly. It reads the PHP and gives appropriate errors, etc. It just doesn’t seem to send the JSON correctly.
The HTML form goes to process-home.php. Below is this file.

<?php
session_start();
require_once($_SERVER["DOCUMENT_ROOT"]."/cadeui/system/includes/bootstrap.php");
if($_SERVER["REQUEST_METHOD"]=="POST")
{
  if(isset($_POST["login"]))
  {
    $email=filter_input(INPUT_POST,"email");
    $password=filter_input(INPUT_POST,"password");
    $remember=filter_input(INPUT_POST,"remember");
    $formData=new UserServices($pdo);
    $isValid=$formData->checkCredentials($email,$password,$remember);
  }
  else if(isset($_POST["subscribe"]))
  {
    $email=filter_input(INPUT_POST,"email");
    $formData=new UserServices($pdo);
    $isValid=$formData->newSubscriber($email);
  }
  $isAjax = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
  if($isAjax)
  {
    $result=["result" => $isValid];
    header("Content-Type: application/json");
    exit(json_encode($result));
  }
  
  if(isset($_POST["login"]))
  {
    if($isValid[0])
      header("Location: http://www.codefundamentals.com/cadeui/dashboard");
    else
      header("Location: http://www.codefundamentals.com/cadeui/login?error=$isValid[1]");
  }
  else if(isset($_POST["subscribe"]))
  {
    if($isValid[0])
      header("Location: http://www.codefundamentals.com/cadeui/index#newsletter#newsletter?result=success");
    else
      header("Location: http://www.codefundamentals.com/cadeui/index#newsletter?error=$isValid[1]");
  }
}
?>

Where it checks for AJAX, that part seems to not be doing its job. If JS is enabled, it uses AJAX to call process-home.js. File below.

This AJAX

$.ajax({
      type: "POST",
      dataType: "text",
      data: {
        'email': user,
        'password':pass,
        'remember':remember
      },
      url: "/cadeui/system/includes/process-home",
      success: function(data) {
        data = JSON.parse(data);alert(data.result);
        if(data.result[0])
          window.location.href="http://www.codefundamentals.com/cadeui/dashboard";
        else
        {
          $(".overlay .loading-bar").remove();
          $(".overlay").css("z-index","9997");
          $("#submit, #email, #password").prop("disabled", false);
          if(data.result[1]==="userpass")
          {
            $("<span id=\"userpass-error\" class=\"error\">Error: Your username or password is incorrect. Please try again.</span>").prependTo("fieldset");
          }
          else if(data.result[1]==="attempts")
          {
            $("<span id=\"attempts-error\" class=\"error\">Error: You have exceeded the maximum number of attempts. Please try again later.</span>").prependTo("fieldset");
          }
          $("#password, #email").removeClass("valid");
        }
      }

Again, this works fine in the PHP version, but not the AJAX version. I alert data.result[0] and I get null. Not sure why it’s just appearing now. I tried looking at past versions but I don’t see what’s different. Can anyone see why this stopped working?
http://www.codefundamentals.com/cadeui/index

When I go do a vardump of json_encode($result), I get the following

string(29) "{"result":[false,"userpass"]}"

Interesting it’s failing at JS…

Check things from the other side, where the problem occurs.

What is the data that the success function receives? Is it valid JSON?

I’m not sure what you mean. I posted a var dump of the json_encode($result) and that’s supposedly valid json.

Exactly what was var dumped is what is being returned to my Javascript, supposedly.

Before I do JSON.parse in the Javascript, I alert(data). I get {“result”:null} . After the parse, I get Object object

Yet data.result[0] is still null…

And you’re doing this “on success”?

Yup. The PHP version works just fine. Just the JS/AJAX one that doesn’t want to cooperate.

So it’s either process-home.php, or process-home.js which is messing up.

Okay, stop right there, You have found a clue about the problem. Don’t go further investigating the scripting until you have the the data that you expect. Garbage in, garbage out, 'n all that.

It’s time to investigate things more fully and find out why you are getting null.

I suggest that you use your Web browsers debugger and find out what is being output from php when the Ajax request occurs.

One of the problems that you will find, is that the boolean false False does not translate well. You may want to use a string or numeric representation of that, such as 0 for false.

Head deep in this. Been working for the past hour on this. I’ve discovered the issue. Am currently figuring out a workaround and will report my findings shortly.

<input type="email" class="envelope" placeholder="Username" id="email" name="loginEmail">
//$email=filter_input(INPUT_POST,"loginEmail");
    $email="admin@codefundamentals.com";

Why does the filter input not allow proper logging in? E.g. it doesn’t recognize the username as correct when I enter in correct details. WHen I hard code the e-mail username in, like this, it works. What makes this filter input return false?

Normally with filter_input we use a sanitize filter, such as FILTER_SANITIZE_EMAIL or FILTER_SANITIZE_STRING
See http://php.net/manual/en/filter.filters.sanitize.php

What does $_POST show before you filter things?

I figure that PHP is more appropriate for this thread so have moved things across to that channel.

Alright, I could write a book about how this whole process went. But just so you all know, it’s fixed. I don’t think I could honestly go through everything I did, so I’ll leave it at that.

You sound like me.
Often with sticky problems, I try this, I try that, I try another thing.
By the time I get things working I’m never quite exactly sure what I did that needed to be done.

Anyway, I’m glad you got it working

Well I remember all the issues, but some of my changes caused other bugs not with the original issue.

I don’t want to bore you all with it :slight_smile: .

Thanks! Kinda killed my evening, but the challenge was worth it. Love these kinda nights where you just tackle an issue until you get it done.

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.