Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

My aim is to use AJAX to display php search results without having to reload the page. So far I have been able to get the results, (I'm new to ajax, and I do not know jQuery), currently my only problem is that the search results which I am displaying in a html table appear at the top the page above everything, not in the specified div. I have used the innerHTML to try and display it correctly.

Here is my main code:

    function searchResults(title) {
        if (title == "") {
            document.getElementById("response").innerHTML="";
        }
        var request= new XMLHttpRequest();
        request.onreadystatechange=function() {

            if (request.readyState == 4 && request.status == 200) {
                var displayDiv= document.getElementById("response");
                displayDiv.innerHTML=request.responseText;
            }
        }

            request.open("GET", "functions.php?titleA="+title, true);
            request.send();
            document.getElementsById("response").innerHTML="fuck";
    }
    </script>
    <title>Anime Search</title>
</head>
<body>
    <div class="main">

        <div class= "header">
        <h1>Search your Database</h1>
    </div> <!-- close header -->

    <div class= "searchA">
        <p>Search your Anime database below</p>
        <form onSubmit="searchResults(titleA)">
            <label>Title</label><input type="text" name="titleA" placeholder="enter title"/>
    <input type="submit" value="submit"/>
        </form>         
        <div id="response">

    </div> <!-- close response -->
</div> <!-- close searchA -->

and here is the php:

if (isset($_GET["titleA"])) {
    $title= $_GET["titleA"];
    $connection= connect(); 
    $username= $_SESSION["username"];
    $tableA= $username . "_Anime";
    $queryA= "SELECT * FROM Anime." . "`$tableA` WHERE Title LIKE '%$title%'";
    $resultA= mysqli_query($connection, $queryA);

    if ($resultA == false) {
        die("no results found");
    }

    $numRows= mysqli_num_rows($resultA);

    echo "<table class= 'tSearch'>
            <thead>
                <th>Title</th>
                <th>Alt Title</th>
                <th>Seasons</th>
                <th>Episodes</th>
                <th>OVA's</th>
                <th>Movies</th>
                <th>Status</th>
                <th>Downloaded</th>
            </thead>
            <tbody>";

    while($row= mysqli_fetch_array($resultA, MYSQLI_BOTH)) {
                echo "<tr>";
                    echo "<td>" . $row["Title"] . "</td>";
                    echo "<td>" . $row["Alt_Title"] . "</td>";
                    echo "<td>" . $row["Seasons"] . "</td>";
                    echo "<td>" . $row["Total_Episodes"] . "</td>";
                    echo "<td>" . $row["OVAS"] . "</td>";
                    echo "<td>" . $row["Movies"] . "</td>";
                    echo "<td>" . $row["Status"] . "</td>";
                    echo "<td>" . $row["Downloaded"] . "</td>";

                echo "</tr>"; 
            }

                echo "</tbody>";
            echo "</table>";

            mysqli_close($connection);

                if ($resultA == false) {
                    echo mysqli_error($connection);
                }
            }

I have of course spend many hours trying to find out whats wrong, I do plan on learning jQuery, but for now I just really want to get this to work, so please do not tell me to use jQuery,

EDIT: link to a screenshot: http://i.imgur.com/EJKhaTi.png My browser is Safari 7.0.4, i tried firefox and got the same problem Thank in advance, Rainy

share|improve this question
    
Are you getting any error? Can we see the error messages your getting if you're getting any? –  GaijinJim Jun 28 at 0:12
    
"my only problem is that the search results which I am displaying in a html table appear at the top the page above everything," ?? –  Mindeater Jun 28 at 0:15
    
Im not getting any error messages, here is a link to a picture, i couldn't upload because my rep isn't high enough.i.imgur.com/EJKhaTi.png –  RainyCats Jun 28 at 0:17
    
Your JavaScript code seems right on first sight. But I detected an sql injection vulnerability in your php code. Please use PDO or mysql_real_escpace_string –  Sascha Galley Jun 28 at 0:23
    
Thank you Sascha, I know about the mysql_real_escape string, but its hosted locally and will never be put on a public server, i will add it in for completeness's sake later though. Im purely creating this website in order to learn more about web development. –  RainyCats Jun 28 at 0:27
add comment

2 Answers

Here, Let me give you a generic layout:

This may be the easiest way to use ajax, I use this in my every project. First link the external ajax.js then you can use the below script.

I don't exactly know where you have done wrong base on your description, but this works for me even locally. One reason may be your #response isn't loaded yet when you execute the script.

ajax.js

function ajaxObj( meth, url ) {
    var x;
    if (window.XMLHttpRequest)
        { //New Browsers
            x = new XMLHttpRequest();
        }
    else
        { //IE5, IE6
        x = new ActiveXObject("Microsoft.XMLHTTP");
        }
    x.open( meth, url, true );
    x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    return x;
}
function ajaxReturn(x){
    if(x.readyState == 4 && x.status == 200){
       return true; 
    }
}

Script Tag Request for Ajax:

var ajax = ajaxObj("GET", "functions.php");
    ajax.onreadystatechange = function() {
        if(ajaxReturn(ajax) == true) {
            document.getElementById("response").innerHTML=ajax.responseText;
        }
    }
ajax.send("titleA="+title);

Or if you prefer JQuery:

//You need to load jQuery first before using this
$(function() {  //This line means when document is ready
    var ajax = ajaxObj("GET", "functions.php");
        ajax.onreadystatechange = function() {
            if(ajaxReturn(ajax) == true) {
                $("#response").html(ajax.responseText);
            }
        }
    ajax.send("titleA="+title);
});
share|improve this answer
    
Thanks man, i didn't think to put it into an external script. I do actually believe that the script loads before the, because if i get rid of the if (isset($_GET["titleA"])) { $title= $_GET["titleA"]; then the website loads everything in the database straight away. I don't understand why it does that, as i have put it in a function which should only activate when you submit the form. –  RainyCats Jun 28 at 8:39
    
the script loads before the div* –  RainyCats Jun 28 at 8:48
    
no, the problem you have i think is maybe outside the external ajax script, it is the document cannot seems to find the right div to put the response. –  Daniel Cheung Jun 28 at 8:53
    
I tried putting all the javascript in the external file, however as soon as the page loads, the database is searched and all the results are still being displayed. –  RainyCats Jun 28 at 9:05
    
that is because you will trigger the script on page load, that's normal. –  Daniel Cheung Jun 28 at 9:21
show 27 more comments

I have fixed the problem, rewriting your code from the start really does help. The problem was that in my javascript I was sending the title as just +title, i really should have changed this to title.value, this is why the php wasn't understanding what i was trying to send it. Thanks Daniel for all the help. I will display all my code below. javascript:

    function searchData() {
        var title= document.getElementById("titleA");
        var request= new XMLHttpRequest();
        request.onreadystatechange= function() {
            if (request.readyState == 4 && request.status == 200) {
                document.getElementById("response").innerHTML=request.responseText;                 
            } 
        }


        request.open("POST", "functions.php", true);
        request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

        request.send("title="+title.value);
    }

    </script>

The php:

if (isset($_POST["title"])) {
$title= $_POST["title"];

} $connection= connect();

    $username= $_SESSION["username"];

    $tableA= $username . "_Anime";

    $queryA= "SELECT * FROM Anime." . "`$tableA` WHERE Title LIKE '%$title%'";

    $resultA= mysqli_query($connection, $queryA);

    if ($resultA == false) {
        die("no results found");
    }


    $numRows= mysqli_num_rows($resultA);

    echo "<table class= 'tSearch'>
            <thead>
                <th>Title</th>
                <th>Alt Title</th>
                <th>Seasons</th>
                <th>Episodes</th>
                <th>OVA's</th>
                <th>Movies</th>
                <th>Status</th>
                <th>Downloaded</th>
            </thead>
            <tbody>";

    while($row= mysqli_fetch_array($resultA, MYSQLI_BOTH)) {
                echo "<tr>";
                    echo "<td>" . $row["Title"] . "</td>";
                    echo "<td>" . $row["Alt_Title"] . "</td>";
                    echo "<td>" . $row["Seasons"] . "</td>";
                    echo "<td>" . $row["Total_Episodes"] . "</td>";
                    echo "<td>" . $row["OVAS"] . "</td>";
                    echo "<td>" . $row["Movies"] . "</td>";
                    echo "<td>" . $row["Status"] . "</td>";
                    echo "<td>" . $row["Downloaded"] . "</td>";

                echo "</tr>"; 
            }

                echo "</tbody>";
            echo "</table>";

            mysqli_close($connection);

                if ($resultA == false) {
                    echo mysqli_error($connection);
                }   
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.