Kill and respond JSON with PHP

0

My framework submits forms with a fixed concatenation stating the type of data, what validation it should pass, the field name in relation to the table in the DB, and the value, would look something like:

data[0][]company_razao_social::Empresa::company_name::text::undefined

There is a class that explodes the string and assembles an array to check:

  {
        $arr = [];
        $key = 0;
        //print_r($_POST);
        foreach ($POST['data'] as $row)
        {
            $data = $row[0];
            $EXP = explode('::', $data);
            $label = $EXP[0];
            $value = $EXP[1];
            $validation = $EXP[4];
            if ($label == 'password')
            {
                $arr[$key][$label] = sha1($value); 
            } else
            {
                $arr[$key][$label] = utf8_encode(\vidbModel\validate::get_rs($value,$validation));
            }
            $key += 1;
        }
        return $arr;
    }

This returns an array:

If it has been validated:

$data['company_razao_social'] = 'Valor do campo';

Or, if it was not:

$data['company_razao_social'] = 'O campo não foi validado (Aqui vem a resposta de não ter sido)';

The problem with this is to treat the client with the error when there is some.

What I want is:

  

Kill the function, and return a json with the error only when the data does not pass the validation, instead of continuing and returning the whole form with all the errors that have occurred and having to treat all this client side.

//Dentro do loop para desconcatenar
{
    $arr[$key][$label] = utf8_encode(\vidbModel\validate::get($value,$validation));
    if($$arr[$key][$label] = 'Possui erro'){
        die('devolver um json aqui');
    }
}

That way, the answer does not come from json, and I'm not able to return json with die, is there another way to kill the method and return it? .

Note: break does not work either.

    
asked by anonymous 18.09.2017 / 15:34

1 answer

2

A little confusing, but I think it would look something like:

//Dentro do loop para desconcatenar
{
    $arr[$key][$label] = utf8_encode(\vidbModel\validate::get($value,$validation));
    if($$arr[$key][$label] = 'Possui erro'){
        header('Content-Type: application/json');
        echo json_encode(["erro" => "Mensagem de erro"]);
        die();
    }
}

So, the header function sends the proper HTTP header indicating that the response will be a JSON, echo defines what the HTTP response body will be, using the json_encode function to simplify, the die function would kill the process, ending execution.

    
18.09.2017 / 15:41