AJAX jquery not responding and showing divs - javascript

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

Related

checking object for blank values and show errors

I am trying to figure out how I can check if any values in the object are blank, and then show the corresponding error.
The form inputs look like this:
<form role="form" action="home.php" class="addLaneForm" id="addLaneForm" name="addLaneForm">
<label for="addlanepartnercode">Partner Code</label><span id="addlanepartnercodeError" class="text-danger laneError" style="display:none;"> * </span>
<input type="text" class="form-control validation" id="addlanepartnercode" placeholder="Enter Partner Code" />
<label for="addlanepartnername">Partner Name</label><span id="addlanepartnernameError" class="text-danger laneError" style="display:none;"> * </span>
<input type="text" class="form-control validation" id="addlanepartnername" placeholder="Enter Partner Name" />
<label for="addlaneipicy">IPI/CY</label><span id="addlaneipicyError" class="text-danger laneError" style="display:none;"> * </span>
<select class="form-control validation" id="addlaneipicy">
<option></option>
<option value="YES">YES</option>
<option value="NO">NO</option>
</select>
// few more inputs and selects
<button type="button" class="btn btn-default btn-flat addLaneSubmit" id="addLaneSubmit" name="addLaneSubmit">Add</button>
</form>
Here is the onClick event:
$('#addLaneSubmit').on('click', function(e){
e.preventDefault();
let partnerCode = $('#addlanepartnercode').val();
let partnerName = $('#addlanepartnername').val();
let ipiCy = $('#addlaneipicy').val();
let addlane = new ProcessLane();
let addlanecriteria = {
partnerCode: partnerCode,
partnerName: partnerName,
ipiCy: ipiCy
}
// how I typically would check the values below:
if(addlanecriteria.partnerCode == ""){
$('#addlanepartnercodeError').show();
return false;
}
if(addlanecriteria.partnerName == ""){
$('#addlanepartnernameError').show();
return false;
}
else{
addlane.addLaneProcessing(addlanecriteria);
}
});
The way I typically check the values is redundant and time consuming.
I did add a class to the inputs called 'laneError'. I was trying to use that to display the errors by calling a function, as follows:
function showAllErrors(){
if($(".addLaneForm .validation") == ""){
$('.laneError').show();
}
}
For one, I wasn't sure where I could put the function call.
But when I was able to call the function, I can only get the first error to show, which is "addlanepartnercodeError".
There has to be a simpler way to check the values in the object.
You can just have a reusable function like below:
showErrorMsg(elemId) {
if($.trim($('#' + elemid).val()) === '') {
$('#' + elemId + 'Error').show()
return true;
}
return false;
}
So your code would just be:-
$('#addLaneSubmit').on('click', function(e){
e.preventDefault();
let Error = false,
addlane = new ProcessLane();
$('form')
.find("input[id^='add']")
.each((i , e){
if(!Error) {
Error = showErrorMsg($(e).attr('id'))
}
})
if(!Error) {
// Your form has no errors , do your thing here
addlane.addLaneProcessing(addlanecriteria);
}
});

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.

Display value of javascript variable in div

Good day all,
I have the following html code
<form method="post" action="blog_comment_post.php" id="post_blog_comment">
<input type="hidden" value="<?php echo $postid; ?>" name="blogid" id="blogid"/>
<textarea name="blog_comment" class="blog_comment_form" id="blog_comment" placeholder="Join the discussion"></textarea>
</form>
and, I have the following javascript code
<script type="text/javascript">
$(document).ready(function() {
$("#post_blog_comment").keypress(function(evt) {
if(evt.which == 13) {
var commentform = $("#post_blog_comment");
var blogid = $("#blogid").val();
var comment = $("#blog_comment").val();
$.post("blog_comment_post.php", { blogid: blogid, comment: comment},
function(data) {
var newmedia =
'<div class="blog_comm_hold"> \
<div class="user_comment_photo1"></div> \
<div class="blog_comment_"> \
<div class="blog_com_text">\
comment\
</div>\
</div>\
<br>\
</div>';
commentform.after(newmedia);
$('#post_blog_comment')[0].reset();
});
}
});
});
</script>
What I am trying to do is have the value that I typed into the textarea field of the form be displayed after the form when the user hits the enter key. The div classes load well but I don't know how to go about getting the actual value from the var variable be displayed too.
The var comment variable as can be seen above is not displaying its value. The variable is found under the blog_com_text div in the above script.
I want that when the user hits the enter key, that the value of the above comment variable is loaded inside of the respective div based on the above code. The div classes load well with no issue but how to have the value of the variable be loaded too.
Thanks much.
Here you go with the solution https://jsfiddle.net/xabt3vgt/
$(document).ready(function() {
$("#post_blog_comment").keypress(function(evt) {
if(evt.which == 13) {
var commentform = $("#post_blog_comment");
var blogid = $("#blogid").val();
var comment = $("#blog_comment").val();
//$.post("blog_comment_post.php", { blogid: blogid, comment: comment},
// function(data) {
var newmedia =`<div class="blog_comm_hold">
<div class="user_comment_photo1"></div>
<div class="blog_comment_">
<div class="blog_com_text">
${comment}
</div>
</div>
<br>
</div>`;
commentform.after(newmedia);
$('#post_blog_comment')[0].reset();
//});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="blog_comment_post.php" id="post_blog_comment">
<input type="hidden" value="<?php echo $postid; ?>" name="blogid" id="blogid"/>
<textarea name="blog_comment" class="blog_comment_form" id="blog_comment" placeholder="Join the discussion"></textarea>
</form>
You just need to uncomment you php ajax call.
Use back tick ` (left to 1) in the keyboard and if you want to add any variable then use ${variable_name} in between the back tick.
Try this
<script type="text/javascript">
$(document).ready(function() {
$("#post_blog_comment").keypress(function(evt) {
if(evt.which == 13) {
var commentform = $("#post_blog_comment");
var blogid = $("#blogid").val();
var comment = $("#blog_comment").val();
$.post("blog_comment_post.php", { blogid: blogid, comment: comment},
function(data) {
var newmedia = $('<div class="blog_comm_hold"><div class="user_comment_photo1" /><div class="blog_com_text" /><br></div>');
newmedia.find('.blog_com_text').html(comment));
commentform.after(newmedia);
$('#post_blog_comment')[0].reset();
});
}
});
});
You can test with this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="post_blog_comment"></div>
<textarea id="blog_comment"></textarea>
<input type="button" value="Go" id="postcomment" />
<script type="text/javascript">
$('#postcomment').click(function() {
showcomment();
});
function showcomment() {
var comment = $("#blog_comment").val();
var newmedia = $('<div class="blog_comm_hold"><div class="user_comment_photo1" /><div class="blog_com_text" /><br></div>');
newmedia.find('.blog_com_text').html(comment);
$('#post_blog_comment').after(newmedia);
$("#blog_comment").val('');
}
</script>

jquery post undefined in firebug

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.

Categories

Resources