jQuery function works intermittently - javascript

I'm pretty stuck here.
I'm using a live search lookup script (AJAX) to lookup customers in the database using a input field. Upon selection I click my chosen customer. Then the form I am filling out for the customer is filled with those details from the database. The problem is only some of the time once clicked the fields are populated with data. It is completely intermittent, if I repetitively click the same customer eventually they will populate, it appears as though it works in bursts and fails it appears as though there is no pattern.
Thanks for any help in advance :)
// ########## LIVE SEARCH FUNCTION ########## //
$(function(){
$(".search").keyup(function()
{
var searchid = $(this).val();
var dataString = 'search='+ searchid;
if(searchid!='')
{
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
cache: false,
success: function(html)
{
$("#result").html(html).show();
}
});
}return false;
});
jQuery(document).live("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search")){
jQuery("#result").fadeOut();
}
});
$('#searchid').click(function(){
jQuery("#result").fadeIn();
});
});
// ########## LIVE SEARCH FUNCTION ########## //
// ########## DATA POPULATE FUNCTION ########## // NOT WORKING ALL THE TIME
$( document ).ajaxComplete(function() {
jQuery("#result").live("click",function(e){
var $clicked = $(e.target);
$('#custid').val($clicked.find('.customerIdS').text());
$('#firstName').val($clicked.find('.firstNameS').text());
$('#lastName').val($clicked.find('.lastNameS').text());
$('#companyName').val($clicked.find('.companyNameS').text());
$('#streetAddressP').val($clicked.find('.streetAddressS').text());
$('#suburbP').val($clicked.find('.suburbS').text());
$('#stateP').val($clicked.find('.stateS').text());
$('#postcodeP').val($clicked.find('.postcodeS').text());
$('#phoneNumber').val($clicked.find('.phoneNumberS').text());
$('#emailAddress').val($clicked.find('.emailAddressS').text());
});
});
// ########## DATA POPULATE FUNCTION ########## // NOT WORKING ALL THE TIME
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<div class="content" style="float:right;">
<input id="searchid" class="search" type="text" placeholder="Search for customer using first name, last name or company name."></input>
<br></br>
<div id="result" style="display: none;">
<div class="show" align="left">
<div class="selection">
<span class="customerIdS">
3628
</span>
<span class="firstNameS">
David
</span>
<span class="lastNameS">
Dodrel
</span>
-
<span class="companyNameS"></span>
,
<span class="streetAddressS">
101 Woodward Place
</span>
,
<span class="suburbS">
Suburb
</span>
<span class="stateS">
State
</span>
<span class="postcodeS">
Postcode
</span>
<span class="phoneNumberS"></span>
<span class="emailAddressS"></span>
</div>
</div>
</div>
<div id="customerDetails" class="row">
<div class="col-sm-6">
<label for="firstName">First Name</label>
<input type="text" name="firstName" id="firstName">
<label for="lastName">Last Name</label>
<input type="text" name="lastName" id="lastName">
<label for="companyName">Company Name</label>
<input type="text" name="companyName" id="companyName">
</div>
<div class="col-sm-6">
<label for="phoneNumber">Phone Number</label>
<input type="text" name="phoneNumber" id="phoneNumber">
<label for="emailAddress">Email Address</label>
<input type="text" name="emailAddress" id="emailAddress">
</div>
</div>

