简体   繁体   中英

Do I need to include PHP scripts again in a ajax loaded PHP page?

I have an ajax call to a php page in which I pass an ID using GET.

<script>
$("#oid").change(function(){
    var oid = $(this).val();
    alert(oid);
    $.ajax({
        type: "GET", 
        url: "tabela_reservas.php",
        data: "oid="+oid,
        success: function(html) {
            $("#tabela_reservas").html(html);
        }
    });
});
</script>

It works, except that PHP gives me an error:

Fatal error: Class 'Reserva' not found in C:\\xampp\\htdocs\\kwagenda\\tabela_reservas.php on line 20

If I include my class files in the "tabela_reservas.php" it works. But these Class files are already loaded/included in my "index.php" from where I'm calling this ajax page.

My question is: do I need to include my php Class file on "tabela_reservas.php" again or there is another way of doing it?

I ask this because, to me, it doesn't seem to be a very elegant solution, and it look's like an overhead, since I'll be loading twice the same thing on my page.

Is this the right thing to do or there is another way of doing this?

Thanks!

When you make an ajax request to the server, this is a completely new request, just like navigating to another page.

So yes, you need to include everything again.

You should look into autoloading of classes for a more elegant solution to include classes.

You need to include all class files again in the tabela_reservas.php as there is no relation between index.php and tabela_reservas.php .

All ajax requests are completely new without any relation to the current(caller) page. Consider those as a new page being called :)

An AJAX call means: You're calling a new page. It doesn't matter where the call came from, it's like calling the new page in the background.

As such it is parsed anew, just like it would be parsed if a browser accessed it.

So yes: You do have to include all required scripts in any script you call via AJAX.

You need to have another instance of this class of you use it in another script. Another way of doing this would be using PHPs autoloading / magic loading (See: PHP: Autoloading )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM