views:

43

answers:

2

I am using the below code to search a mysql database but cannot get the form to submit when the return key is pressed.

Does anybody have any ideas?

function ajaxFunction(){
 var ajaxRequest;
{
  // Opera 8.0+, Firefox, Safari
  ajaxRequest = new XMLHttpRequest();
 } catch (e){
  // Internet Explorer Browsers
  try{
   ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (e) {
   try{
    ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
   } catch (e){
    // Something went wrong
    alert("Your browser broke!");
    return false;
   }
  }
 }
 ajaxRequest.onreadystatechange = function(){
  if(ajaxRequest.readyState == 4){
   var ajaxDisplay = document.getElementById('ajaxDiv');
   ajaxDisplay.innerHTML = ajaxRequest.responseText;
  }
 }
 var kw = document.getElementById('kw').value;
 var division = document.getElementById('division').value;
 var queryString = "?kw=" + kw + "&division=" + division;
 ajaxRequest.open("GET", "search/jsearch.php" + queryString, true);
 ajaxRequest.send(null); 
}

Form code is:

<form name='myForm'>
Keywords<input type='text' id='kw' /> <br />
<br />
<select id='division'>
  <option value='0' selected="selected">window & door</option>
  <option value="1">window</option>
  <option value="2">door</option>
</select>
<input type='button' onclick='ajaxFunction()' value='Query MySQL' />
</form>
A: 

Where is your event code for the form? Are you using an onclick instead of onsubmit? I don't think we have enough code/information to answer this, but from what you describe your first step to make sure you are using an onsubmit event for the form so you can fire off the xhr.

EDIT: Then the answer to this problem: "...cannot get the form to submit when the return key is pressed", is use onsubmit instead of onclick. You also need to attach the event to the form instead of the button, and if possible refrain from using inline js.

http://en.wikipedia.org/wiki/Unobtrusive_JavaScript

mk
I am using onclick at the moment - form is now posted above.
Haribo83
If I change to onsubmit then when i press return the search clears but doesn't search....
Haribo83
Please update your code so we can see exactly what you are doing.
mk
A: 

onclick fires when you click the button. You are pressing return, not clicking the button.

As mentioned earlier, you should use onsubmit which fires when the form is submitted. You will need to return false, ie use onsubmit="ajaxFunction();return false;", to prevent the normal submission from occurring.

This has worked!! Thank you so much.sorry to be a pain but I can only test on safari and firefox at the moment - will this work on IE?
Haribo83