rozerro rozerro - 3 months ago 9
Ajax Question

JavaScript updates a page instead of updating a field

An original page url is

http://localhost:8080/appname/help.action

This page contains a form

<div id="message"></div>

<form id="help_form" name="help_form" onsubmit="return validate_help_form()">
...
<input type="submit" value="Submit" />
</form>


a script

function validate_help_form() {

if ( ... ) {
...
return false;
}

$.ajax({

url : 'http://localhost:8080/appname/question',
type : 'POST',
dataType : 'html',
success : function(result) {
console.log('^^^^^^^^^');
$('#message').text(result);
},
error : function(xhr, ajaxOptions, thrownError) {
alert('Unable to receive result. ' + thrownError);
},
});

}


a servlet is fairly simple

logger.info("-----------");

try {
response.getWriter().append( "a servlet result" );
} catch (IOException e) {
e.printStackTrace();
}


The problem is when ajax request works then the original page ruqested again by path `http://localhost:8080/appname/help.action. But i want to update a field message with ajax result.
So in a console I get

^^^^^^^^^
Navigated to http://localhost:8080/my-mates-ajax/help.action?username=...

Answer

Try using this

<form onsubmit="event.preventDefault(); return validate_help_form();">

Basically you need to first prevent form from submitting then you can perform the operation. Otherwise the form will be submitted along side the ajax request.

Comments