0

I am struggling with inserting data into my database. The thing is that if I do "form action = "adduser.php" method = "post" then it works. However, it loads a new page and I don’t want that.

function addUser() {
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
        }
    };

    xmlhttp.open("POST", "adduser.php");
    var formData = new    FormData(document.getElementById("new_person"));
    xmlhttp.send(formData);
}

<form onsubmit="addUser()">
   Name: <input id = "new_name" type="text" name = "new_name">
    <button type="submit"> Submit </button>
</form>

<?php
$conn = pg_connect(******);

$name = pg_escape_string($_POST['name']);
$query = "INSERT INTO highscores (name, score) VALUES ('$name', 200)";

$res = pg_query ($conn, $query);

pg_close();
?> 
1
  • <button type="submit"> Submit </button> => <input type="button" value="submit" onclick="addUser()" /> also consider looking into jquery. api.jquery.com/jquery.ajax Commented Dec 11, 2016 at 14:50

2 Answers 2

0

Change button type and add event to send data to server on click this button:

<button type="button" onclick="addUser()">Submit</button>

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

Comments

0

It loads a new page because you submit the form. Remove the onsubmit handler from the form and change the button type "submit" to "button".

<form id="user" name="user" method="post" action="#">
    <button type="button" onclick="addUser()">Submit</button>
</form>

Also, why not using jquery ajax, it's much more intuitive : http://api.jquery.com/jquery.ajax/

See exemple :

$.ajax({
    url: 'your_url',
    type: 'POST',
    async: true,
    data: $(your_form).serialize(),
    dataType: 'html',
    global: false, // Prevent the global handlers "ajaxStart" from being triggered...
    beforeSend: function() {

    },
    success: function(result, status) {

    },
    error: function(result, status, errno) {

    },
    complete: function(result, status) {

    }
}).done(function() {

});

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.