Hello Beautiful Campers, I have this code that works with jQuery but I’ve been searching for ways to do it with Vanilla Javascript all to no avail.
Here is the code
index.html
<body>
<h1>Metric/Imperial Converter</h1>
<hr>
<section class="code">
<h3>Example Usage</h3>
<code>/api/convert?input=4gal</code><br>
<code>/api/convert?input=1/2km</code><br>
<code>/api/convert?input=5.4/3lbs</code><br>
<code>/api/convert?input=kg</code>
<h3>Example Return</h3>
<code>{initNum: 3.1, initUnit:'mi',returnNum:4.98895,returnUnit: 'km', string:'3.1 miles converts to 4.98895 kilometers'}</code>
<hr>
</section>
<section class="form">
<div class="test-container">
<h3>Front-End</h3>
<form id="form">
<input type="text" name="input" placeholder="3.1mi">
<input type="submit" value="Convert!" name="convert">
</form>
<p id='result'></p>
<code id='jsonResult'></code>
</div>
</section>
<script src="https://code.jquery.com/jquery-2.2.1.min.js"
integrity="sha256-gvQgAFzTH6trSrAWoH1iPo9Xc96QxSZ3feW6kem+O00=" crossorigin="anonymous"></script>
<script>
$(function () {
$('#form').submit(function (event) {
event.preventDefault();
$.ajax({
url: '/api/convert',
type: 'get',
data: $('#form ').serialize(),
success: function (data) {
$('#result').text(data.string || data);
$('#jsonResult').text(JSON.stringify(data));
console.log(data)
},
error: function (request, textStatus, errorThrown) {
alert(request.getResponseHeader('some_header'));
}
});
});
});
</script>
</body>
</html>