-1

I got this code online and it seems to do what i'm trying to achieve. However, the function calls onload. I want it to work only when i click a button. Something as simple as:

<button type="submit" form="form" value="Submit">Submit</button>

This is the JS:

$.ajax("https://api.base62.io/encode", {
    type: "POST",
    data: JSON.stringify({ data: "Hello world!" }),
    contentType: "application/json",
}).done(function (data) {
    $("#encoded").html(data.encoded);
}).fail(function (xhr, status, error) {
    $("#error").html("Could not reach the API: " + error);
});

HTML:

<p id="encoded">Encoding..</p>
<p id="error"></p>

JSFiddle DEMO

Elaine Byene
  • 3,868
  • 12
  • 50
  • 96

1 Answers1

0

Added the handler to your code. Learn more about ajax here

$('#ajax-btn').click(function() {
$.ajax("https://api.base62.io/encode", {
  type: "POST",
  data: JSON.stringify({
    data: "Hello world!"
  }),
  contentType: "application/json",
}).done(function(data) {
  $("#encoded").html(data.encoded);
}).fail(function(xhr, status, error) {
  $("#error").html("Could not reach the API: " + error);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="encoded">Encoding..</p>
<p id="error"></p>

<button id="ajax-btn"> CLick Me </button>
Ramesh
  • 2,297
  • 2
  • 20
  • 42