skip to Main Content

I am encoding an array in JSON format before sending data to my HTML page with PHP then I am echoing out the result so I can get it with Ajax.

Here is the controller that does so


if(!isset($_SESSION))
{
    session_start();
}

class ProjectController
{

    private $User;
    private $project;
    private $lists;
    private $param=[];



    public function load(){
        $this->User=$_SESSION['User'];

        $this->project=$this->User->getPrjAt($_SESSION['NomeP'])[0];

        $this->lists=$this->project->loadLists();

        $this->prepare();

        $this->encode($this->lists);
        return view('progetto',$this->param);

    }

    private function prepare(){
        $this->param['Nome_utente']=$this->User->getName();
        $this->param['Liste']=$this->lists;
        $this->param['Nome_progetto']= $this->project->getName();

    }

    public function view($id){
        $this->project=App::get('query')->selectWhereSingle('Progetti',"id_proj='{$id['proj_id']}'",'Progetto')[0];
        $this->lists=$this->project->loadLists();
        $this->lists= $this->order($this->lists);

        $this->param['Liste']=$this->lists;
    $this->param['Nome_progetto']= $this->project->getName();
    $_SESSION['id_proj']=$this->project->getId();
        $this->encode($this->lists);

        return view('progetto',$this->param);


    }

    public function delete($id){
        App::get('query')->delete('Progetti',"id_proj='{$id['proj_id']}'");
        header('Location: /user/home');

    }

    public function Add(){
        $data=[
            'Scala'=>$_POST['priority'],
            'cod_proj'=>$_SESSION['id_proj'],
            'nome'=>$_POST['NomeLista']
        ];
        if($_POST['NomeLista']==''){
            $data['nome']='Untitled';
        }
        else
            $data['nome']=$_POST['NomeLista'];
        App::get('query')->insert('Liste',$data);
        $this->encode($this->lists);

        header("Location: /user/project/view/?proj_id={$_SESSION['id_proj']}");

    }

 private function order($arr){
    $num=count($arr);
    $support=0;
    for($i=0; $i<$num;$i++){
        for($j=0; $j<$num-1;$j++){
            if($arr[$j]->getScala()>$arr[$j+1]->getScala()){
                $support=$arr[$j];
                $arr[$j]=$arr[$j+1];
                $arr[$j+1]=$support;
            }
        }
    }
    return $arr;
 }


 public function Share(){

        $email=$_POST['usrEmail'];
        $usr= App::get('query')->selectWhereSingle('Utenti',"email='{$email}'",'User')[0];

        if($usr==null){
            header("Location: /something-went-wrong");

        }
        else {
            $usr_id=$usr->getId();
            $proj=App::get('query')->selectWhereSingle('Progetti', "id_proj='{$_POST['proj_id']}'",'Progetto')[0];

            $data = [
                'cod_utente' => $usr_id,
                'NomeProj' => $proj->getName()

            ];

            App::get('query')->insert('Progetti',$data);
            header("Location: /success");

        }



 }



 public function Modify(){
        $nome=$_POST['newName'];
        $id=$_POST['proj_id'];

        $proj=App::get('query')->selectWhereSingle('Progetti', "id_proj='{$id}'",'Progetto')[0];

     App::get('query')->modify($nome,'NomeProj', 'Progetti',"id_proj='{$id}'");
     header("Location: /user/home");

 }
private function encode($lists){
        $enc_arr=[];

        for($i=0; $i<count($lists);$i++){
            $enc_arr[$lists[$i]->getNome()]=$lists[$i]->loadAssoc();

        }

    echo json_encode($enc_arr, JSON_FORCE_OBJECT);


}
}

Encode is the function meant to encode a list of tasks and lists.

The list class is showed below



class Lista
{
    private $id_lista;
    private $Scala;
    private $cod_proj;
    private $nome;

    public function __construct()
    {
    }

    public function getNome(){
        return $this->nome;
    }

    public function loadCompiti(){
        return App::get('query')->selectWhereSingle('Tasks', "cod_lista='{$this->id_lista}'",'Compito');
    }

    public function loadAssoc(){
        return App::get('query')->selectAssoc('Tasks', "cod_lista='{$this->id_lista}'");
    }

    public function getId(){
        return $this->id_lista;
    }
    public function getScala(){
        return $this->Scala;
    }
} 

the echoed output is this

    "Ingredienti": {
        "0": {
            "id_task": "8",
            "cod_lista": "8",
            "Nome": "Carote",
            "descr": "carote, carote, solo carote, le regalo a mio nipote diventano banconote",
            "due_date": "12/11/2019"
        },
        "1": {
            "id_task": "9",
            "cod_lista": "8",
            "Nome": "",
            "descr": "",
            "due_date": ""
        }
    },
    "ale": {},
    "mamma": {
        "0": {
            "id_task": "7",
            "cod_lista": "9",
            "Nome": "Abbracciare",
            "descr": "abbracciare mamma",
            "due_date": "12/03/2019"
        }
    },
    "X factor": {}
}

What I need is ajax to process the result without getting this error, I already tried to use JSON.stringfy but I got the same error.

3

Answers


  1. Chosen as BEST ANSWER

    Turned out that I am echoing my data from a class. The class also echoes HTML and loads my project view. So After having my JSON well-formatted, I got this error: Unexpected < in JSON at position 0. It was because before echoing my JSON I was echoing HTML.

    I fixed this by passing my array to a dedicated PHP file that echoed the array out.


  2. You can try following code

    For PHP

        $data = json_decode($json_data);
    

    For Jquery

        var json = $.parseJSON(response);
    
    Login or Signup to reply.
  3. var json={
    	"data": {
    		"0": {
    			"id_task": "8",
    			"cod_lista": "8",
    			"Nome": "Carote",
    			"descr": "carote, carote, solo carote, le regalo a mio nipote diventano banconote",
    			"due_date": "12/11/2019"
    		},
    		"1": {
    			"id_task": "9",
    			"cod_lista": "8",
    			"Nome": "",
    			"descr": "",
    			"due_date": ""
    		}
    	},
    	"ale": {},
    	"mamma": {
    		"0": {
    			"id_task": "7",
    			"cod_lista": "9",
    			"Nome": "Abbracciare",
    			"descr": "abbracciare mamma",
    			"due_date": "12/03/2019"
    		}
    	},
    	"X factor": {}
    }
    console.log(json)

    I can see your JSON is not well formatted. so if its not then it will give you error while parsing or stringify. you can validate JSON here

    I supposed your JSON should be something like below.

    {
        "data": {
            "0": {
                "id_task": "8",
                "cod_lista": "8",
                "Nome": "Carote",
                "descr": "carote, carote, solo carote, le regalo a mio nipote diventano banconote",
                "due_date": "12/11/2019"
            },
            "1": {
                "id_task": "9",
                "cod_lista": "8",
                "Nome": "",
                "descr": "",
                "due_date": ""
            }
        },
        "ale": {},
        "mamma": {
            "0": {
                "id_task": "7",
                "cod_lista": "9",
                "Nome": "Abbracciare",
                "descr": "abbracciare mamma",
                "due_date": "12/03/2019"
            }
        },
        "X factor": {}
    }
    

    And whenever response is coming by default it is in JSON format no need to stringify it.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search