Ajax is not working with submit button in HTML form while using the onclick option

The code below works when i use just the input text field but it doesn't works when i use a submit button. I don't know jquery so please explain

<!DOCTYPE html>
function showHint(str) {
 if (str.length == 0) { 
    document.getElementById("txtHint").innerHTML = "";
} else {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
    xmlhttp.open("POST", "download.php?q="+str, true);

 <p><b>Start typing a name in the input field below:</b></p>
 <form method="POST" action="showHint(str)"> 
 First name: <input type="text" placeholder="Copy Your Facebook Video URL Over Here" name = "URL" onclick="showHint(URL.value)" >
 <button type="submit" onclick="showHint(URL.value)">Download</button>
 <p>Suggestions: <span id="txtHint"></span></p>

However when i use the submit button instead it doesn't works Please help



Same thing happened with me instead of using button use input type = button like described below -

<input type="button" id="submit" value="submit" name="submit" onclick="showHint(URL.value)"></input>

it would surely work


so looks like you're trying to use an XHR request initiated by user action (clicking the button) but the form's default action is causing you problems.

The form is trying to take you to a page called showHint(str) when you click the button as the button submits the form and you've defined this action in action="showHint(str)".

If you add event.preventDefault(); to your function (I would put it as the first line of the function, ie. just before your if statement) then this function, which runs on button click as you've prescribed, will not submit the default form action and your problem will be solved. You can even remove the action property from your form tag entirely.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.