jquery post undefined in firebug - javascript

On 2 of my elements in a form, I am receiving 'undefined' in firebug. I have tried to trace the error, but keep hitting a brick wall, hence the post. One of the areas with the error is in the divId block and the other is the #company in the form. I would be grateful if someone could check my code and point out my error. Thanks
// Function to add box
function addbox() {
$("#boxform").dialog({
autoOpen: false,
resizable: true,
modal: true,
title: 'Submit a box intake request',
width: 470,
beforeclose: function (event, ui) {
$("#addbox").html("");
$("#divId").html("");
}
});
$('#boxsubmit').click(function () {
var company = $('.company').val();
var box = $('.box').val();
var service = $('#service').val();
var authorised = $('.authorised').val();
var address = $('.address').val();
var data = 'company=' + company + '&box=' + box + '&authorised=' + authorised + '&service=' + service + '&address=' + address;
$.ajax({
type: "POST",
url: "boxesadd.php",
data: data,
success: function (data) {
$("#boxform").get(0).reset();
$('#addbox').html(data);
//$("#form").dialog('close');
$("#flex1").flexReload();
}
});
return false;
});
$("#boxform").dialog('open');
}
html
<script language="javascript" type="text/javascript">
$(function() {
$("#company").live('change', function() { if ($(this).val()!="")
$.get("../../getOptions.php?customer=" + $(this).val(), function(data) {
$("#divId").html(data); }); });
});
</script
<form id="boxform" method="post" class="webform" name="boxform" />
<label for="company">Select a Company:</label>
<select name="company" id="company" />
<option SELECTED VALUE="">Select a Company</option>
<?php
do {
?>
<option value="<?php echo $row_Recordsetcust['customer']?>"><?php echo $row_Recordsetcust['customer']?></option>
<?php
}
while ($row_Recordsetcust = mysql_fetch_assoc($Recordsetcust));
$rows = mysql_num_rows($Recordsetcust);
if($rows > 0)
{
mysql_data_seek($Recordsetcust, 0);
$row_Recordsetcust = mysql_fetch_assoc($Recordsetcust);
}
?>
</select>
<!--- displays the address from the change function -->
<div id="divId"></div>

Try changing
<form id="boxform" method="post" class="webform" name="boxform" />
to
<form id="boxform" method="post" class="webform" name="boxform">
and
<select name="company" id="company" />
to
<select name="company" id="company">
and
var company = $('.company').val();
to
var company = $('#company').val();

<select name="company" id="company" /> should be <select name="company" id="company">
Then form tag is also not closed correctly.

In your #boxsubmit click handler, you use dot instead of hash for #company.
Change
var company = $('.company').val();
to
var company = $('#company').val();
and remove the self close / on non-empty elements.

Related

textarea not send form do not send form the first click to send. The at 2 click yes

In a Tinymce textarea, it forces me to double click submit form. In the first send "var a" is empty, in the second click if you have the data and it is sent correctly. How can it be solved?
<script src="https://cdn.tiny.cloud/1/zgxpx6ymtwpuc7yy5x3wuic7eu7ughi6w7q98msfnxmbcpjp/tinymce/5/tinymce.min.js" referrerpolicy="origin"></script>
<script>
tinymce.init({
selector: '#comment',
});
</script>
<script type="text/javascript">
function FQB() {
var a = document.forms["Formularioqr"]["comment"].value;
if (a == null || a == "") {
alert(a);
return false;
}else{
a = a.replace(/\r?\n/g, '<br />');
$.ajax({
type: "POST",
url: "send-email-manual-envio.php?mesaje=" + a + "&correo=<?php echo $correo;?>" ,
dataType: "json",
success: function() {
document.getElementById("Formularioqr").reset();
document.getElementById("showtextqr1").innerHTML =" Enviado Con exito ";
},
error: function() {
document.getElementById("Formularioqr").reset();
document.getElementById("showtextqr1").innerHTML = " ERROR!!";
}
});
}
}
</script>
<form method="POST" autocomplete="off" id="Formularioqr" name="Formularioqr" onsubmit="return FQB()">
<div class="form-group">
<label for="comment">Mesaje:</label>
<textarea class="form-control" rows="12" id="comment" name="comment"></textarea>
</div>
<p id="showtextqr1"></p>
<input type="submit" value="Enviar">
</form>
I haven't tried it, but i would guess, that '.value' isn't working properly for tinymce textareas.. the tinymce has an dedicated function to get the content. See https://www.tiny.cloud/blog/how-to-get-content-and-set-content-in-tinymce/
I would suggest, trying this way instead this var a = document.forms["Formularioqr"]["comment"].value;

