I have a strange issue with my code I can’t seem to figure out. I’m relatively new to js and utilizing http requests to retrieve json data however I’ve been able to come up with code that works, for the most part.
Essentially the workflow is as follows: I have a user enter some form field values and select the submit button. Onsubmit the the apiCall() function is called which then calling the createXMLHttpRequestObject() and constructApiURL(searchtype) functions creates, populates, and sends the xmlHttpRequest Object via the proxy to the search api url. Once the result is returned the handleResults() function is called which then parses and displays the results in the apropriate div container using the handleResultsContainer() function.
Everything works when I step through the code via firebug. The object is created, sent via the proxy to the search api, the results are returned and displayed but once the focus returns to the function onsubmit(event) {callApi();} and the contents then clear!?! I don’t know if the page is reloaded or something else is going on.
Now if I change the initial trigger from a form submit to a button onclick it works without issues. The user selects the button, the search results are retrieved and displayed until the user selects the button again at which point the results are cleared and the new results are displayed. The problem is that I have to hard code the parameters I would normally be getting from the form.
Has anyone experienced this or sees something with how the code is being read by the browser that could cause this? My Pseudo code is below.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function createXMLHttpRequestObject() {
-- code to create the XMLHttpRequestObject based on browser type --
}
function constructApiURL(searchtype) {
-- code to create the api url using the form values & proxy url --
}
function handleResultsContainer () {
-- code to create/remove search results display div
}
function handleResults(jsndata) {
-- code to parse and display results here --
}
function callApi() {
-- code to create XMLHttpRequestObject, populate it, and send it --
}
</script>
</head>
<body>
<form id="basicform" name="mashsearch" onsubmit="callApi()">
-- Code for user input fields which are then used by constructApiURL --
<input type="submit" id="searchbtn" value="Search!"/>
</form>
//Div displaying a Search Results Loading… message which is hidden/displayed//
<div id='loadingDiv' style="display:none">Search Results Loading...</div>
//Div used to display the search results
<div id='json'></div>
</body>
</html>
Change your onsubmit to :
Alternatively you could add
return falseto the bottom of yourcallApi()method and change your onsubmit to beonsubmit="return callApi()"If you do not the page will submit and reload as its normal behaviour would.