I am using jQuery's serialize(). But in this case, it is not picking up my input fields that are created via some JavaScript code in a called PHP page in $(document).ready(function (). I did an alert but the input fields were not in the JSON string.
The serialize() call is actioned by a submit action.
I tried both these but neither worked.
var dataString = $( "input" ).serialize();
var dataString = $(this).serialize().replace(/\'/g,'\\\'');
I am guessing it is becuase they are generated at runtime.
Any help is much appreciated.
var url = "../js/contactmail.php";
var dataString = $(this).serialize().replace(/\'/g,'\\\'');
$.ajax({
type: "POST",
url: url,
data: dataString,
success: function (data) {
var arraydata = $.parseJSON(data);
}
});
Code auto generated by JavaScript at runtime:
<div class="col-md-12">
<input data-prefix="thé" data-suffix="tea" id="tea" type="number" value="0"
min="0" max="10" step="1" style="display: none;">
<div class="input-group ">
<div class="input-group-prepend">
<button style="min-width: 2.5rem" class="btn btn-decrement btn-outline-secondary" type="button">
<strong>-</strong>
</button>
<span class="input-group-text">thé</span>
</div>
<input type="text" inputmode="decimal" style="text-align: center" class="form-control " placeholder="" />
<div class="input-group-append">
<span class="input-group-text">tea</span>
<button style="min-width: 2.5rem" class="btn btn-increment btn-outline-secondary" type="button">
<strong>+</strong>
</button>
</div>
</div>
</div>
Okay.. after some trial and error I have realised that serialize() uses HTML name Attribute and not the ID Attribute. So the answer is to include name = 'tea'
Related
Let me describe what does the codes are doing. It is a simple form of html. Here is two box. When user type a name (the name must exist in the list that I clawed from other website) in the second box. The firstbox would show the id of the name. When someone click the "clone" button the programe would clone the form and change its id.
Here is my question:
How can set autocomplete automatically when I clone the form.
How can I autocomplete the first box (id of the name,id="Rent_form_g_ID") while user type the name in the second box (id="Rent_form_g_name").
The following code only run when I didn't clone anything.
This is my code:
<body>
<form>
<div class="row" id="general_form">
<div class="col-2">
<label for="Rent_form_g_ID" class="form-label">id of name</label>
<input type="text" class="form-control"id="Rent_form_g_ID" value="" disabled readonly>
</div>
<div class="col-2">
<label for="Rent_form_g_name" class="form-label">name</label>
<input type="text" class="form-control" placeholder="enter the name" id="Rent_form_g_name">
</div>
<div class="col-2">
<button type="button" class="btn btn-primary btn-block" onclick="delete_data(this.id)">delete</button>
</div>
<br>
</div>
</form>
<div class="row">
<hr>
<button type="button" class="btn btn-primary btn-block" onclick="append_a_data()">新增一筆資料</button>
</div>
<body>
<script>
var general_data={};
var general_name=[];
var general_key=[];
//get general data via api
//analyze the data which i get
var url='https://ap3.ragic.com/haisann/forms2/1?api=true';
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", url, false ); // false for synchronous request
xmlHttp.send( null );
general_data=JSON.parse(xmlHttp.responseText);
console.log(general_data);
for(var i in general_data){
general_key.push(general_data[i]["財產編號"]);
general_name.push(general_data[i]["財產名稱"]);
};
console.log("get general data ssucess fully");
function link_autocomplete_data($id){
//連結財產資料
$('#'+$id).autocomplete({
source: general_name
});
}
var cloneCount = 1;//clone
//clone sub form and change id
function append_a_data(){
var $html=$('#general_form').clone().attr('id', 'general_form'+ cloneCount).insertAfter($('[id^=general_form]:last'));
$('#general_form'+ cloneCount).find('#Rent_form_g_ID').attr('id','Rent_form_g_ID'+cloneCount);
$('#general_form'+ cloneCount).find('#Rent_form_g_name').attr('id','#Rent_form_g_name'+cloneCount);
link_autocomplete_data('Rent_form_g_name'+cloneCount);
cloneCount++;
};
function delete_data($id){
$('#'+$id).parent().parent().remove();
};
$(document).ready(function(){
link_autocomplete_data("Rent_form_g_name");
// also I don't know how to write this programe better
$('#Rent_form_g_name').click(function() {
$(this).change(function(){
var g_name=$('#Rent_form_g_name').val();
for(i in general_data){
if(general_data[i]["財產名稱"]==g_name){
$('#Rent_form_g_ID').val(general_data[i]["財產編號"])
$('#Rent_form_g_stock').val(general_data[i]["財產數量"])
};
};
});
});
})
</script>
<form id="pricing_plan_form" action="" method="POST" class="prcCF_box">
<div class="price_form_opt">
<div class="pcf_col">
<div class="pcf_col_inner">
<h2 class="number_no">1.</h2>
<span>
<span class="title_1">Are your married?</span>
<span class="title_not">(or might as well be)</span>
</span>
</div>
<div class="pcf_col_op_fields pcf_swt">
<span>no</span>
<label class="switch">
<input class="onoffsw" name="married" type="checkbox">
<span class="slider_swt round"></span>
</label>
<span>yes</span>
</div>
</div>
<div class="pcf_col">
<div class="pcf_col_inner">
<h2 class="number_no">2.</h2>
<span>
<span class="title_1"># of children running<br>wild in your house?</span>
</span>
</div>
<div class="pcf_col_op_fields">
<span id="ratext1">0</span>
<input name="children" type="range" min="0" max="5" value="0" class="slider_ran" id="myRange">
<span>5+</span>
</div>
</div>
<div class="pcf_col">
<div class="pcf_col_inner">
<h2 class="number_no">3.</h2>
<span>
<span class="title_1"># of siblings who<br>still talk to you?</span>
</span>
</div>
<div class="pcf_col_op_fields">
<span id="ratext2">0</span>
<input name="siblings" type="range" min="0" max="10" value="0" class="slider_ran" id="myRange2">
<span>10+</span>
</div>
</div>
</div>
<input type="submit" value="Submit">
</form>
jQuery(document).ready(function($){
var frm = $('#pricing_plan_form');
frm.submit(function (e) {
e.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm,
success: function (data) {
console.log('Submission was successful.');
console.log(data);
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
});
});
});
I am new in javascript/jquery. I am creating a pricing sorting option with the form. when the user selects the necessary values the automatically a recommended packet will be shown. I have created the form when I submit the form data of the whole page is shown. I am not getting form data separately. Can anyone help me with the problem? I will be using it on PHP. And the form and product items are on the same page.
` $('#pricing_plan_form').on('submit', function () {
var that = $(this),
url = that.attr('action'),
method = that.attr('method'),
data = {};
that.find('[name]').each(function ( index, value ) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = parseInt(value);
});`
I have feeling (not 100% sure) you have to disable them selectively, would something like this work?
if (your condition) {
$("#formField").attr("disabled", "disabled");
} else {
$("#formField").removeAttr("disabled");
}
Another thing is that you have a full submit button which will trigger the original form even if you will make yours in ajax, the underlining HTML doesn't know what magic JS is doing behind it's back (and if it should stop submitting the form). To fix that you can make form without a valid HTML submit button, and only rely on the bind JS to do the job. Would remove
<input type="submit" value="Submit">
And just make a button of type button (no pun intended) which then could do extra JS hackery without HTML doing its thing:
https://www.w3schools.com/tags/att_button_type.asp
<button type="button|submit|reset">
I am trying to insert some HTML before a divider class="replydivider" using insertBefore() but I can't get it to work. This is my code:
<div class="col-sm-12 mb-2 replydivider">
<div class="row">
<div class="col-sm-2 offset-1">
<img src="/assets/uploads/user/<?=$_SESSION['userImage'];?>" class="border rounded-circle comment-user-img mr-3">
</div>
<div class="col-sm-8 rounded form-inline">
<form method="POST" class="form-group reply-form">
<input type="text" name="comment" class="form-control mr-2" placeholder="Reply here" required>
<input type="hidden" name="postId" value="<?=$id?>">
<input type ="hidden" name="replyId" value="<?=$row['commentId'];?>">
<input type="submit" class="btn-sm btn-primary" value="Reply">
</form>
</div>
</div>
</div>
The issue I'm having is it has to be inserted before the div relative to the form that is submitted as there will be many replydividers and forms on the page.
I've tried the following and countless variations but can't get it to work:
$(this).closest('.replydivider').before(data);
$(this).closest('div').find(".replydivider").before(data);
$(this).closest('form').find(".replydivider").before(data);
$(data).insertBefore('.replydivider');
Any guidance would be appreciated.
EDIT:
This is my jquery function:
$(function () {
$('.reply-form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/comment/addComment',
data: $(this).serialize(),
success: function (data) {
alert('test');
var test = "<p>Sample data</p>";
$(this).closest('.replydivider').before(test);
}
});
$(this).closest('form').find("input[type=text]").val("");
});
});
Interestingly, if I put the $(this).closest('.replydivider').before(test); line outside the ajax call it works, but not inside it. I put the alert there to test it was returning successful and it is.
.ajax()
The this reference within all callbacks is the object in the context option passed to $.ajax in the settings; if context is not specified, this is a reference to the Ajax settings themselves.
If you want this in the callbacks to be the element that received the event then set the context property of Ajax like:
.......
context:this,
success: function (data) {
.......
I'm learning javascript/jquery on the go, I'm trying to reload a form but keeping its js properties (required and masked inputs), code and pictures attached.
First image: Masked inputs works like a charm
Second image: The form its fully filled, still working
Third image: The form it reloaded, but no properties applied
The html form (minmized, just the first field)
<div class="card-body" id="clientsAddFormContainer">
<form method="post" action="main/clients/addController.php">
<div class="form-group row" id="clientRutDiv">
<div class="col-lg-6">
<div class="form-group" id="clientRutInnerDiv">
<label class="col-form-label" for="clientRut">RUT <span class="required">*</span></label>
<input type="text" name="clientRut" id="clientRut" class="form-control" placeholder="Ej. 11.111.111-1" required="" data-plugin-masked-input="" data-input-mask="99.999.999-*" autofocus>
</div>
</div>
</div>
</div>
</form>
<footer class="card-footer">
<div class="switch switch-sm switch-primary">
<input type="checkbox" name="wannaStay" id="wannaStay" data-plugin-ios-switch checked="checked" />
</div> Mantenerme en esta página
<button type="button" style="float: right;" class="btn btn-primary" onclick="realizaProceso();">Enviar</button>
</footer>
The JS for realizaProceso()
function realizaProceso(){
var validator =0;
validator += validateRequiredField('clientRut');
if(validator == 0){
var parametros = {
"clientRut" : document.getElementById('clientRut').value,
"tableName" : 'clients'
};
$.ajax({
data: parametros,
url: 'route/to/addController.php',
type: 'post',
success: function (respText) {
if(respText == 1){
if(document.getElementById('wannaStay').checked){
$("#clientsAddFormContainer").load(location.href + " #clientsAddFormContainer");
}else{
window.location = "linkToOtherLocation";
}
}else{
showNotyErrorMsg();
}
},
error: function () {
showNotyErrorMsg();
}
});
}else{
showNotyValidationErrorMsg();
}
}
So my JS check all fields are validated, then prepare the array, and wait for the php binary response, 1 means the data has been inserted to db, if wannaStay is checked reload the div "clientsAddFormContainer" but as I said, it loose the properties.
Please sorry for my grammar or any other related english trouble, not a native english speaker.
Ps. I've removed some code so it could go different than the images.
Thanks in advance!
EDIT!
The original code is
<div class="card-body" id="clientsAddFormContainer">
<form method="post" action="main/clients/addController.php">
</form>
</div>
one the js exec I got
<div class="card-body" id="clientsAddFormContainer">
<div class="card-body" id="clientsAddFormContainer">
<form method="post" action="main/clients/addController.php">
</form>
</div>
</div>
2nd EDIT
I found the answer in other stackoverflow question
I want to populate multiple forms with multiple buttons on PHP loop from mysql. For each entry, I have 3 buttons to be handled with the same ajax calls. The issue I'm facing is to recognize which button is clicked and added it to the form data to be sent for a PHP file
function() {
var form = $('#PayBillFormForm0'); // will be different for each PHP loop
var formMessages = $('#PayBillResults0'); // will be different for each PHP loop
$(form).submit(function(e) {
e.preventDefault();
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url: "php/pay.php", // When pay0 button is clicked
url: "php/decline.php", // When decline0 button is clicked
data: formData
})
.done(function(response) {
var messageAlert = response.type;
var messageText = response.message;
var alertBox = '<div class="alert ' + messageAlert + '"style="margin-top:10px;"><d style="font-size:12px; ">' + messageText + '</d></div>';
(formMessages).html(alertBox);
$('#Bill0').delay(3000).fadeOut(2000); //Bill0 is different for each PHP loop
})
});
}
<div class="card" id="Bill0">
<div id="PayBillResults0"></div> <!-- To show Ajax Response Message -->
<div class="card-header">
<h1>XXX</h1>
</div>
<div class="card-body">
<form id="Form0" method="post" action="">
<input name="user" id="user" value="user" type="hidden">
<input name="id" id="id" value="9" type="hidden">
<input name="reciver" id="reciver" value="ppp" type="hidden">
<input name="amount" id="amount" value="333.0" type="hidden">
<input name="tax" id="tax" value="5.0" type="hidden">
<input name="comment" id="comment" value="XXX" type="hidden">
</form>
<div id="Buttons">
<div id="Pay">
<button form="" class="btn btn-success" id="pay0" value="pay0">Pay</button>
</div>
<div id="decline">
<button form="" class="btn btn-danger" id="decline0" value="decline0">Decline</button>
</div>
<div id="Hide">
<button form="" id="hide0" class="btn btn-warning" value="hide0">Hide</button>
</div>
</div>
</div>
</div>
I was able to perform this by labeling each form and labeling each button plus having multiple onclick functions as well as multiple jQuery codes. Any idea how to send clicked button value along with form data to PHP to handle differently.
When looping with PHP, you should NEVER use any id on elements. Use classes instead... Or some data attributes.
You were using unique ids by adding a number to them... Fine. But a class is more useful since you can add one event handler to a class... Instead of n event handlers for element created by the PHP iterations. So it avoid useless code duplication and just make sens.
That is what I suggest you now. Modify your PHP loop so it will create that HTML:
(I removed all that seemed useless)
<div class="card" data-id="0">
<div class="PayBillResults"></div> <!-- To show Ajax Response Message -->
<div class="card-header">
<h1>XXX</h1>
</div>
<div class="card-body">
<form>
<input name="user" value="user" type="hidden">
<input name="id" value="9" type="hidden">
<input name="reciver" value="ppp" type="hidden">
<input name="amount" value="333.0" type="hidden">
<input name="tax" value="5.0" type="hidden">
<input name="comment" value="XXX" type="hidden">
</form>
<div>
<div>
<button class="btn btn-success pay" value="pay">Pay</button>
</div>
<div>
<button class="btn btn-danger decline" value="decline">Decline</button>
</div>
<div>
<button class="btn btn-warning hide" value="hide">Hide</button>
</div>
</div>
</div>
</div>
See the data-id="0"? That is where you will have your form number using the PHP iteration counter.
Now here is the client-side script to use once (do not loop that):
$(document.ready(function(){
// Change the URL to use with Ajax on button click
var AjaxUrl = "";
$(".pay").on("click",function(){
AjaxUrl = "php/pay.php";
$(this).closest(".card").find("form").submit();
});
$(".decline").on("click",function(){
AjaxUrl = "php/decline.php";
$(this).closest(".card").find("form").submit();
});
// Form submit handler
$("form").submit(function(e) {
e.preventDefault();
var card = $(this).closest(".card");
var formData = $(this).serialize();
formData.append("formNumber",card.data("id"));
$.ajax({
type: 'POST',
url: AjaxUrl,
data: formData
})
.done(function(response) {
var messageAlert = response.type;
var messageText = response.message;
var alertBox = '<div class="alert ' + messageAlert + '"style="margin-top:10px;"><d style="font-size:12px; ">' + messageText + '</d></div>';
card.find(".PayBillResult").html(alertBox);
card.delay(3000).fadeOut(2000);
})
});
}); // End ready
So on .pay or .decline button click, the URL to use with the Ajax request is changed accordingly.
(I don't know the use of the third button)
Then the .closest() form submits. And from $(this), which is the <form>, you can find all the related elements you need.
Notice that the form number that is submitting is added to the formData.
You'll retreive it with $_POST['formNumber'].