简体   繁体   中英

document.getElementById(..) gives null even though element is present

I have the following program in which a user can enter any name in a search box after which I redirect the user to a page called usernameSearchResults.php where I print a list of the usernames obtained in the form of an array from usernamesearch.php. Here is the javascript:

$(window).on('load', function() {
$(".searchBarForm").submit(function(e){ 
    e.preventDefault();

    var search=document.getElementsByClassName("search")[0].value;     

    $.ajax
    ({
        type: 'POST',
        url: 'usernamesearch.php',
        data: 
        {
            search:search
        },
        success: function (response) 
        { 
            window.location.href="usernameSearchResults.php";
            response = JSON.parse(response);

            var array_length = Object.keys(response).length;//getting array length          

            for(var i=0;i<array_length;i++){

                if(i==0){
                    document.getElementById("searchResults").innerHTML="<a href=userprofile.php?id="+response[0].id+">"+response[0].username+"</a><br>";//i=0
                }else{
                    document.getElementById("searchResults").innerHTML+="<a href=userprofile.php?id="+response[i].id+">"+response[i].username+"</a><br>";
                }

            }

            window.stop();//stops page from refreshing any further(put here to fix a bug that was occuring)
        },
        error: function(xhr, status, error) {
            alert(xhr.responseText);
        }              
    });

return false;
})
});

This is usernameSearchResults.php(inside tags):

<h1>Username Search Results</h1>

<p id="searchResults"></p>

But the problem is that whenever I go to any other page say index.php and enter the username to be searched, the page redirected to is indeed usernameSearchResults.php but the page is blank and error in the console shown says document.getElementById("searchResults") is null.But if I stay at the page usernameSearchResults.php and refresh it and then search any name again, then the results are correctly obtained. What is the problem here?

I would say that the user is being redirected to usernameSearchResults.php but the JavaScript code is still being executed from the current page, which have no element with id "searchResults" defined.

As @Kashkain said, one way to achieve what you want is to pass your response variable in your redirection url and process it then into your other page.

I think the problem here is that the new document could very well still not have been loaded when you call getElementById. You could add a listener on your target element which would trigger on the load event. In this event's handler you could execute the operations that are now giving you an error.

I have never done or tried this, but maybe something like this would work:

$('#searchResults').on('load', function() {
   //execute code here
});

Or you could add a form to the page with action="target_url" method="post" and send your response data through post by doing form.submit, and place the problematic code into usernameSearchResults.php, which will need to read data from POST - this way you can send your ajax data to the new page

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