0

When I was trying to recieve a code from PHP page using jQuery Ajax, I found a strange error: "Undefined variable: errors"

<?php
$errors = array("already_signed" => "You are already signed in", "field_empty" => "All fields must be filled", "long_username" => "Username length must be less then 40 symbols", "incorrect_email" => "Your mail is incorrent", "user_exists" => "User with such username already exists", "account_not_found" => "Account not found", "passwords_arent_same" => "Passwords must be the same");
Function check_post() {
    $answer = array("ok" => "false", "answer" => $errors["field_empty"]);
    echo json_encode($answer);
}

check_post();
?>

If I'll echo without function - everything will be ok. Thanks for any help

4
  • Also, quick question, in PHP shouldn't Function be function? php.net/manual/en/language.functions.php Commented Aug 24, 2011 at 18:55
  • "Undefined variable: errors"? PHP Commented Aug 24, 2011 at 18:55
  • 1
    @oscar: php function names and keywords are case insensitive. variables, on the other hand, are case sensitive. Commented Aug 24, 2011 at 18:57
  • @marc awh, didn't know. Strange Commented Aug 24, 2011 at 19:06

2 Answers 2

4

You seem to be missing at least one } in there. As is, your function definition has no close, so it reads as an infinitely recursive call.

As well, you've got $errors being defined OUTSIDE of your function. PHP does not allow "lower" code scopes to see variables defined in higher scopes. You need to declare $errors as a global within the function:

<?php

$errors = array(....);
function check_post() {
   global $errors;
   $answer = ...
   ...
}

check_post();
0
3

You are trying to access a global variable from within the function. In order to acomplish that, you need to use "global" keyword:

<?php
$errors = array("already_signed" => "You are already signed in", "field_empty" => "All fields must be filled", "long_username" => "Username length must be less then 40 symbols", "incorrect_email" => "Your mail is incorrent", "user_exists" => "User with such username already exists", "account_not_found" => "Account not found", "passwords_arent_same" => "Passwords must be the same");
function check_post() {
    global $errors;
    $answer = array("ok" => "false", "answer" => $errors["field_empty"]);
    echo json_encode($answer);
}
check_post();
?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.