Search code examples
javascriptphphtmlajaxxmlhttprequest

how to fix xmlhttprequest function problem when inserting data


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


Solution

  • 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>