skip to Main Content

When I call the function I always get an undefined value, I don’t understand what can ruin it.

You are logged in as undefined, Error undefined

Ajax script:

function Submit() {
   console.log('asd')

   $.ajax({
       url: "Server.php",
       type: "POST",
       dataType: "json",
       data: {
          name: "Test2",
          email: "[email protected]"
       },
       success: function(data, textStatus, jqXHR) {
          console.log("You are logged in as: ", data.name);
          $('#user').html("You are logged in as: " + data.name);
       },
       error: function(request, error, data) {
          console.log(arguments);
          alert(" Can't do because: " + error + " DATA: " + data);
       }
   })
}

PHP Script:

<?php
header("Content-type: application/json; charset=utf-8");

$errors = [];
$data = [];

if (empty($_POST['name'])) {
    $errors['name'] = 'Name is required.';
}

if (empty($_POST['email'])) {
    $errors['email'] = 'Email is required.';
}

if (!empty($errors)) {
    $data['success'] = false;
    $data['errors'] = $errors;
} else {
    $data['success'] = true;
    $data['message'] = 'Success!';
    $data['name'] = $_POST['name'];
}
echo json_encode($data);
?>

I tried every solution in vain, so I still get an indefinite value. I’m slowly starting to think there’s nothing wrong with the script.

2

Answers


  1. You want to use data.name but you never return name. hence the undefined.
    I’ve added data.name in the example below and it seems to work fine.

    <?php
    header("Content-type: text/html; charset=utf-8");
    
    $errors = [];
    $data = [];
    
    if (empty($_POST['name'])) {
        $errors['name'] = 'Name is required.';
    }
    
    if (empty($_POST['email'])) {
        $errors['email'] = 'Email is required.';
    }
    
    if (!empty($errors)) {
        $data['success'] = false;
        $data['errors'] = $errors;
    } else {
        $data['success'] = true;
        $data['message'] = 'Success!';
        $data['name'] = $_POST['name'];
    }
    
    echo json_encode($data);
    ?>
    

    Also the parameters used in the succes function are in a different order than you seem to use, in your case the request will have your data in it

    Login or Signup to reply.
  2. the callback parameter not

    success:function(request, data, error)
    

    but

    success: function(data, textStatus, jqXHR)
    

    data.name of course undefined because it is string

    and your Server.php return this

    {"success":true,"message":"Success!"}
    

    no data.name but data.success and data.message

    so you have to write

    if (!empty($errors)) {
        $data['success'] = false;
        $data['errors'] = $errors;
    } else {
        $data['success'] = true;
        $data['message'] = 'Success!';
        $data['name'] = $_POST['name']; // add this
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search