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
Related
Is it possible to pass an array that is populated via checkboxes to another page via AJAX POST and navigate to that page?
The current scenario is I have a table with checkboxes that allows the user to select the checkboxes to pay for multiple items. The issue is passing that multiple ids to the payment page. Are there any suggestions as to how I can do it?
This is what I have so far:
function pay(input){
var id = input;
$.ajax({
method: "POST",
url: "<?php echo site_url($this->data['controller'].'/Pay'); ?>",
data:'id='+id,
beforeSend: function () {
$('.loading').show();
},
success: function(data){
//what do i fill here
}
});
}
Or is there an alternate method of doing this?
I will break this question down into 2 questions:
Is it possible to pass an array that is populated via checkboxes to
another page?
Why yes use square brackets in the input name to make it an array.
<input type="checkbox" name="id[]" value="2">
<input type="checkbox" name="id[]" value="6">
in PHP you can access the selected item ids like this:
$selectedItemIDs = $_POST['id'];
// $selectedItemIDs is now [2, 6] if both checkboxes were selected.
Can I pass an array to another page via AJAX POST and navigate to that
page?
IIRC this is not possible without using a dirty workaround. JavaScript and jQuery do not provide this functionality.
To find the workaround you have to realize that what you are trying to do is simply navigate to a different page, with POST parameters.
Don't forms do exactly that? Yes, they do!
The dirty workaround i was talking about is of course a hidden form where you fill all needed information with JS / jQuery and submit it. Here is a stackOverflow post about this
In your situation though, I would just use the form that you already have (with the multiple checkboxes), since you can easily pass an array of checkbox-values with a form.
The data parameter is not a string when making a POST request. Save all of your form data to a variable and assign that variable to the "data" element of the POST call. You can do this like so:
var myform = $('form').serialize(); // This will save all the form's data to the variable myform
and then
data: myform, // This will send what myform contains via POST
Inside "success" you get to parse the information from the POST response.
After that you can redirect using:
window.location.href = 'http://yourlink.here'; //this will redirect you to another page
Through an array you can post it to ajax
var check_box_array = [];
$("input:checkbox[name=type]:checked").each(function(){
check_box_array.push($(this).val());
});
and then
$.ajax({
method: "POST",
url: "<?php echo site_url($this->data['controller'].'/Pay'); ?>",
data:{check_box_data:check_box_array},
beforeSend: function () {
$('.loading').show();
},
success: function(data){
//what do i fill here
}
});
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.
I am using the plugin jquery.form.js and I want to programmatically submit a form and include a file with it. The code and options I have set up with work with $.ajax but not .ajaxSubmit. According to the jquery.form.js documentation you can pass any standard $.ajax options to .ajaxSubmit but I can't seem to get it to work. I'd like to use .ajaxSubmit if possible so I can utilize some of the other features it offers.
$(document).ready(function() {
$('#file-form').submit(function(event) {
event.preventDefault();
var form = $("<form style='display:none;' method='post' action='video_upload.php' enctype='multipart/form-data'></form>");
var fd = new FormData();
fd.append('uploadedfile', $('#file')[0].files[0]);
var options = {
url: 'video_upload.php',
data: fd,
processData: false,
contentType: false,
type: 'POST',
beforeSend: function(xhr){
alert('start');
},
success: function(data){
alert(data);
}
};
$.ajax(options);
//form.ajaxSubmit(options);
return false;
});
});
Running $.ajax(options) works but form.ajaxSubmit(options) doesn't. What am I missing?
Thanks!
If you check the source code of the method ajaxSubmit - http://malsup.github.io/jquery.form.js you can see that the property data of the options is serialised/deserialised and converted several times. So most likely the content really submitted will be quite different from what happens in .ajax call. Later on the ajaxSubmit collects the files from form and submits them differently.
Basically, for me the specifying data while submitting with ajaxSubmit goes against the concept of this plugin, which is described as "The main methods, ajaxForm and ajaxSubmit, gather information from the form element to determine how to manage the submit process." Idiomatic way of using ajaxSubmit would be applying this method for the form with controls.
I have this code
$("#dummy_div").on('submit', "form", function(event){
console.log(event);
event.preventDefault();
});
Does the event object contain hold the query string or data of the submitted form? If not, is there a way to get them short of iterating over the form fields?
no the event doesn't store the querystring, but you could obtain all the fields value via serialize() jQuery method applied to the form to obtain a querystring-like value
See http://api.jquery.com/serialize/ for further reference
Getting the query string for a form is quite easy, just use .serialize(). .serializeArray() may be also helpful
You can use serialize
$("#dummy_div").on('submit', "form", function(event){
event.preventDefault();
var form = $(this);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
success: function(r) { }
});
});
How can I find ID/Class of the current form within the ajax success function? Since there are multiple forms with the same Class, I cant simply search for the class, but need exactly the form that was submitted.
I have following script:
$('#fAddOs,#fAddFs,.addJ').submit(function(){
//$(this) = form
$.ajax({
type:'POST',
url:'admin.inc.php',
data:data,
dataType:'html',
success:
function(response){
//Get form
}
});
});
If I call $(this) within the AJAX function (see my comment in the code above), I get:
[Object { url="admin.inc.php", isLocal=false, global=true, mehr...}]
outside the ajax call, save the form to a variable that you can use inside the ajax callback.
$('#fAddOs,#fAddFs,.addJ').submit(function(){
var form = $(this);
$.ajax({
type:'POST',
url:'admin.inc.php',
data:data,
dataType:'html',
success:
function(response){
// use the form variable here...
console.log(form.attr('id'));
}
});
});
With the selector you're using, you are grabbing multiple elements. Inside the submit, the current form being worked with can be accessed using this. Or to use it as a jQuery object $(this).
In the function:
var id = $(this).attr("id");
Or to grab the class name
var class = $(this).attr("class");
UPDATE
Before the ajax call, create a var:
var form = $(this);
then use form in the ajax function
Try this within the submit function:
var id = this.id;