Stop submitting from javascript ajax request

2019-07-28 22:29发布

I'd like to stop a form submitting by thr result of an ajax request... this is the code i tried to use: The function chreg() should return a boolean given from the ajax request, but it doesn't!

Javascript:

function chreg() {

user = document.getElementById('nome').value;
passw1 = document.getElementById('passw1').value;
passw2 = document.getElementById('passw2').value;
mai = document.getElementById('mail').value;
dat = 'use='+encodeURIComponent(user)+'&pas='+encodeURIComponent(passw1)+'&pas2='+encodeURIComponent(passw2)+'&mail='+encodeURIComponent(mai);

htp = new XMLHttpRequest;
htp.onreadystatechange = function(){

    if (htp.readyState == 4 && htp.status == 200){
        if (htp.responseText == "true"){
            alert('true');
        return true;
        }
        else {
        document.getElementById('er2').innerHTML = '<br/><h3>'+tag_esc(decodeURIComponent(htp.responseText))+'</h3>';
        return false;
        }


    }
};
a = Math.random
  htp.open("POST","checklog.php?a="+a,true);
  htp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    htp.send(dat);   
}

And the HTML:

<form action="reg.php" method="POST" onsubmit="return chreg(this);">
<table id="tab2"><tr><td>

<label for="user1">Username: <input type="text" name="user" id="nome" /></label></td>      <td>
<label for="mail">Indirizzo e-mail: <input type="text" name="mail" id="mail" /></label>   </td>
</tr>
<tr><td><label for="pass1">Password: <input type="password" name="pass1" id="passw1" />    </label></td>
    <td><label for="pass2">Password (conferma): <input type="password" name="pass2"  id="passw2" /></label></td></tr>
     <tr><td colspan="2"><br /><input type="submit" class="st" value="Registrati" /></td>    </tr>

</table>
<div id="er2"></div>
</form>

But it doesn't work! Help Thanks a lot!

3条回答
劫难
2楼-- · 2019-07-28 22:58

You won't be able to make it work as it stands because AJAX is asynchronous by default. That means that your chreg method initiates the request and returns immediately, before the request has completed and its result become known. This is a problem because you cannot return from chreg before the result is known since you need that result to know what to return.

One solution would be to make the request synchronous by changing the third parameter here:

// you will not need to set onreadystatechange at all

htp.open("POST","checklog.php?a="+a,false); // false = synchronous
htp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
htp.send(dat);   
if (htp.responseText == "true"){
    alert('true');
    return true;
}
else {
    document.getElementById('er2').innerHTML = '<br/><h3>'+tag_esc(decodeURIComponent(htp.responseText))+'</h3>';
    return false;
}

This is not the best solution because it might end up locking up the UI for the duration of the request, which is undesirable. However, going back to the asynchronous model (which does not have this problem) is going to be more involved because it requires you to do stuff "backwards":

  1. Function chreg is called and makes the AJAX request; it always returns false (so the form is not submitted)
  2. When the onreadystatechanged handler you installed detects that the AJAX is complete, it checks the response.
  3. If the response is logically true (the form actually needs to be submitted) then use form.submit to do it.
查看更多
在下西门庆
3楼-- · 2019-07-28 22:59

Your success handler function returns either true or false but your main chreg method doesn't.

You need to return false in your chreg method to stop the form submitting.

    [...]
    htp.send(dat); 
    return false;

Since you're handling the form submission through ajax, you'll likely not want the form to do a postback atall.

查看更多
beautiful°
4楼-- · 2019-07-28 23:00
<!DOCTYPE html>
<html>
<body>

<h1>My First JavaScript</h1>

<p>Please input a number.</p>

<input id="demo" type="text">

<script>
function myFunction()
{
var x=document.getElementById("demo").value;
if(x==""||isNaN(x))
        {
        alert("Not Numeric");
        }
}
</script>
查看更多
登录 后发表回答