Jquery problem in handling ajax data coming as array

Asked

Viewed 220 times

2

My array returns from php like this (post):

Array
(
    [0] => Array
        (
            [O email digitado é invalido! Por favor insira um email correto.] => 1
        )

    [1] => Array
        (
            [O telefone digitado está num formato invalido por favor siga o modelo: (DDD) XXXX-XXXX] => 1
        )

    [2] => Array
        (
            [Sua senha deve ser maior que 4 caracteres e menor que 20] => 1
        )

)

My goal is to have Jquery use the main array to identify the phrase ex:

1. The Email typed is... 2. The Telephone typed is... 3. Your password must be....

And the internal array of the message identifies the type of css I’m going to use. 1 - severe error, 2- common error, 3-hit. I just don’t know how to do it. When I try to use a foreach, I come across an error in lenght, which returns Undefined. All help is welcome...

============ PHP CODE ================

<?php
$jq = filter_input_array(INPUT_POST, FILTER_DEFAULT);

if($jq['acao'] == 'cadastro'):
    unset($jq['acao']);
    require ('../_app/Models/Cadastro.class.php');
    require '../_app/Config.inc.php';

    $cadastra = new Cadastro;
    $cadastra->ExeCadastro($jq);

    if(!$cadastra->getResult()):
        print_r($cadastra->getError());
    else:
        print_r($cadastra->getResult());
    endif;
endif;

PHP receives from jquery the data of the fields stores via post in the variable jq and sends it to the class.

============== PHP CLASS =====================

private function CheckData() {
    if (!Check::Email($this->Data['email'])):
        $this->Result = FALSE;
        $this->Error[] = ["O email digitado é invalido! Por favor insira um email correto." => 1];
    endif;
    if (!Check::Telefone($this->Data['telefone'])):
        $this->Error[] = ["O telefone digitado está num formato invalido por favor siga o modelo: (DDD) XXXX-XXXX" => 1];
        $this->Result = FALSE;
    endif;
    if (strlen($this->Data['senha']) < 5 || strlen($this->Data['senha']) >= 20):
        $this->Error[] = ["Sua senha deve ser maior que 4 caracteres e menor que 20" => 1];
        $this->Result = FALSE;
    endif;
}

private function CheckCadastro() {
    $CheckExistUser = new Read;
    $CheckExistUser->ExeRead('cadastro', "WHERE email = :e", "e={$this->Data['email']}");

    if ($CheckExistUser->getResult()):
        $this->Error[] = ["O email {$this->Data['email']} já está cadastrado no sistema. Se você for ... clique aqui. Se não tente um outro email" => 1];
        $this->Result = FALSE;
    endif;
}

The class is a little bigger but, follow this principle. If you have an error in the data you received, store it in $this->Error and don’t let you continue to register in the database. As you can see in PHP I recover the error by $register->getErro, if you sent a print_f to print the message. My goal now is to handle the message I received to display to the customer. So that the main array is the error amount identifier and the internal action of the message identifies the type, if it is 1 is an error, I will see by the number the type and identify which css I will use to send the final message.

  • You shouldn’t use values as keys.

  • Puts your source code in both PHP and jQuery, which makes it easy.

  • I put an excerpt see there! :)

  • You shouldn’t return the data with a print_r. Uses a json_encode, that generates a javascript object. Type: echo json_encode($cadastra->getResult())

2 answers

1

Use the foreach.

   $.each(array, function( index, value ) {
         alert( index + ": " + value );
   });

1

Do you have access to PHP code? The best (and simplest) way to handle this data is to prepare it for javascript using the function json_encode($array);. Now otherwise you will have to use regular Xpression and you will lose performance and integrity on this data.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.