使用Javascript AJAX进行发布

I am currently writing some poll software and, even though it works fine, I am having difficulties getting some of my javascript to work. I have a button labelled "Add New Option" which, when clicked, will call the following javascript function:

function newoption()
{
    var option = "";
    while((option.length < 1)||(option.length > 150))
    {
        var option = prompt("Please enter the option value... ").trim();
    }
    var add = confirm("You entered " + option + ", are you sure?");
    if(add==1)
    {
        var code = window.location.href.length;
        var poll = prompt("Which poll are you adding this to?", window.location.href.substring(code - 5, code));
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) 
        {this.responsetext = option;}};
        xhttp.open("POST", "../special/new.php", true);
        xhttp.send("poll=" + poll + "&opt=" + option);
    }
    else
    {
        alert("OK... try again");
    }
}

The page it posts to simply has a function to add the option to the poll which the user supplies the code for (it automatically gets this from the end of the URL) but the problem is that, when I refresh the page, the list of options is not updated which makes me think it isn't being added to the database but the function to add new options works on when the poll is created. Is there something I'm doing wrong?

The code for new.php is:

<?php require("internal/index.php");
$option = string_format($conection, $_POST["opt"], 1)
$poll =(int) $_POST["poll"];
if($poll&&$option)
{
        new_poll_option($connection, $poll, $option);
}
?>

From what you wrote I understand that the code works until you refresh the page. That means that you don't check the Ajax response and just insert some HTML which will last until you refresh the page.

You need to look in your database if the items was created. If it is created then maybe you need to delete the browser cache (you can do that from the Network tab in DevTools in Chrome). If the items was not insert in the database then you need to debug or just echo the message from the insert function that you used.

You can also use a form and not use Ajax if you will refresh the page anyway in a few moments.