Getting Gravity Forms AJAX Confirmation Message in Javascript Instead of Outputting - javascript

I have the Gravity Forms plugin setup in Wordpress, and I am using the AJAX feature on my form. I have it configured to return a Confirmation message upon submission, but I want to grab the value contained in the confirmation message in Javascript instead of having it automatically output onto the form.
I'm not sure how to get grab the Confirmation Message before it is output, or how to prevent it from being output.
It looks like the 'gform_post_render' javascript hook is called right before the message is output, but I'm not sure where to target the confirmation message value or prevent it from outputting.
Is there a way to override the confirmation message output? Or is there a better way to setup Gravity Forms to return a dynamic value through AJAX where I can then determine what to do next?
Thanks!

I ended up getting help from the Gravity Forms support team, and they recommended that instead of using the included AJAX functionality, that I look into the Gravity Forms Web API, specifically the /forms/{ID}/submissions endpoint:
https://www.gravityhelp.com/documentation/article/web-api/#form-submissions
My solution ended up looking something like this:
$('form').submit(function(e) {
e.preventDefault();
// Get Form ID for submission URL //
var formID = $(this).attr('id');
formID = formID.replace('gform_', '');
var formURL = '/gravityformsapi/forms/'+formID+'/submissions';
// Get Form Input Data and Format JSON for Endpoint //
var formArray = $(this).serializeArray();
var formData = [];
$.each(formArray, function(index, data) {
var name = data['name'];
var value = data['value'];
formData[name] = value;
});
formData = $.extend({}, formData);
var data = { input_values : formData };
// AJAX to Submit Form //
$.ajax({
url: formURL,
method: 'POST',
data: JSON.stringify(data)
}).done(function (data, textStatus, xhr) {
// This is the HTML that is output as a part of the Confirmation Message //
console.log(data.response.confirmation_message);
});
});
This allows you to submit the form via AJAX, but then you can chose what to do with the response in the data.response.confirmation_message variable.

Related

Form that already being validated by JS. Need to have it also clear fields on submit

I have a web form that is part of a CMS, therefore I am not able to alter the input field of the submit button. The form is already being validated by JS, so I need to add a line to the existing code below that will clear the fields.
Currently, the page redirects to a Thank you page on submit. I want it to continue doing that. But, currently, if the user hits the back button on their browser, the data is still there. I need it to submit the data, clear the fields, then redirect to the thank you page.
$('form').submit(function(event)
{
if (validateForm())
return true;
event.preventDefault();
});
Have you tried adding document.querySelector('form').reset() above the return statement? In jquery that might just be $(this).reset(), I'm not sure.
if (data.status) {
$(this).find('input').val('');
// code to redirect to success page here
}
If form is successfully sent, then set the value of all inputs in the sent form to a string with the length of 0.
$('form').submit(function(event) {
event.preventDefault();
if (!validateForm()) {
return false;
} else {
formSubmit($(this));
}
}
);
function formSubmit(form) {
var url = form.attr('action');
var method = form.attr('method');
var data = form.serialize();
$.ajax({
method: method
, url: url
, data: data
})
.done(function (data) {
try {
$(this).find('input').val('');
// code to redirect to success page here
} catch (e) {
console.log(e);
}
});
}
FE validation is bad practice in my honest opinion, just good for lowering the amount of HTTP requests to the server. The hard form data validation should happen on the BE.

Validate a simple HTML form via JSON answere

