2

I'm trying to run a php file with AJAX from my "main.php".

The problem is that it doesnt let my stay on the main.php and moves me to "tallennus.php", when I want to stay at "main.php". The tallennus.php should be done on the background.

"tallennus.php" does it's work perfectly (saves data to database). But I want to stay on mainsite while it does it.

Im trying to use AJAX to run "tallennus.php" on the background.

Why does the site change from main.php to tallennus.php?

<button onclick="testi()">testi</button><br>
<script>
function testi()
{
    alert("function started");
    var xmlhttp;
   if (window.XMLHttpRequest) {
     xmlhttp=new XMLHttpRequest();
   } else {
     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
   }

    xmlhttp.onreadystatechange=function() {
     if (xmlhttp.readyState==4 && xmlhttp.status==200) 
            }
            xmlhttp.open("get", "tallennus.php",true);
            xmlhttp.send();
        }   




</script>
0

2 Answers 2

1

The default type of <button> is type="submit", so it submits the form. Change it to type="button".

<button type="button" onclick="testi()">testi</button><br>

As per the following reference:

"A button element with no type attribute specified represents the same thing as a button element with its type attribute set to "submit"."

Sign up to request clarification or add additional context in comments.

Comments

0

I fixed my problem by doing this:

<script>
function tallenna()
{


    var tunnus=document.getElementById('tunnus').value;
    var nimi=document.getElementById('nimi').value;
    var deadline=document.getElementById('deadline').value;
    var vaihe=document.getElementById('vaihe').value;
    var dataString=
    'tunnus='+ tunnus + 
    '&nimi='+ nimi+
    '&deadline='+ deadline+
    '&vaihe='+ vaihe;

    $.ajax({
        type:"post",
        url: "tallennus.php",
        data: dataString,
        cache:false,
        success:function(html){
            $('#msg').html(html);
        }
    });

    document.getElementById("frm").reset();// for clearing form
    return false;

}
</script>

<br><input type="submit" value="TALLENNA" onclick="return tallenna()">

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.