Reputation: 105
I'm really struggling to understand what's going on with my code. The goal is to take 2 strings and display the edit distance. The request and response must be sent as JSON objects
Here is my index.html file.
<html>
<head>
<meta charset="utf-8"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready( function() {
$('#mainForm').click(function() {
var formdata = $("#mainForm").serialize();
console.log(formdata);
$.ajax({
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({string1: $('#string1').val(), string2: $('#string2').val()}),
dataType: 'json',
url: '/index',
success: function (e) {
console.log(e);
window.location = "/index";
},
error: function(error) {
console.log(error);
}
});
});
});
</script>
</head>
<body>
<h1>Compute Edit Distance</h1>
<form action="/index" method='post' name="mainForm" id="mainForm">
String1: <input type="text" name="string1" id="string1">
</br>
</br>
String2: <input type="text" name="string2" id="string2">
</br>
</br>
<button name = "submit" id = "submit" name="submit">submit</button>
</br>
</br>
<span id="editDistance">{{edit_distance}}</span>
</form>
</body>
</html>
Now, when I switch $('#mainForm').click to $('#mainForm').submit, no data is sent over. If I keep it as .click my controller receives the data in JSON form correctly, but this is not the behavior I want. The strings are sent over only when you click within the form, and the edit_distance does not display. If I switch it to on submit, content-type is application/x-www-form-urlencoded and I get a server error. Why is this happening? Also, how can I dynamically display the edit distance as I'm typing in the strings?
When I press the submit button, the request JSON data gets set to None. Here is my server code.
@app.route('/index', methods=['GET', 'POST'])
def index():
edit_distance = 0
if request.method == 'POST':
print(request.content_type)
data = request.get_json()
string1 = data['string1']
string2 = data['string2']
print(string1, string2)
edit_distance = get_edit_distance(string1, string2, len(string1),len(string2))
print(edit_distance)
response = make_response(render_template('index.html', edit_distance = edit_distance))
return response
Upvotes: 1
Views: 89
Reputation: 1669
The content-type is application/x-www-form-urlencoded because the submit request still goes through after the ajax .onsubmit is executed. So you'll see alternating JSON and x-www-form-urlencoded requests. To address this you can cancel the default submit behavior:
//Prevent form submission from refreshing page
event.preventDefault();
As for how to dynamically update it, you can on success set the innerHTML of the desired div like so:
document.getElementById("divId").innerHTML = "desired value";
Upvotes: 1