Send and request form via Ajax - (pure Javascript)

Asked

Viewed 3,348 times

1

I’m a beginner in Javascript and I 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.
I am using Ajax to send the data and trying to request them to appear in a div, without refresh obviously, however, I am unable to order after sending.

Follows 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;
    };
  • Which doubt???

  • I can send the data to the file, but the result only appears if I refresh the page. This is the problem

  • If you want to send and retrieve the name, you don’t need PHP to return the content again, just the status of success... use the var name.

  • PHP is only writing the information in txt. Ajax sends the data to php, php stores in txt, and then ajax searches for this data in txt.

  • PHP is successfully writing the name in the file?

  • Already tried to make a single request, and reply from php itself?

Show 1 more comment

1 answer

1


There are two problems:

1) At each sendData it is necessary to call loadData to check the data.

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

To solve the first problem should be used onreadystatechange in function sendData, within the if we should use ajax.readyState to check if the load is complete (remember ajax is asynchronous).

To solve the second problem you must call a new XMLHttpRequest with 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> for <input type=button>, why if you use Ubmit the page will redirect and the ajam will be canceled

  • This was a typo here on the kkk site. No inputs, I had already tested different. If I put "Return false;" in the last line of btn.onclick = ... then refresh does not occur, but the data is not loaded.

  • Yes. I tested. The default behavior after Submit is refresh, so I add "Return false" to btn.onclick, to prevent the default behavior of this event on the button. ...

  • worked perfectly. the/ If you can, explain to me why this line works there. I tried something similar before, it ran, but Firefox reported an abort.

  • ajax.onreadystatechange = loadData; Worked, but gave an error "error" in Chrome. _names.php gives status OK, but the names.txt is (canceled). I was updating the page, and the reply that was sent was loaded. Now, with this new code, everything is perfect. Can you explain the reason for this?

  • Watching the code I noticed. The error I’m talking about was arising, perhaps, because there was the call to two methods open consecutive. I believe they conflicted.

  • 100% code. So, were you thinking right? One object cannot make two consecutive requests because one will conflict with another?

  • Almost exact, it is not that will conflict, the problem is that it has already been used, probably in the internal process of the API has already been set data, which would not work or work partially (depending on the Ecmascript engine used by the browser). But regardless of this, yes you were thinking right, it takes one object for each request.

  • Thank you so much for your attention and immense help William. Sorry for any inconvenience.

  • It was no inconvenience, we are here to learn and share knowledge! Hug and success!

  • Have a great night. =)

  • It was like this before: window.onload = function () {&#xA; "use strict";&#xA; loadComment();&#xA;}; Now it looks like this: window.onload = loadData; The latter will not fire the page’s Reload?

  • loadComment is not defined, do not understand where it applies.

  • Sorry, I meant "loadData()".

  • I believe I understood, but this was wrong window.onload = loadData(); because it was not called in onload have to remove the () to be set to the onload event

  • So, window.onload = loadData(); launches the event and window.onload = loadData;, just as window.onload = function { loadData(); } arrow the function to the event?

  • Not in the second example is the same thing, but you create an anonymous event. I prefer how it is in the answer, so there is no need to create two events. Note: event = function.

  • @Guilhermenascimento and after the user select how this selected data can be sent to mysql. My case is as http://answall.com/questions/181981/form-din%C3%A2mico-e-send-to-mysql-via-jquery-e-ajax? noredirect=1#comment376494_181981

Show 12 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.