Try using the code below, instead yours. Also, please, check the comments explaining what i think was wrong with your code.
jQuery(function(){
jQuery(".search").on("keyup", function() {
var searchId, dataString;
searchId = jQuery(this).val();
dataString = "search=" + searchId;
if (searchId) {
jQuery.ajax({
type: "POST",
url: "search.php",
data: dataString,
cache: false,
success: function(html) {
jQuery("#result").html(html).show();
}
});
}
});
jQuery(document).on("click", function(e){
//No need to use "live" here since this whole block of code will be executed once the DOM is ready
var $clicked = jQuery(e.target);
if (!$clicked.hasClass("search")) {
jQuery("#result").fadeOut();
}
});
jQuery("#searchid").on("click", function(){
jQuery("#result").fadeIn();
});
//This is only attached once since your "#results" div is there from the beginning and you only change its content, you don't remove and attach it again.
jQuery("#result").on("click", ".selection", function(e){
//You were getting jQuery(e.target) but i assume it wasn't what you wanted since you were getting the element that was clicked inside "#result" and not "#result" itself (that is where you find your content and then assign values based on it)
var $clicked = jQuery(this);
jQuery('#custid').val($clicked.find('.customerIdS').text().trim());
jQuery('#firstName').val($clicked.find('.firstNameS').text().trim());
jQuery('#lastName').val($clicked.find('.lastNameS').text().trim());
jQuery('#companyName').val($clicked.find('.companyNameS').text().trim());
jQuery('#streetAddressP').val($clicked.find('.streetAddressS').text().trim());
jQuery('#suburbP').val($clicked.find('.suburbS').text().trim());
jQuery('#stateP').val($clicked.find('.stateS').text().trim());
jQuery('#postcodeP').val($clicked.find('.postcodeS').text().trim());
jQuery('#phoneNumber').val($clicked.find('.phoneNumberS').text().trim());
jQuery('#emailAddress').val($clicked.find('.emailAddressS').text().trim());
});
});

Related

Javascript - After creating a div, Ajax is not working

