简体   繁体   中英

Include php file via Ajax and display on page

I was wondering if there is any way to include a php file after an AJAX call and display that included file in my page as response.

For example this is an ajax call:

$('#id').change(function(){
    var selected = $(this).val();
    $.ajax({
        url:  "ajax.php",
        type: "POST",
        data: "select="+selected,
        success: function (data) {
            $("#here").html(data);
        }
    });
});

And this is what i tried in php but i got not result displayed on my html:

if(isset($_POST['select'])){
    $post= $_POST['select'];

    $class = ClassName::find_by_id($post);

    $sql = " sp_SQLStoredproc {$class->id} ";
    if($class->hasRows($sql)){
        include("include.php");
    }

}

Is there any way to display my included file in my html?

I tried to change my success response from Ajax $("#here").html(data); to $("#here").load(data); but it returned the whole page.

Any suggestions will help.

UPDATE: Inside the include.php file exist a long html code and some class methods

PS. Please don't mentioned that script is not safe, I know is just an example script.

Thank you in advance

In order to get the success data you need to return the data which you want to be included. And remember php will not work in html except it is action call. You can have php file for this since it has the html support also.

Also you need to remember, before setting the success data to the element it's better to console the value and make sure you are getting the correct data.

if(isset($_POST['select'])){
    $post= $_POST['select'];

    $class = ClassName::find_by_id($post);

    $sql = " sp_SQLStoredproc {$class->id} ";
    if($class->hasRows($sql)){
        return include("include.php");
    }

}

you can set all your "include.php" html in buffers and then you need to echo your content into console.

<?php
    if(isset($_POST['select'])){
        $post= $_POST['select'];

        $class = ClassName::find_by_id($post);

        $sql = " sp_SQLStoredproc {$class->id} ";
        if($class->hasRows($sql)){
            ob_starts();
            include("include.php");
            $include = ob_get_contents();
            echo $include;
        }
    }
?>

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