I am working on a block of code that will fire off an API if a checkbox is checked. I've tested the API and it works. I had the form functioning before turning it into a widget. (at least I think I did??)
So here is the script that won't GET form values when checked:
<script type="text/javascript">
(jQuery || $)(function($) {
$('#survessay-form').on('submit', function() {
// the jquery element of the form
var $this = $(this);
if($this.find('input[type="checkbox"]').is('checked')) {
$.ajax({
type: "GET",
url: `https://www.example.com/?cmd=api-co-reg&apik=ukp!BjItWgMi6Qk&Email=${$('#awf_field-95505011').val()}&FirstName=${$('#awf_field-95505010').val()}&aff_sid=emailcoreg&cmp=1320&cxid=242570`
}).done(function(data) {
data = data.result;
$("#checkedmessage").html("<p>Thanks, " + data.name + ", you're now a Swagbucks participant!</p>");
// continue to the confirmation page
}).fail(function(data) {
// verify data
data = data.responseJSON;
$("#errormessage").html("Error: Please check the format of your input");
});
}
// stops probagation of event (doesn't submit the request to the php page)
return false;
});
});
So essential this should submit the API when the checkbox is checked and the user clicks the submit button but it continues on to the forms action method. Without submitting the request. What am I missing here?
Use type: GET if the version is earlier than 1.9.0. Else use method: GET. More also, your URL suppose to start and end with " instead of the single quote since some of your parameter's value has the single quote. Below is the edited version of your code. Try to use your browser developer tools to debug your code.
(function($) {
$('#survessay-form').on('submit', function() {
// the jquery element of the form
var $this = $(this);
if($this.find('input[type="checkbox"]').is('checked')) {
$.ajax({
method: "GET",
url: "https://www.example.com/?cmd=api-co-reg&apik=ukp!BjItWgMi6Qk&Email=" + $('#awf_field-95505011').val() + "&FirstName=" + $('#awf_field-95505010').val() + "&aff_sid=emailcoreg&cmp=1320&cxid=242570",
success: function(data) {
data = data.result;
$("#checkedmessage").html("<p>Thanks, " + data.name + ", you're now a Swagbucks participant!</p>");
// continue to the confirmation page
}
}).fail(function(data) {
// verify data
data = data.responseJSON;
$("#errormessage").html("Error: Please check the format of your input");
}
// stops probagation of event (doesn't submit the request to the php page)
return false;
});
})(jQuery);