Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

dadub's avatar
Level 1

I try to get some data, but I have all the pages code as response (AJAX)

Hello,

I'm trying to get data from a table to put them in a select list.

I have this JS code :

$.ajax
    ({
        type: 'GET',
        url: '../hinteractions/hdi',
        dataType: 'json',
        success: function(retour)
        {
            alert(retour);
            alert("dans succes");
        },
        error:function(retour)
        {
            alert('dans erreur');
        }
    });

This is the controller :

public function index()
    {
        $herbs = Herb::all();
        $json = json_encode($herbs);

        return view('interaction.index', compact('herbs', 'json'));
    }

I don't understand why I get as response the full page and not only my data ?

My response (only accepted if I put data : text) is something begining with this code :

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">

Do you have any idea how can I get only $herbs ?

Thank you for your help.

0 likes
6 replies
jamalroger's avatar
Level 1

In index controller your are returning a view wish is page you should just return $json or directly return $herbs

1 like
dadub's avatar
Level 1

Thank you jamalroger, yes indeed, I have this code now :

public function get_herbs()
    {
        $herbs = Herb::all();
        return $herbs;
        // return $herbs->toJson();
    }

But I get an empty array

[]

Maybe Have I to add some code about herb in the model ?

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;

class Herb extends Model
{
    use Notifiable;

    protected $fillable = ['name', 'sciname', 'user_id'];

    public function temporary()
    {
        return $this->hasOne(TemporaryData::class);
    }

    public function user()
    {
        return $this->belongsTo(User::class,'user_id');
    }

    public function herb_forms() {
        //DD herb_has_forms c'est le nom de la table pivot
        return $this->belongsToMany(HerbForm::class, 'herb_has_forms')->withTimestamps();
    }

    public function targets()
    {
        return $this->belongsToMany(Target::class, 'hinteractions')->withTimestamps();
    }

    public function hinteractions() 
    {
        return $this->hasMany(Hinteraction::class);
    }


    //Thierry Tester


}
jamalroger's avatar

🙄🙄🙄 Because you have no herb in database

1 like
dadub's avatar
Level 1

I'm very tired and confused.... Thank you so much Jamal...

How can I put this post as resolve ?

Again, thank you.

dadub's avatar
Level 1

You're the best Jamal, thank you Friend.

Please or to participate in this conversation.