skip to Main Content

I’m trying to include a file on my server using AJAX, the only problem is that it stops my php code from working.

The page I’m using ajax at:

<div id="content">
<!--- HERE GOES CONTENT --->
</div>
<script>
$.ajax({
    url: 'https://mywebsite.com/func/contentpage.php',
    dataType: 'html'
})
.done(function(data) {
    // Assuming the request returns HTML, replace content
    $('#midten').html(data);
});
    </script>

contentpage.php code:

<?php
$g1 = $database->query("SELECT * FROM `users` WHERE `sesid` = '" . $_SESSION["uises"] ."' AND abd='" . $_SESSION["uiabd"] ."'");
$ui2 = $g1->fetch_object();

echo $ui2->name;
?>

The code above should echo a name from the database but for some reason it does not.

If I use php and include the page like this: include("/func/contentpage.php") it echo the name without any problems.

But when trying to load the page with ajax it does not echo a name or anything. The reason I’m using AJAX is to load content when buttons is clicked without the browser having to reload.

How can I solve this problem with AJAX or another method? I could use in php to change the path in include without having to reload the webpage/load the whole website again.

2

Answers


  1. For debugging purposes, you can echo out anything else other than name, but if there are errors in your PHP file then there will be a message in the developer console, something like 502 internal server error.

    Your contentpage.php is missing a lot of declarations and references.

    <?PHP
    session_start();//since you are using sessions here
    $database = something;//undefined variable
    //better use a file where you have declared all the variables and 
    //then include it here
    require variables.php;//something like this
    $g1 = $database->query("SELECT * FROM `users` WHERE `sesid` = '" . $_SESSION["uises"] ."' AND abd='" . $_SESSION["uiabd"] ."'");
    $ui2 = $g1->fetch_object();
    
    echo $ui2->name;
    ?>
    

    For more information on what actually going wrong, visit https://mywebsite.com/func/contentpage.php using URL, if you have error_reporting() enabled you will see the errors.

    If there are no errors in .php then you need to check with your ajax.

    Login or Signup to reply.
  2. Replace the datatype HTML to text, Because return response in text not a html, because of that response is empty

    Try this:

    <div id="content">
    <!--- HERE GOES CONTENT --->
    </div>
    <script>
    $.ajax({
        url: 'https://mywebsite.com/func/contentpage.php',
        dataType: 'text'
    })
    .done(function(data) {
        // Assuming the request returns HTML, replace content
        $('#midten').html(data);
    });
        </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search