Sending and requesting form via Ajax - (pure JavaScript)

1

I'm a beginner in JavaScript and started to see Ajax. I made an example where I have a form that sends a name to a php file. This php receives via post and writes the information in a txt. Home I am using Ajax to send the data and trying to request them to appear in a div, without refresh obviously, however, I am not able to request after sending.

Follow the codes

HTML

    <form id="form" method="post" action="">
        <label for="name">Nome:</label>
        <input type="text" name="name" id="name">
        <input type="submit" id="submit" name="submit" value="Enviar">
    </form>
    <div id="result"></div>

PHP

    <?php
        $name = "<p>" . $_POST["name"] . "</p>" . PHP_EOL;
        $file = fopen("names.txt", "a");
        fwrite($file, $name);
        fclose($file);
    ?>

JavaScript

    var btn = document.getElementById("submit"),
              result = document.getElementById("result"),
              ajax = new XMLHttpRequest();

    function sendData() {
        "use strict";
        var name = document.getElementById("name").value;
        ajax.open("POST", "_names.php", true);
        ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        ajax.send("name=" + name);
    }

    function loadData() {
        "use strict";
        ajax.onreadystatechange = function () {
            if (ajax.readyState === 4 && ajax.status === 200) {
                result.innerHTML = ajax.responseText;
            }
        };
        ajax.open("POST", "names.txt", true);
        ajax.send(null);
    }

    window.onload = loadData();

    btn.onclick = function () {
        "use strict";
        sendData();
        return false;
    };
    
asked by anonymous 31.07.2014 / 05:04

1 answer

1

There are two problems:

1) Every sendData is required to call loadData to verify the data.

2) Each request must have a new Ajax (call class) constructor

To solve the first problem, you must use onreadystatechange in the function sendData , inside if we must use ajax.readyState to check if the load is complete (remember ajax is asynchronous). >

To solve the second problem you should call a new XMLHttpRequest for each request.

Try this:

var btn = document.getElementById("submit"),
          result = document.getElementById("result");

function sendData() {
    "use strict";

    var ajax = new XMLHttpRequest();
    var name = document.getElementById("name").value;
    ajax.open("POST", "_names.php", true);
    ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    ajax.onreadystatechange = function () {
        if (ajax.readyState === 4 && ajax.status === 200) {
            loadData(); //Recarrega dados após o envio dos dados
        }
    };
    ajax.send("name=" + name);
}

function loadData() {
    "use strict";

    var ajax = new XMLHttpRequest();
    ajax.onreadystatechange = function () {
        if (ajax.readyState === 4 && ajax.status === 200) {
            result.innerHTML = ajax.responseText;
        }
    };
    ajax.open("POST", "names.txt", true);
    ajax.send(null);
}

window.onload = loadData;

btn.onclick = function () {
    "use strict";
    sendData();
    return false;
};

Failed to add } at the end of this function:

function sendData() {
        "use strict";
        var name = document.getElementById("name").value;
        ajax.open("POST", "_names.php", true);
        ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        ajax.send("name=" + name);

And change the <input type=submit> by <input type=button> , why if you use submit the page will redirect and the action will be canceled

    
31.07.2014 / 05:57