Reputation: 63
First of all: I'm relatively new to jQuery, so please be gentle ;)
What I'm trying to achieve: I have a Java server (backend) which does some text parsing and offers a REST-style API. On the other side (front end) I have an HTML file with a form and few lines of jQuery code.
<html>
<body>
<form id="form">
<table>
<thead>
<tr>
<th>Code</th>
<th> </th>
<th>Code</th>
</tr>
</thead>
<tbody>
<tr>
<td><textarea id="input" name="input" cols="100" rows="50" type="text" placeholder="Input your code here..."></textarea></td>
<td>
<button id="btnTranslate" type="submit">Translate -></button>
</td>
<td><textarea id="output" name="output" cols="100" rows="50" type="text" placeholder=" "></textarea></td>
</tr>
</tbody>
</table>
</form>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$('#btnTranslate').click(function () {
var valueOfTextArea = $('textarea#input').val();
$.post("/parse", $('textarea#input').val(),
function (data) {
alert("Data Loaded: " + data);
$('#output').val("" + data);
$('#input').val(valueOfTextArea);
}
);
});
</script>
</body>
</html>
The problem is: the data gets send, is translated on the server side and is send back to the client, resulting in an alert window popup, at least some times. The textAreas however are never updated properly.
I've searched Google a lot and tried almost all of the suggestions on this site. With no luck so far.
What am I missing? What am I doing wrong?
Upvotes: 2
Views: 816
Reputation: 63
A possible solution, as I learned in a loooooong debug session with one of my coworkers, is:
$('#btnTranslate').click(function (event) {
var valueOfTextArea = $('textarea#input').val();
event.preventDefault();
$.post("/parse", valueOfTextArea, function (data) {
$('#output').val(data);
$('#input').val(valueOfTextArea);
});
});
So you need to prevent the default click-action, as it causes a "status 0" on the XMLHttpRequest somehow. I still don't get the whole picture, but at least it works now.
Thank you all for your input.
Upvotes: 2
Reputation: 2595
Try adding fallback methods. Start with something like this:
valueToSend = $( "#input" ).val();
var request = $.post( "/parse", valueToSend, function() {
alert( "success" );
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
Upvotes: 0