How to include button value in jQuery serialize() function? - javascript

I got two buttons in the form.
<button type="submit" class="btn btn-danger" value="Send Back" name="Save">Send Back</button>
<button type="submit" class="btn btn-primary" value="Approve" name="Save">Approve</button>
When I post the form data using jquery $.ajax(), the form data is serialized first.
(function () {
'use strict';
function process(event) {
event.preventDefault();
var $form = $(this);
var data = $form.serialize();
console.log('posted data', data);
$.ajax({
type: 'POST',
url: url,
data: data
}).done(function(data) {
...
});
}
$(document).on('submit', 'form', process);
})();
Here in the output of my console.log(), I can see all other fields in the form are serialized, but the value on the submit button is lost.
Is there some setting to tell jQuery to include the button value for the serialize() function?

You can know which button was clicked thanks to document.activeElement.
So if you want the value of the button you can just just take the value attribute, encode it and put in at the end of your uri parameters.
(function () {
'use strict';
function process(event) {
event.preventDefault();
var $form = $(this);
var data = $form.serialize()+'&save='+encodeURI(document.activeElement.getAttribute('value'));
console.log('posted data', data);
$.ajax({
type: 'POST',
url: url,
data: data
}).done(function(data) {
...
});
}
$(document).on('submit', 'form', process);
})();