I have a button for a form. When I click the button, the form is created. After being created, the form is not working with Ajax. My script codes are in here. My #testform is not wrong because it's working without creating form. Do you have any ideas?
function addDiv() {
var panel = document.querySelector(".add_new");
var div = document.createElement("div");
div.innerHTML = '<br> <form id="testform" method="POST"> <div class="row" style="padding-left:10rem;"> <div class="col-md-4"> <input type="text" class="form-control" value="" placeholder="Başlık" name="yeniBaslik" required></div> <div class="col-md-4"> <input type="text" placeholder="Açıklama" name="yeniAciklama" class="form-control" value="" name="" required> </div> <div class="col-md-2 text-left"> <button type="submit" class="btn btn-success btn-animated btn-wide addToDatabase">Add to the Database</button> </div> </row> </form> <br>';
panel.appendChild(div);
}
$("#testform").submit(function(e) {
e.preventDefault();
var formData = new FormData($("#testform").get(0));
$.ajax({
url: 'config.php',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function() {
setTimeout(
function() {
$(".addToDatabase").html("Successfully.");
}, 1000);
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="addDiv()"> Create a form </button>
<div class="add_new"></div>
Since second statement is executed before "div" is created, submit event is not being listened to on the new <form>
function addDiv() {
/*...*/
panel.appendChild(div);
$("#testform").submit(function(e) { /*...*/ });
}

HTML Form Submit does not reach my javascript

I am trying to reach my javascript code when I press the submit button within my form and it is not triggering my javascript code at all.
So I got this form within my Bootstrap Modal using the following code:
<form id="updateUserForm">
<div class="form-group">
<label for="firstName">First name:</label>
<input type="text" class="form-control" id="firstnameModalInput" />
</div>
<div class="form-group">
<label for="middleName">Middle name:</label>
<input type="text" class="form-control" id="middlenameModalInput" />
</div>
<div class="form-group">
<label for="lastName">Last name:</label>
<input type="text" class="form-control" id="lastnameModalInput" />
</div>
<div class="form-group">
<label for="mobileNumber">Mobile number:</label>
<input type="text" class="form-control" id="mobilenumberModalInput" />
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="text" class="form-control" id="emailModalInput" />
</div>
<div class="form-group">
<label for="Enabled">Enabled:</label>
<input type="checkbox" class="form-control" id="enabledModalInput" style="width:34px" />
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-default" data-dismiss="modal" id="submit" value="Apply" />
</div>
</form>
And the javascript code I have:
$('document').ready(function(){
$("#updateUserForm").submit(function (event) {
console.log("Method entered");
event.preventDefault();
var serialize = $("#updateUserForm").serialize();
$.ajax({
type: "POST",
data: serialize,
url: "/Dashboard/UpdateUser",
datatype: JSON,
succes: function (data) {
console.log("succes!");
console.log(data);
},
error: function (data) {
console.log("error");
console.log(data);
}
})
})
})
I have another function in that javascript that is used to populate the input fields and that works fine, so I guess the HTML can reach the javascript file. But it does not reach the javascript submit function (it doesn't do the console.log for example) . Does anyone have an idea what I am doing wrong?
EDIT:
I have been playing around a bit more, and it seems that I can acces the javascript method when I try to reach it from outside of the bootstrap modal, it goes wrong somewhere within the modal.
Use return false instead of prevent default end of the function and change the submit function with on function.
$('document').ready(function(){
$("#updateUserForm").on("submit", function () {
console.log("Method entered");
var serialize = $("#updateUserForm").serialize();
$.ajax({
type: "POST",
data: serialize,
url: "/Dashboard/UpdateUser",
datatype: JSON,
succes: function (data) {
console.log("succes!");
console.log(data);
},
error: function (data) {
console.log("error");
console.log(data);
}
})
return false;
})
})
try this
$("#updateUserForm").on('submit', function (e) {
e.preventDefault();
});
Can you please try below code. and please check post URL"/Dashboard/UpdateUser" is right?
$("#UpdateUserForm").submit(function (e)
{
var isValid = $("#UpdateUserForm").valid();
if (!isValid)
return;
//This is important as it prevents the form being submitted twice
e.preventDefault();
$.ajax({
type: "POST",
url: "/Dashboard/UpdateUser",
data: $("#UpdateUserForm").serialize(),
success: function (response)
{
var status = '';
status = response.Status;
console.log("succes!");
console.log(data);
}
})
.error(function () {
console.log("error");
console.log(data);
});
});
$("#updateUserForm").on('submit', function (e) {
e.preventDefault();
});
Or use action properties in form.

codeigniter : form validation jquery

i have a form name nama kategori and then when someone input the nama kategorithat already exist, i want the button become unclickable like when the button being clicked it's not gonna do anything, the problem is i manage to get the error message when input the existing nama kategori, but when i click the button it's still send the data and inputting the data, for more info look the images below
Success Display Error Message
Then i clicked button "Tambah"
it's still adding the data into the tables, i want to prevent that, i want when the button clicked it's not gonna do anything below are my code
JQUERY
$(document).ready(function(){
var check1=0;
$("#kategori").bind("keyup change", function(){
var nama = $(this).val();
$.ajax({
url:'cekData/kategori/nama_kategori/'+nama,
data:{send:true},
success:function(data){
if(data==1){
$("#report1").text("");
check1=1;
}else{
$("#report1").text("*choose another kategori");
check1=0;
}
}
});
});
});
VIEW
<div class="row">
<div class="col s12 m8 l6 offset-m2 offset-l3" align="center">
<form action="<?php echo site_url('kategori/insertKategori') ?>" method="post">
<div class="input-field">
<input id="kategori" name="kategori" type="text" maxlength="40" class="validate" required>
<label for="kategori">nama kategori</label> <span class="error" id="report1"></span>
</div>
<br/>
<button type="submit" class="waves-effect waves-light btn blue darken-1">Tambah</button>
</form>
<br/>
</div>
</div>
CONTROLLER
public function cekData($table, $field, $data){
$match = $this->MKategori->read($table, array($field=>$data), null, null);
if($match->num_rows() > 0){
$report = 2;
}else{
$report = 1;
}
echo $report;
}
You need to make following changes to your jquery code:
$(document).ready(function(){
var check1=0;
$("#kategori").bind("keyup change", function(){
var nama = $(this).val();
$.ajax({
url:'cekData/kategori/nama_kategori/'+nama,
data:{send:true},
success:function(data){
if(data==1){
$("#report1").text("");
check1=1;
$('button[type="submit"]').prop('disabled','');
}else{
$("#report1").text("*choose another kategori");
check1=0;
$('button[type="submit"]').prop('disabled',true);
}
}
});
});
});

Avoid Refreshing page submiting the form

Whenever using this form that I made (in Portuguese), refreshing removes all previously entered data from the page. Why does this happen, and how can I fix it? Thank you for your time.
<script type="text/javascript">
function submitForm(){
// Initiate Variables With Form Content
var nome = $("#nome").val();
var email = $("#email").val();
var telefone = $("#telefone").val();
var assunto = $("#assunto").val();
var mensagem = $("#mensagem").val();
$.ajax({
type: "POST",
url: "send-contact2.php",
data: "nome=" + nome + "&email=" + email + "&telefone=" + telefone + "&assunto=" + assunto + "&mensagem=" + mensagem,
cache:false,
success: function (data) {
alert(data);
}
});
}
</script>
<form id="myForm">
<div class="col col-md-6">
<input type="text" name="nome" id="nome" required value="" tabindex="1" placeholder="Nome">
<input type="text" name="email" id="email" required value="" tabindex="2" placeholder="E-mail">
<input type="text" name="telefone" id="telefone" required value="" tabindex="2" placeholder="Telefone">
<select id="assunto" name="assunto" required>
<option value="outros">Outros assuntos</option>
<option value="encomendas">Encomendas</option>
</select>
</div>
<div class="col col-md-6">
<textarea name="mensagem" id="mensagem" cols="29" rows="8" placeholder="Mensagem"></textarea>
</div>
<div class="col col-md-12 ">
<button name ="submit" type="submit" onclick="return submitForm();">Enviar</button>
</div>
</form>
Your function also needs to return false to stop the click event behaviour from submitting the form:
function submitForm(){
// your code...
return false;
}
Better still, hook to the submit event of the form directly and do away with the clunky onclick handlers, and use serialize() to gather the form data for you:
<button name="submit" type="submit">Enviar</button>
<script type="text/javascript">
$(function() {
$('#myForm').submit(function(e) {
e.preventDefault(); // stop form submission
$.ajax({
type: "POST",
url: "send-contact2.php",
data: $(this).serialize(),
cache: false,
success: function (data) {
alert(data);
}
});
}
});
</script>
Try to change onClick action to onSubmit and add return false after method. Like this:
<button name ="submit" type="submit" onsubmit="submitForm(); return false;">Enviar</button>
Good practice will be add method="POST" to your form attributes.

Form serialize issue

Here is my form's markup
<form name="contactForm" id="contactForm" role="form">
<div style="width: 190px">
<div class="form-group">
<input type="text" placeholder="fullname" name="fullname" id="formFullname" class="form-control">
</div>
<div class="form-group">
<input type="email" placeholder="email" name="email" id="fromEmail" class="form-control">
</div>
<div class="form-group">
<input type="text" placeholder="company" name="company" id="fromCompany" class="form-control">
</div>
</div>
<div class="clear"></div>
<div class="form-group">
<textarea placeholder="message" name="message" id="formMessage" rows="3" class="form-control"></textarea>
</div>
<button class="btn btn-success" type="submit" name="submit" id="formSubmit">send</button>
</form>
Using jquery 1.10.2
And here is JS
var form = $('#contactForm');
form.submit(function () {
console.log("form ", $(this).serialize());
$.ajax({
type: "POST",
url: url + "ajax/sendmail",
data: $(this).serialize(),
success: function (response) {
console.log(response);
}
});
return false;
});
I know that function fires, tested with alert. But console.log doesnt return anything, and during ajax call I don't see anything in POST (Watching with firebug's XHR).
BTW: role="form" is because i'm using Twitter Bootstrap framework
What am I doing wrong?
UPDATE
data: $(form).serialize() didn't help also
If you try this :
form.submit(function () {
console.log("form ", $(this).serialize());
return false;
});
it works just fine. So I think the problem
form.on('submit',function () {
event.preventDefault();
console.log("form ", $(this).serialize());
$.ajax({
type: "POST",
url: url + "ajax/sendmail",
data: $("form").serialize(),
success: function (response) {
console.log(response);
}
});
return false;
});
Because $(this) in your code doesn't refer to the form but instead refers to jQuery on which the ajax method is called
Try the following code, but first modify your form HTML so that is has an "action" attribute. The nice thing about this code is that it can be used on any form which has a submit button and an action attribute. (i.e. it is not coupled to any specific IDs)
$(function() {
$('input[type="submit"]').click(function(event) {
event.preventDefault();
var form = $(this).closest('form');
var url = form.attr('action');
var data = form.serialize();
$.post(url, data)
.done(function() {
alert('Yay! your form was submitted');
})
.fail(function() {
alert('Uh oh, something went wrong. Please try again');
});
});
Cheers.

Categories