How to submit the dynamical input field into the database?

I am displaying the input field dynamically which is working for me.
The issue is,
I have to submit the form. I have tried some code as below but it's not working.
I am using Codeigniter.
Controler code
public function register(){
$save = array(
'pp_fileStatus' => $this->input->post('pp_fileStatus');
'reasonDate' => $this->input->post('reasonDate');
'reasonAmt' => $this->input->post('reasonAmt');
);
$afterxss=$this->security->xss_clean($save);
if ($afterxss)
{
$this->db->insert('tbl_register',$afterxss);
$response['error'] = "true";
$response['msg'] = "Successfully";
}else{
$response['error'] = "false";
$response['msg'] = "Sometning wrong! please check the internet connection and try again";
}
echo json_encode($response);
}
I am adding the field dynamically and incrementing the name. Please let me know what name I have to use here
$save = array(
'pp_fileStatus' => $this->input->post('pp_fileStatus');
'reasonDate' => $this->input->post('reasonDate');
'reasonAmt' => $this->input->post('reasonAmt');
);
Below is the code for adding the input field dynamically.
$(document).ready(function() {
var maxField = 10; //Input fields increment limitation
var x = 1; //Initial field counter is 1
var count = 2;
var numberIncr = 1; // used to increment the name for the inputs
var addrm = '';
//Once add button is clicked
$(document).on('click', '#clicktoadd', function() {
//Check maximum number of input fields
if (x < maxField) {
x++; //Increment field counter
numberIncr++;
$(".medication_info").append('<select name="pp_fileStatus' + numberIncr + '" class="form-control multipleselect pp_fileStatus dynamicVal"><option value="" disabled selected>Status</option><option value="1">Open</option><option value="2">Close</option><option value="3">Pending</option></select>');
}
count++;
});
$(document).on('change', '.pp_fileStatus', function(event) {
if (($(this).val() == '1') || ($(this).val() == '3')) {
$(".medication_info").append('<div class="addbankField input-wrapper padding0"><div class="form-group"> <input type="text" name="reasonDate' + numberIncr + '" class="form-control datetimepicker dynamicVal" placeholder="Date"></div></div><div class="addbankField input-wrapper"><div class="form-group"> <input type="text" name="reasonAmt' + numberIncr + '" class="form-control commnumber dynamicVal" placeholder="amt"></div></div><input type="hidden" name="remark' + numberIncr + '" class="form-control" placeholder="Remark">');
} else {
$(".medication_info").append('<div class="addbankField input-wrapper lbpflex padding0"><div class="form-group"> <input type="text" name="reasonDate' + numberIncr + '" class="form-control datetimepicker dynamicVal" placeholder="Date"></div></div><div class="addbankField input-wrapper"><div class="form-group"> <input type="text" name="remark' + numberIncr + '" class="form-control dynamicVal" placeholder="Remark"></div></div><input type="hidden" name="reasonAmt' + numberIncr + '" class="form-control" placeholder="amt">');
}
});
});
$('#register').on('submit', function(event) {
event.preventDefault();
// adding rules for inputs with class 'comment'
$('.dynamicVal').each(function() {
$(this).rules("add", {
required: true
})
});
// test if form is valid
if ($('#register').validate().form()) {
$.ajax({
//url:"process.php",
url: baseUrl + "/Customer_control/register",
type: "POST",
dataType: "json",
data: $('#register').serialize(),
success: function(data) {
alert("success");
},
}); // AJAX Get Jquery statment
}
//alert('hellow');
});
$('#register').validate({
errorPlacement: function(error, element) {
if (element.is("select")) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
<div id="clicktoadd">Add More</div>
<form action="#" method="post" id="register" name="register">
<div class="row">
<div class="medication_info">
</div>
</div>
<input type="submit" name="send" value="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/additional-methods.min.js"></script>
Can anyone here to help me out with this issue?
You can use arrays for multiple names in HTML form and then get the values using Foreach Loop in PHP (CodeIgniter).
Here is how you should change your code: Change your this line:
$(".medication_info").append('<select name="pp_fileStatus' + numberIncr + '" class="form-control multipleselect pp_fileStatus dynamicVal"><option value="" disabled selected>Status</option><option value="1">Open</option><option value="2">Close</option><option value="3">Pending</option></select>')
To:
$(".medication_info").append('<select name="pp_fileStatus[]" class="form-control multipleselect pp_fileStatus dynamicVal"><option value="" disabled selected>Status</option><option value="1">Open</option><option value="2">Close</option><option value="3">Pending</option></select>')
Note: I just changed select field name to "pp_fileStatus[]" and remove numberIncr variable
Now you can access this field name values in your controller like this.
$pp_fileStatus = $this->input->post('pp_fileStatus');
Here $pp_fileStatus is an array and contains all the values of pp_fileStatus.
You can do same for your other form fields too.
So you get rid of giving names to fields by incrementing one to a variable.
Hope this solves your problem.
You can update your register function like this:
public function register(){
$insert_array = [];
$pp_fileStatus = $this->input->post('pp_fileStatus');
$reasonDate = $this->input->post('reasonDate');
$reasonAmt = $this->input->post('reasonAmt');
$remark = $this->input->post('remark');
foreach ($pp_fileStatus as $key => $value) {
$insert_array[] = array(
'pp_fileStatus' => $value,
'reasonDate' => $reasonDate[$key],
'reasonAmt' => $reasonAmt[$key],
'remark' => $remark[$key]
);
}
$this->db->insert_batch('tbl_register',$insert_array);
}
Update this function according to your needs
you need to create a function for your submit actions, which you call (make available) on document load and also with your change event, after having appended the DOM.
simplified example:
$(document).ready(function() {
my_submit(); // enables your submit calls
$(document).on('change', '.pp_fileStatus', function(event) {
// your append code
my_submit(); // again, enables your submit calls
})
}
function my_submit(){
$('#register').on('submit', function(event) {
// your code
})
$('#register').validate({
// your code
})
}

Delete required on input before submitted in ajax

I tried to validate by submitting a form by using ajax on codeigniter, when I want to insert data but only a few input fields only and input field that I do not use I try to hide, but attr required still running on the input field that I have hidden, how to solve this. so delete the required input field when hidden.
Views
<form id="fr" method="post" class="form-horizontal form-label-left">
<div class="form-group">
<label for="fullname">Section * :</label>
<select name="section" class="form-control" required="required">
<option value="">Select section</option>
<option value="manager">Manager</option>
<option value="head manager">Head Manager</option>
</select>
<span class="help-block"></span>
</div>
<div class="form-group">
<label for="nama">Kitchen * :</label>
<input type="text" name="name_kitchen" class="form-control" required="required" />
<span class="help-block"></span>
</div>
<div class="form-group">
<label for="nama">Resto * :</label>
<input type="text" name="name_resto" class="form-control" required="required" />
<span class="help-block"></span>
</div>
<div class="form-group">
<label for="fullname"> </label><br>
<button type="button" id="submit" class="btn btn-primary"><i class="fa fa-save"></i> Simpan</button>
</div>
</form>
<script>
$("[name='section']").change(function(){
var value=$(this).val();
if(value == "manager"){
$("[name='name_kitchen']").hide();
$("[name='name_resto']").show();
}else{
$("[name='name_kitchen']").show();
$("[name='name_resto']").hide();
}
});
$("#submit").click(function() {
$.ajax({
type: "POST",
url: base_url+"add",
dataType: 'json',
data: $('#fr').serialize(),
success: function(data) {
if(data.status) {
$(".add-from-staff").toggle("slow");
$("#fr").load(location.href + " #fr");
$('form#fr input[type="text"],texatrea, select').val('');
}else {
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error');
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]);
}
}
},
error: function (request, jqXHR, textStatus, errorThrown) {
alert('Error');
console.log(request.responseText);
}
});
});
</script>
Controllers
public function add() {
$this->_validate();
$insert = $this->My_models->_add();
echo json_encode(array("status" => TRUE));
}
function _validate() {
$data = array();
$data['error_string'] = array();
$data['inputerror'] = array();
$data['status'] = TRUE;
if($this->input->post('name_kitchen') == '')
{
$data['inputerror'][] = 'name_kitchen';
$data['error_string'][] = 'Kitchen is required';
$data['status'] = FALSE;
}
if($this->input->post('name_resto') == '')
{
$data['inputerror'][] = 'name_resto';
$data['error_string'][] = 'Resto is required';
$data['status'] = FALSE;
}
if($data['status'] === FALSE)
{
echo json_encode($data);
exit();
}
}
so how when I choose one of the select options that hide disabled required?
when u are hiding any div u can get the element and remove its required attribute using jquery
$("[name='name_kitchen']").removeAttr('required');
e.g:
$("#elementID").removeAttr('required');
In this example I would not use the required attribute. It is causing more headaches than it is worth. Instead, rely on the server-side validation.
To determine which "section" is in use it seems to me that passing another piece of info to the controller would be the easiest way to solve the problem. This could be done many different ways. Adding another hidden field is one option.
Somewhere inside the <form> add
<input type="hidden" id="use-section" name="use_section" value="">
It is not clear that you have a "default" section shown when you first show the page. If there is one then use that for the "value" in the above field.
During the handler
$("[name='section']").change(function(){ ...
set the value of the "use_section" field.
var value=$(this).val();
$("#use-section").val(value);
You can evaluate the "use_section" in your controller, or in your case, in the model which is where I assume you are capturing the data posted.
if($this->input->post('use_section') === "manager")
{
//get the fields you want
}
else
{
//get the other fields
}
I have a suggestion regarding _validate(). Instead of calling exit() to short-circuit add() return a value - TRUE if it works, or $data if it doesn't. The last few lines of _validate() become
if($data['status'] === FALSE)
{
return $data;
}
return TRUE;
Then use this add() method
public function add()
{
if(TRUE === ($status = $this->_validate()))
{
$insert = $this->My_models->_add();
$status = array("status" => TRUE);
}
echo json_encode($status);
}
Use of exit or die in CodeIgniter is, IMO, not appropriate because it short-circuits the framework's designed execution flow.

AJAX jquery not responding and showing divs

I have code a simple form in which I retrieve data dynamically and then sending it to another page. Using that data i want some divs to be displayed on my page. It is returning divs when I check it simply without using AJAX. But now I have applied some AJAX and it is not working. Any suggestions please.
AJAX
$("document").ready(function() {
$("#search_keyword").on("submit", function (e) {
e.preventDefault();
$.post("keyword_search.php?query="+encodeURIComponent($("#keyword").val())+"category="+encodeURIComponent($("#category").val())+"store="+encodeURIComponent($("#store").val()), function (data) {
var res = JSON.parse(data);
if (res.divs) {
$('#search_result').html("");
for (var i = 0; i < res.divs.length; i++) {
$('#search_result').append(res.divs[i]);
}
} else {
$('#search_result').html("No matched coupons found !");
}
});
});
});
form
<form class="form-horizontal select-search" id="search_keyword" method="post">
<label class="control-label ">Keyword</label>
<input class="form-control" id="keyword" name="keyword" type="text">
<!-- Select Category -->
<label class="control-label " for="category">Select category</label>
<select class="category" id="category" name="category">
<?php
$sm=mysqli_query($con,"select * from categories ");
while ($row1 = mysqli_fetch_array($sm,MYSQLI_ASSOC)){
$cat_id = $row1['cat_id'];
$name = $row1['cat_name'];
echo '<option value="' . $cat_id . '">' . $name . '</option>';
}
?>
</select>
<label class="control-label " for="store">Select a store</label>
<select class="storesname" id="store" name="store">
<option selected="selected">Select Stores</option>
</select>
<button id="search_btn" name="search_btn" class="btn btn-danger">Search coupons</button>
</form>
<div id="search_result"> </div>
You need to change from button to submit type so that it can actually submit.
So change:-
<button id="search_btn" name="search_btn" class="btn btn-danger">Search coupons</button>
To:-
<input type="submit" id="search_btn" name="search_btn" class="btn btn-danger" value="Search coupons"/>
Note:- Make sure that jQuery library added before your script code so that it will work.
Change your code like below:-
$("document").ready(function() {
$("#search_keyword").on("submit", function (e) {
e.preventDefault();
var data = {'query':encodeURIComponent($("#keyword").val()),'category':encodeURIComponent($("#category").val()),'store':encodeURIComponent($("#store").val())};
$.post("keyword_search.php",data, function (data) {
var res = JSON.parse(data);
if (res.divs) {
$('#search_result').html("");
for (var i = 0; i < res.divs.length; i++) {
$('#search_result').append(res.divs[i]);
}
} else {
$('#search_result').html("No matched coupons found !");
}
});
});
});
And in your keyword_search.php check like this:-
<?php
echo "<pre/>";print_r($_POST); //check that how post data are coming
// rest do code accordingly
?>
Also remove method="post" from your current <form>
You just to change some thing in jQuery.
I have just changed "submit" to "click" and "#search_keyword" to "#search_btn"
$("document").ready(function() {
$("#search_btn").on("click", function (e) {
e.preventDefault();
$.post("keyword_search.php?query=" + encodeURIComponent($("#keyword").val())+encodeURIComponent($("#category").val())+encodeURIComponent($("#store").val()), function (data) {
var res = JSON.parse(data);
if (res.divs) {
$('#search_result').html("");
for (var i = 0; i < res.divs.length; i++) {
$('#search_result').append(res.divs[i]);
}
} else {
$('#search_result').html("No matched coupons found !");
}
});
});
});
It might help you

Debugging failing jQuery validate addMethod

I have a page where almost every click is handled by delegate().
http://itsneworleans.com/shows/midnight-menu-plus-1/blogs/after-midnight?preview=1
I set up jQuery validate like so
$(document).ready(function(){
$(".commentform form").validate({
rules: {
antispam: { equalToParam: "INO" }
}
});
jQuery.validator.addMethod("equalToParam", function(value, element, param) {
return value == param;
},
"Anti-spam field does not match requested value.");
});
if I check in console with
$.validator.methods['equalToParam']
I get back
function (value, element, param) { return value == param; }
so that looks good.
The validation works on the form submission BUT the equalToParam method has no effect. Only the "required" events occur for it.
The field HTML is
<input name="antispam" type="text" class="required" id="antispam" size="5" />
Where am I going wrong?
EDIT Here is whole form code (generated from PHP script and added to page via AJAX):
<? if ($post = (int) $_POST['pID']) { ?>
<div class="commentform">
<form>
<div class="commenttext">Comment:<br>
<textarea name="comment" class="required"></textarea>
</div>
<div class="commenttext">Your name:<br>
<input type="text" name="name" class="required">
</div>
<div class="commenttext">Your email (will not be publically visible):<br>
<input type="text" name="email" class="required email">
</div>
<div class="commenttext">Type the letters INO here to help us beat spam!<br>
<input name="antispam" type="text" class="required" id="antispam" size="5" />
</div>
<div class="commenttext">
<input type="button" name="submitcomment" class="submitcomment" value="Submit Comment">
<input type="hidden" name="post" value="<?=$post?>">
<? if ($parentComment = (int) $_POST['cID']) { ?>
<input type="hidden" name="parent" value="<?=$parentComment?>">
<? } ?>
</div>
</form>
</div>
<? } ?>
EDIT AGAIN And here's the click delegation code...
$("body").delegate(".submitcomment", "click", function(e) {
e.preventDefault();
var theform = $(this).closest("form");
console.log('Posting comment');
if ($(".commentform form").valid()) {
$.ajax({
type: "POST",
url: "/addComment.php",
data: theform.serialize()
}).done(function(html) {
if (html == 'OK') {
$(theform).html("<div class='commentposted'>Your comment has been received. Thank you. A moderator will review it for public viewing.</div>");
} else {
alert(html);
}
});
}
});
EDIT Here is the code which populates the form into the space where the Reply to Post link was:
$("body").delegate(".getcommentform", "click", function(e) {
e.preventDefault();
var pIDval = $(this).attr("data-pid");
var cIDval = $(this).attr("data-cid");
var thebox = $(this).closest("div.commentformcontainer");
console.log('Getting comment form');
$.ajax({
type: "POST",
url: "/commentForm.php",
data: { pID : pIDval, cID : cIDval }
}).done(function(html) {
thebox.html(html);
});
});
When you need to apply the .validate() method to more than one form, you must wrap it within a jQuery .each().
$(".commentform form").each(function() {
$(this).validate({
rules: {
antispam: {
equalToParam: "INO"
}
}
});
});
EDIT:
You need to initialize the plugin AFTER the form is inserted into the page. Assuming this code properly inserts the form... put your .validate() call as the last item inside...
$("body").delegate(".getcommentform", "click", function(e) {
e.preventDefault();
var pIDval = $(this).attr("data-pid");
var cIDval = $(this).attr("data-cid");
var thebox = $(this).closest("div.commentformcontainer");
console.log('Getting comment form');
$.ajax({
type: "POST",
url: "/commentForm.php",
data: { pID : pIDval, cID : cIDval }
}).done(function(html) {
thebox.html(html);
});
$(".commentform form").validate({ // <- initialize plugin AFTER form is inserted
// your rules & options
});
});
EDIT 2:
Include the equalToParam function someplace on your page within a DOM ready event handler.

Categories

Resources