Try with map() function and create the string like serialize()
var res = $('form').children().map(function(){
if($(this).attr('name')) //prevent the element without name
return $(this).attr('name')+'='+$(this).attr('value')
}).get();
console.log(res.join('&'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input name="sss" value="ssss">
<input name="sss" value="ssss">
<button type="submit" class="btn btn-danger" value="Send Back" name="Save">sss</button>
<p>ddddddddd</p>
<button type="submit" class="btn btn-primary" value="Approve" name="Save">sss</button>
</form>

I use this
var $form = $(this);
var data = $form.serialize()+'&' + encodeURI(document.activeElement.getAttribute('name')) + '='+encodeURI(document.activeElement.getAttribute('value'));

Related

Disable button with value after submit

How can I block submit after click? I have form with button submit with value.
<button type="submit" name="submit" value="1" class="btn btn-sm btn-warning" id=""><i class="fa fa-pencil" aria-hidden="true"></I>Save edit</button>
And my JS looks this:
$(function(){
$("form").submit(function (e) {
$(".btn").attr("disabled", true);
return true;
});
});
Button is blocked but form is not submitting, I don't know why?
$(function(){
$("form").submit(function (e) {
$(".btn").attr("disabled", true);
return true;
});
});
Here the line written as return true prevents the form from being sent and leaves it with the true.
This is what should be written.
$(function(){
$("form").submit(function (e) {
$(".btn").attr("disabled", true);
});
});
Edit
Using AJAX
$(function() {
$("#myForm").on('submit', function(event) {
var form = this;
// Prevent native form submit!
event.preventDefault();
// Disable Button
$(".btn").attr("disabled", true);
// Submit form with AJAX
$.ajax({
url: $(form).attr('action'), // URL where we will send the form
data: $(form).serialize(), // Serialize form data automatically,
type: 'POST',
beforeSend: function() {
alert('The form is sent to: ' + $(form).attr('action') + ' \nForm data: ' + $(form).serialize());
},
success: function(response) {
alert(response); //or whatever
},
error: function() {
alert('Failed!\nBecause "' + $(form).attr('action') + '" not a valid URL'); //or whatever
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myForm" action="//localhost/some-page.html">
<input name="txt" value="TXT" />
<button type="submit" name="submit" value="1" class="btn btn-sm btn-warning" id=""><i class="fa fa-pencil" aria-hidden="true"></I>Save edit</button>
</form>
I thing it is work in your case:
$(document).ready(() => {
$('#yourFormIDhere').on('submit', () => {
$.ajax({
url:"/your_url",
method:"POST",
beforeSend:function() {
$('.btn').attr('disabled', 'disabled');
},
})
});
});
Your question is not really clear,
I don't really understand what you are trying to do.
Do you want the button to be blocked after you click the button and the form to be submitted?
If you are trying to make the form submit then remove
return true;

jQuery Ajax POST save delete submit

Here is my code
<form method="post" role="form" id="form" enctype="multipart/form-data" autocomplete="off">
<input type="submit" id="save" name="save" value="Simpan Data Client" class="btn" style="font-size:0.7em; letter-spacing:1px; color:#666666" /> //For save
<input type="submit" id="delete" name="delete" value="Delete Client" class="btn-delete" style="font-size:0.7em; letter-spacing:1px; color:#666666; padding:8px 15px" /> //For Delete
</form>
<script type="text/javascript">
$("#form").on("submit",function (e)
{
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax(
{
url:'Master/Database/Client/RunClient.php',
type: 'POST',
data: formData,
contentType: false,
enctype: 'multipart/form-data',
processData: false,
beforeSend:function()
{
document.getElementById("loading").style.display = "";
},
complete:function()
{
//document.getElementById("loading").style.display = "none";
},
success:function(result)
{
document.getElementById("info").innerHTML = result;
var n = result.search("error");
if(n < 0) /*document.getElementById("form").reset();*/ $(".input").val('');
}
});
});
</script>
I can get all data from inside my form except from Input type submit i make.
I can't use isset($_POST["save"]) and isset($_POST["delete"]) at my RunClient.php
Create separate function for a submit and pass "submit type" depending on what button is clicked;
$('#save').click(function() {
submitForm('save');
});
$('#delete').click(function() {
submitForm('delete');
});
function submitForm(submittype) {
var formData = new FormData();
//push your form data to formData and add the submittype
formData['type'] = submittype
}
in your php file
$submittype = $_POST['type']; // 'save' or 'delete'
if($submittype == 'save') {
//do save action
}
if($submittype == 'delete') {
//do delete action
}
I use to avoid submit inputs and change by buttons.
<button type="button" id="save">SUBMIT</button> //For save
<script type="text/javascript">
$("#save").on("click",function (e)
{
});
</script>
So, if anyone deativates javscript form will not submit.
And you can send the data like this:
data: {
foo: 'var'
foo2: 5
},
EDIT. Sorry missunderstood your question.
Just control with javascript what button is clicked and assign a value with a hidden field.
'$("#form").on("submit",function (e)' replace the function with
$("#save").click(function() {
});
$("#delete").click(function() {
});

AJAX loading my php page is not working

I have code to load my bookmark.php via AJAX when clicking submit but when I'm clicking it alert was popping up but bookmark.php is not working properly.
Here is my code in below:
What am I missing ?
PHP:
require_once 'class.trip.php';
$trip = new TRIP();
$save = $trip->saveTrip();
HTML/AJAX:
<script type="text/javascript">
$(function () {
$('#joinform').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'bookmark.php',
data: $('#joinform').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
</script>
<form id="joinform">
<input name="submit" type="submit" class="btn btn-success btn-lg" value="Join This Trip"/>
</form>

Using JQuery and AJAX to pass data to a PHP script

I have an HTML form that Is only composed of a button with a value. I would like to leave it this way. I am using AJAX/JQuery to pass the form data to a PHP script. But, for some reason, the button value is not sent. What could I be doing wrong?
HTML:
<form id="friend-send" method="post" action="">
<button type="submit" class="foll" name="approve-friend" value="4"> Approve </button>
</form>
AJAX/JQUERY:
$(document).ready(function() {
$("#friend-send").submit(function(e) {
var $this = $(this);
var dataString = $this.serialize();
e.preventDefault();
$.ajax({
type: "POST",
url: "relate.php",
data: dataString,
async: false,
success: function() {
$this.hide();
}
});
});
});
JQuery won't serialize a button, use a hidden field instead
<form id="friend-send" method="post" action="">
<input type="hidden" name="approve-friend" value="4" />
<button type="submit" class="foll"> Approve </button>
</form>
Also, You need to serialze the form by id, not the button by id
Instead of this
$("#friend-request-buttons")
It should be this
$("#friend-send")
Lastly, since you are using ajax to post, you can simplfy your form open tag to this...
<form id="friend-send">
<button>
tags are not supported by serialize https://api.jquery.com/serialize/
You would need to use an input of some kind. A hidden one would work.
Don't use serialize, create the input data yourself:
var dataString = {};
var $button = $this.find("[type=submit]");
dataString[$button.attr('name')] = $button.val();
When you provide an object as the data: argument to $.ajax, jQuery will serialize it automatically.
This answer would be if you are set on using the button alone
$(document).ready(function() {
$("#friend-send").submit(function(e) {
var $this = $(this);
var dataString = "?" + $(this).find('button').attr('name') + "=" + $(this).find('button').attr('value');
e.preventDefault();
$.ajax({
type: "POST",
url: "relate.php",
data: dataString,
async: false,
success: function() {
$this.hide();
}
});
});
});

jQuery ajax post strange behaviour

I have an ajax function to calculate and perform a certain validation.
Code is shown below:
function collectFormData(fields) {
var data = {};
for (var i = 0; i < fields.length; i++) {
var $item = $(fields[i]);
data[$item.attr('name')] = $item.val();
}
return data;
}
function calculate(){
var $form = $('#purchase-form');
var $inputs = $form.find('[name]');
var data = collectFormData($inputs);
$.ajax({
url: '${validateUrl}',
type: 'POST',
data: data,
contentType: 'application/json; charset=utf-8',
success: function (response) {
alert(response.status);
},
error: function () {
alert("error");
}
});
}
HTML:
<button id="calculateBtn" class="btn btn-primary" onclick="calculate();">
<spring:message code="button.calculate" />
</button>
However, as soon as the above function called my form is being submitted. What might cause this ?
It is because you have a form with a button, whose default behaviour is to submit the form. If you do not want to submit the form then you need to prevent the default action of the button on click.
Since you are using jQuery I recommend using jQuery to register the click event instead of using onclick attribute and the calculate method has to return false value to prevent the default click event from happening.
Change to
<button id="calculateBtn" class="btn btn-primary">
<spring:message code="button.calculate" />
</button>
function calculate(){
var $form = $('#purchase-form');
var $inputs = $form.find('[name]');
var data = collectFormData($inputs);
$.ajax({
url: '${validateUrl}',
type: 'POST',
data: data ,
contentType: 'application/json; charset=utf-8',
success: function (response) {
alert(response.status);
},
error: function () {
alert("error");
}
});
return false;
}
$(function(){
$('#calculateBtn').click(calculate)
})
Try setting the 'type' attribute on the button to 'button'
<button type="button" id="calculateBtn" class="btn btn-primary" onclick="calculate();">
<spring:message code="button.calculate" />
</button>
The default value of the type attribute is 'submit': https://developer.mozilla.org/en-US/docs/HTML/Element/button

Categories