简体   繁体   中英

AJAX module not submitting the form

I am having a problem with this JavaScript, it's reloading the page and not submitting the form!

JavaScript:

var xmlHttp
function GetXmlHttpObject(){
  var objXMLHttp=null;
  if (window.XMLHttpRequest) {
    objXMLHttp=new XMLHttpRequest();
  } else if (window.ActiveXObject) { 
    objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  return objXMLHttp
}
function ajax_module(){
  xmlHttp=GetXmlHttpObject();
  if (xmlHttp==null) {
    alert ("Browser does not support HTTP Request");
    return
  }
  xmlHttp.open('POST', 'save.php');
  xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
  xmlHttp.send('user='+document.form1.user1.value+'&text='+document.form1.text1.value);
  document.form1.test1.value = '';
  document.form1.test1.focus();
}

HTML:

<form name="form1" method="POST" onsubmit="ajax_module(); return false;">
    <textarea name='text1'></textarea> 
    <input type='hidden' name='user1' value='$user' />
    <input type="submit" name="submit" value="submit" />
</form>

Double-check that no errors are occurring within ajax_module . If there are any, it will never get to return false and won't stop the onsubmit .

If you have Firebug or a similar debugger available, set breakpoints within ajax_module . Otherwise, add a try / catch right inside ajax_module :

function ajax_module() {
  try {
    /* place what you already have here */
  } catch (e) {
    alert(e);
  }
}

You also commented that text inputs usually work. This may be due to newlines being allowed in textareas, which you aren't currently encoding.

Whether that's the cause or not, it's probably a good idea to encode the values anyways.

xmlHttp.send('user=' + encodeURIComponent(document.form1.user1.value) + 
            '&text=' + encodeURIComponent(document.form1.text1.value));

For more info, check out http://www.w3schools.com/jsref/jsref_encodeuricomponent.asp .

An alternative would be escape -- though, note the character differences described on each page.

Perhaps it's the missing self-closing tag on the user input? Is there a JavaScript error?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM