如何在插入数据时修复xmlhttprequest函数问题

my code works only if i add this code:

document.write(str);

which open a new page and write in it insert data in database

but if i try to the code without it like this :

    function addcourse2(str,cn)
{
    xmlhttp=new XMLHttpRequest();
//document.write(str);  
xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState === 4 && xmlhttp.status == 200) { 

                       alert('response:'+xmlhttp.responseText);

            } else {

                       alert('failure!');
            }

};

    xmlhttp.open("GET","tpages/addcourse2.php?q="+str+"&p="+cn,true);

     xmlhttp.send();
}

here i get alert message failure and nothing gets inserted into database i need and explanation to this a way to fix it

looking at your comments i understand that the page is refreshing after you click the button before the state is reaching 4 then this is the button code to prevent it from refreshing

add return false;

<button "onclick='addcourse2("value1","value2");return false;'>add course</button>

Let's try to describe.

Note: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open.

https://developer.mozilla.org/en-US/docs/Web/API/Document/write

So, this AJAX script with document.write work as from new page and each case calls to URL ""tpages/addcourse2.php?q="+str+"&p="+cn"

If commented document.write Then browser may be cached URL and browser read from cache and doesn't call same URL. So, you can use unique URL string and test so.

Also, may be was an other case.