I´am a UX designer and one of these JS dummie/"HTML coder" guys.
I need help or a hint to validate a simple HTML form via a second request which returns a JSON answere, before the form is send.
I have a really simple HTML form on a landingpage where the user can enter a coupon code:
<form id="tokensubmit" method="GET" action="https://www.xyz/cart.html">
<div class="form-group">
<input type="text" name="tokenCodeAdd" id="tokenCodeAdd" size="25" value="" class="form-control input-lg" placeholder="Please enter Coupon Code">
</div>
<input id="input_id" type="submit" class="btn btn-lg btn-warning btn-block" value="Submit">
</form>
If a user enters his Coupon code and hit the submit button, the code will be added to the action URL (https://www.xyz/cart.html) and the User is redirected to this cart.html page. If the coupon code is correct everything is fine. If not he receives an error message on the cart.html page.
So far so good.
BUT: I want to validate the coupon code without redirecting the user to a new website(cart.html).
The system offers a second URL for this already. A url like:
/checkout/validate.html?tokenCode=12345678
This returns a JSON answere with a status like:
{"error":"Wrong Coupon Code."}
if the Coupon code isnt right.
If it is valid, something like:
{"error":"null"}
returns.
What I am searching for is a simple solution to call the validation URL (validation.html) first on click on the "submit" button, parse the returning JSON, prevent the form from sending if "error" is something else than "null" and print the JSON message ("Wrong Coupon Code.") right above the form input.
If "error" = "null" the forms behavior should not change. It should just open the https://www.xyz/cart.html URL with the tokenCode attached as parameter.
What I´am trying/starting with looks like:
$('#tokensubmit').submit(function(event){
event.preventDefault();
var tokenCheck = $(this).find('input[id="tokenCodeAdd"]').val();
$.ajax({
url: '/checkout/validate.html'+tokenCheck,
type: 'GET',
success: function(data){
var jsonData = $.parseJSON(data);
}
});
});
Its just the beginning, I know. The real parsing part is missing and the error message output if the validation fails, or the redirect if not.
Anyone who could help?
And thx in advanced!
Small hint: The form is placed on a WordPress driven landingpage, so PHP and JQuery is an option.
The code you have for getting the validation is almost correct:
$('#tokensubmit').submit(function(event){
event.preventDefault();
var tokenCheck = $(this).find('input[id="tokenCodeAdd"]').val();
$.ajax({
// either attach the parameter like you are trying to do directly to the url,
// but in this way:
url: '/checkout/validate.html?tokenCode='+tokenCheck,
// or give the URL parameter(s) as data object to jQuery:
data: {
tokenCode: tokenCheck
}
type: 'GET',
// if you specify the dataType you want to receive as json,
// jQuery will parse it for you already
dataType: 'json',
success: function(data){
// now you can check the data for error or not, for example like:
if(data.error == null){
// do something (most likely REALLY submit the form now?)
}else{
alert('tokenCode invalid');
}
}
});
});
With jquery you can send through a data parameter and it will work out how to place it in the URL:
$.ajax({
url: '/checkout/validate.html',
type: 'GET',
data: {"tokenCode": tokenCheck}
success: function(data){
var jsonData = $.parseJSON(data);
}
});
I would also advise not doing an Ajax request at all if tokenCheck is empty.
Wouldn 't it be easier to check the coupon code when the user leaves the input field? First the example while submitting the whole form.
$('#tokensubmit').on('submit', function(event) {
event.preventDefault();
var validationSuccess = false;
$.ajax({
url : '/checkout/validate.html',
type : 'GET',
data : { tokenCode : $('#tokeninput').val() }
success : function(response) {
var data = $.parseJSON(response);
if (data.error === null) {
validationSuccess = true;
}
}
if (validationSuccess === true) {
$('#tokensubmit').off('submit').submit();
}
});
So what we 've done here? The submit event listener is nearly the same you 've done. We prevent the default submitting of the form and do an ajax request for validation the input value. If the request returns no error as response, we simply unbind the submit event listener from the form and submit the form again.
In my opinion it would be better to work with the blur event listener on the input field. In combination you could use the HTML5 Constraint Validation API. So you don 't have to submit the form and the ajax request would be done on blurring the input field. I think that would be the better user experience.
So here 's the blur event listener:
<input type="text" name="the-input-field" id="the-input-field" value="" required>
$('#the-input-field').on('blur', function(event) {
var element = this;
$.ajax({
url : '/checkout/validate.html',
type : 'GET',
data : { tokenCode : element.val() }
success : function(response) {
var data = $.parseJSON(response);
if (data.error !== null) {
element.setCustomValidity('Your input is invalid!');
// place some error message elsewhere in the markup
} else {
element.setCustomValidity('');
}
}
});
});
First we placed the required Attribute in the input element. It marks the input element as required. So if it 's empty you could not submit the form. Then we placed the blur event listener, which is doing the ajax request. If the response is false, we place a custom error via setCustomValidity. It is a native HTML5 Constraint Validation API function. If the custom error on the input element is set, you could not submit the form. If the user enters another token the request is done again on leaving the input element. If the token is valid, the custom error message will be removed and the form can be submitted.

How to send data to post method of node js using AJAX/jQuery?

I have a udp server that sends back different message each time a message is sent to it. If i hard code the message into the var message, then everything works. But i want the client to able to manually type in a message, then when the refresh button is pressed, the ajax re sends that same inputted message again. Right now, nothing happens when the button is pressed because ajax doesn't know what req.body.number is.
You can use jQuery's $.post() method to send a json object, or you can url encode parameters:
JSON:
$.post('/output2', {number: 'value1'}, function(data){
// Do things
});
URL:
$.post('/output2?number=value1', function(data){
// Do things
});
To receive these parameters on your post route you can use the req.body variable:
app.post('/output2', function(req, res){
var number = req.body.number;
// Do things
});
The way you have your form set up you don't really need jQuery post method to do this. If you did want a full jQuery submission though, add this to your index2.html.
<script>
$(function(){
$(document).on('submit', 'form', function(e){
e.preventDefault();
var formdata = { number: $('input[name="number"]').val() };
$.post('/output2', formdata, function(data){
alert(data);
});
});
});
</script>
modified a little bit code from wrxsti, We don't need to let a var formdata, just use:
$("#submit").on("submit",function (e) {
e.preventDefault();
$.post("http://localhost:5000/post/comment",$(this).serialize(), function( data ) {
console.log(data);
});
});

Download file via jquery ajax post

I am trying to export my web page data and download it as excel file. but the download does not start even the response return succeed.
$.ajax({
type: "POST",
url: _url,
contentType: 'multipart/form-data;boundary=SzB12x',
data: json,
});
The responseText something like this:
PK�J;Fxl/theme/theme1.xml�YOo�6����,[r��n;v��i����#-�kJH:�oC{0X7�2��mZ���d��u#�(٦b:M���������{|��^�0t#��*"w$�!0I�[�՚n�i��'����iH� g�,��|�J�!���hRh�h��?r&�L ���߶S��v#���#��׮�"���}��Жt%�hR�t"������+��������u{ނ��0K���oy�9OTWywkAͯ�
���F�� 6*�����[���U���
I think its the file but I cant download it!!
Any help please?
Thanks!
I faced the same issue and successfully solved it. My use-case is this.
Post JSON data to server and receive an excel file.
That excel file is created on the fly and returned as a response to client.
Code:
$("#my-button").on("click", function() {
// Data to post
data = {
ids: [1, 2, 3, 4, 5]
};
// Use XMLHttpRequest instead of Jquery $ajax
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
var a;
if (xhttp.readyState === 4 && xhttp.status === 200) {
// Trick for making downloadable link
a = document.createElement('a');
a.href = window.URL.createObjectURL(xhttp.response);
// Give filename you wish to download
a.download = "test-file.xls";
a.style.display = 'none';
document.body.appendChild(a);
a.click();
}
};
// Post data to URL which handles post request
xhttp.open("POST", excelDownloadUrl);
xhttp.setRequestHeader("Content-Type", "application/json");
// You should set responseType as blob for binary responses
xhttp.responseType = 'blob';
xhttp.send(JSON.stringify(data));
});
The above snippet is just doing following
Posting an array as JSON to the server using XMLHttpRequest
After fetching content as a blob(binary), we are creating a downloadable URL and attaching it to invisible "a" link then clicking it.
Here we need to carefully set few things at the server side. I set few headers in Python Django HttpResponse. You need to set them accordingly if you are use other programming languages.
# In python django code
response = HttpResponse(file_content, content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
Since I download xls(excel) here, I adjusted contentType to above one. You need to set it according to your file type.
Try to use a hidden form to submit the request.
When a user submits an HTML form, all the data entered into the form by the user is sent as either a GET or POST request to the URL specified in the “ACTION” attribute of FORM.
<FORM action="http://www.labnol.org/sendmail.php" method="post">
...form contents...
</FORM>
In the above example, an HTTP POST request is issued to the sendmail.php script on form submission. You can add target=”_blank” to the FORM tag to process the request in a new window.
However, if you would like to submit a FORM on the page in the background without directing the browser to another page (document.location.href changes on form submit), you have two options:
Option #1. You can either create an invisible IFRAME inside your HTML page and set that as a target for the Original FORM. This will submit the form but without reloading the parent window.
<FORM action="http://example.com/script.php"
method="POST" target="hidden-form">
...form contents...
</FORM>
<IFRAME style="display:none" name="hidden-form"></IFRAME>
Option #2: There’s another method that allows you create custom payloads before submitting the form. Unlike the IFRAME based form submission, the following code makes a standard form submit request and thus your browser location will change and the current page will get added to the browser history. Credit: Rakesh Pai.
submitFORM('http://example.com/script.php', 'POST',
{'name':'digital+inspiration', 'age':'100', 'sex','M'});
function submitFORM(path, params, method) {
method = method || "post";
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
//Move the submit function to another variable
//so that it doesn't get overwritten.
form._submit_function_ = form.submit;
for(var key in params) {
if(params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form._submit_function_();
}
In this link you can find the way to create hidden form and submit it.
enjoy!!
The approach here is directly lifted from https://gist.github.com/DavidMah/3533415.
This approach uses <form> and appends the data with a key. This approach works if the server is already expecting the data as an attribute of the request body, as opposed to being the request body itself. If the data to be uploaded is an object, you could iterate over that object's keys. If the data to be uploaded is an array, either modify the server route or [add idea here].
In browser
// Takes a URL, param name, and data string
// Sends to the server... The server can respond with binary data to download
jQuery.download = function(url, key, data) {
// Build a form
var form = $('<form></form>').attr('action', url).attr('method', 'post');
// Add the one key/value
form.append($("<input></input>").attr('type', 'hidden').attr('name', key).attr('value', data));
//send request
form.appendTo('body').submit().remove();
};
On server
# A Tidbit of sinatra code to respond
# Assume 'url' is a set variable
# Assume 'key' is the key of the value used in the javascript
post url do
data = params[:key]
puts request.body.read
headers['Content-Type'] = "application/octet-stream"
body(data)
end
Example
$.download('/path/resource/', 'data', JSON.stringify(data))
If you just want to download a file, you don't need to use ajax to do it. Actually, you cannot download file using ajax.
You can still do it by making a hyperlink Export request to a server page that responses content-type is application/vnd.ms-excel and content-disposition is attachment.
You can achieve this using an iFrame as well. A sample function:
// append the data to URL
var requestData = {
param1 : "value1",
param2 : "value2",
}
// call the function
downloadFile(<your_URL>, requestData);
function downloadFile(requestURL, data) {
// "transData" is just a user defined variable to encapsulate "downloadIFrame". It can be named anything as required.
var downloadIFrame = window.transData.downloadIFrame = window.transData.downloadIFrame || $("#downloadFileiFrame");
downloadIFrame.attr("src", requestURL + $.param(requestData));
}
// define the iFrame in your HTML and hide it.
<iframe id="downloadFileiFrame" style="display:none;"></iframe>"
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: yoururlpath,
success: function (response) {
var file = fileName+".xlsx";
window.location = "someFilePath?file=" + file;
}
});

How to submit a dynamically generated form to AJAX?

I have an AJAX call which dynamically generates a HTML form. This form contains a number of elements including inputs, selects, textareas, checkboxes as well as etc.
I need to write some javascript (jquery available) to get all the fields in this form and submit them to an AJAX script. I won't know how many or what fields are there (only a basic idea) as it all depends on what the user does.
Any ideas how to do this? Lets say my form name is 'ajaxform'
As everyone said, use jQuery serialize. One other note is to override your form submit (if needed) via jQuery live method:
//Override form submit
$("form").live("submit", function (event) {
event.preventDefault();
var form = $(this);
$.ajax({
url: form.attr('action'), // Get the action URL to send AJAX to
type: "POST",
data: form.serialize(), // get all form variables
success: function(result){
// ... do your AJAX post result
}
});
});
var string_ready_to_be_posted = $("#formId").serialize();
http://api.jquery.com/serialize/
You can use jQuery's .serialize():
var data = $('#ajaxform').serialize();
var action = $('#ajaxform').attr('action');
$.post(action, data, function(data) {
...
});
var string_ready_to_be_posted = $('form[name="ajaxform"]').serialize();
As addon for using NAME-selector instead of ID

Categories