codeigniter : form validation jquery - javascript

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);
}
}
});
});
});

Related

php not inserting data into table

I have a HTML form
<div class="contact-form col-md-6 " >
<form id="contact-form" method="post" action="" role="form">
<div class="form-group">
<input type="text" placeholder="Your Name" class="form-control" name="name" id="name" required>
</div>
<div class="form-group">
<input type="email" placeholder="Your Email" class="form-control" name="email" id="email" required>
</div>
<div class="form-group">
<input type="text" placeholder="Your Phone Number" class="form-control" name="phone" id="phone" required>
</div>
<div class="response_msg"></div>
<div id="mail-success" class="success">
Thank you. You are registerd. :)
</div>
<div id="mail-fail" class="error">
Sorry, don't know what happened. Try later :(
</div>
<div id="cf-submit">
<input type="submit" id="contact-submit" class="btn btn-transparent" value="Register" name="submit">
</div>
</form>
</div>
I need to submit form on same page and show message on successfully submission. I am using JS for this
<script>
$(document).ready(function(){
$("#contact-form").on("submit",function(e){
e.preventDefault();
if($("#contact-form [name='name']").val() === '')
{
$("#contact-form [name='name']").css("border","1px solid red");
}
else if ($("#contact-form [name='email']").val() === '')
{
$("#contact-form [name='email']").css("border","1px solid red");
}
else if ($("#contact-form [name='phone']").val() === '')
{
$("#contact-form [name='phone']").css("border","1px solid red");
}
else
{
$("#loading-img").css("display","block");
var sendData = $( this ).serialize();
$.ajax({
type: "POST",
url: "js/ajaxsubmit.php",
data: sendData,
success: function(data){
$("#loading-img").css("display","none");
$(".response_msg").text(data);
$(".response_msg").slideDown().fadeOut(3000);
$("#contact-form").find("input[type=text], input[type=email], textarea").val("");
}
});
}
});
$("#contact-form input").blur(function(){
var checkValue = $(this).val();
if(checkValue != '')
{
$(this).css("border","1px solid #eeeeee");
}
});
});
</script>
As soon i clicked on submit button page refresh but my i don't see my pho code inserting data in database.
<?php
require_once("conn.php");
if((isset($_POST['name'])&& $_POST['name'] !='') && (isset($_POST['email'])&& $_POST['email'] !='') && (isset($_POST['phone'])&& $_POST['phone'] !=''))
{
// require_once("contact_mail.php");
$yourName = $conn->real_escape_string($_POST['name']);
$yourEmail = $conn->real_escape_string($_POST['email']);
$yourPhone = $conn->real_escape_string($_POST['phone']);
$sql="INSERT INTO Beta_Registration (name, email, phone) VALUES ('".$yourName."','".$yourEmail."', '".$yourPhone."')";
if(!$result = $conn->query($sql)){
die('There was an error running the query [' . $conn->error . ']');
}
else
{
echo "Thank you! We will contact you soon";
}
}
else
{
echo "Please fill Name and Email";
}
?>
I want my form to submit on same page also stays on same block and shows the messages in div inside form when data entered successfully or failed into database.
The issues i am facing whenever i press submit button it refreshed the page and form data doesn't executed into database. It might be php or JS i am using. Please help me in this.
1- You need to add "return false" in your on submit function to prevent browser to submit the form
$(document).ready(function () {
$("#contact-form").on("submit", function (e) {
...
return false;
});
...
});
2- You need to match you database table name, and their columns name which you have used in your MySQL query.

Laravel multiple checkboxes to insert into database using ajax

I need someone to help me please to insert multiple products to cart, adding single one is working fine but I have one product which inserting with no issue and related products which have checkboxes where I need to add it but dont know how
enter image description here
ajax for adding product:
<script>
$(function(){
$('.add_to_cart').on("click", function () {
var id = ($("#item_id").val());
$.ajax({
url: 'cart/' + id+'/edit',
type: "get",
success: function (data) {
$('#myModal').modal('hide');
$('#cart_product').html(data);
}
});
});
});
</script>
add in controller
public function edit(Request $request,$id)
{
$quantity=$request->quantity;
$product=Product::find($id);
Cart::add($id,$product->product_title,$quantity,$product->product_price);
$products = Cart::content();
foreach($products as $Product){
echo '<div class="OrderItem_root styles_base styles_spacing-base">
<div class="OrderItem_quantity styles_just-right styles_base styles_spacing-base">'.$Product->qty.'</div>
<div class="OrderItem_container">
<div class="OrderItem_category"></div>
<div class="OrderItem_itemHeader">
<div id="cartprice" class="OrderItem_total">$'.$Product->price*$Product->qty.'</div>
<input id="mycartprice" type="text" name="mycartprice" value="'.$Product->price.'" hidden="">
</div>
<div>
</div>
<div>
<button class="remove_item OrderItem_action Button_root" data-id="'.$Product->rowId.'" data-price="'.$Product->price*$Product->qty.'" data-qty="'.$Product->qty.'" type="submit">Remove</button>
</div>
</div>
</div>';
}
}
related items
foreach($products as $Product){
echo '<div class="SuggestedItem_container">
<label>
<input id="ppleadd" type="checkbox" onchange = "AutoCalculateMandateOnChange(this)">
<span id="related_item" class="SuggestedItem_name">'.$ProductDetails->product_title.'</span><span class="SuggestedItem_price styles_small styles_base styles_spacing-base">+$'.$ProductDetails->product_price.'</span></div></div>
</div>
</label>';
}
to solve this issue use this
<input id="ppleadd" type="checkbox" class="get_value" data-id="'.$ProductDetails->product_id.'" >
$(document).ready(function(){
$('.testbtn').on("click", function (){
var insert=[];
$('.get_value').each(function(){
if($(this).is(":checked"))
{
insert.push($(this).attr('data-id'));
}
});
insert=insert.toString();
$.ajax({
url:"add-to-cart",
method:"get",
data:{insert:insert},
success:function(data){
} }); }); });

How to execute an action when textbox's content has changed?

I have two actions like:
Function getNews: to get list news.
Function searchNews: to get list news base on a keyword.
I create a form to submit that:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<form id="getNew" action="<?php echo admin_url('Xpathnews/searchKeyword') ?>" method="post">
<div class="col-md-12 col-sm-12 col-xs-12">
<h4><b>Select your news</b></h4>
<select id="selectcate" name="selectcate" class="field-custom">
<option value="http://theverge.com">The Verge</option>
<option value="http://neowin.net">Neowin</option>
</select>
</div>
<div class="col-md-12 col-sm-12 col-xs-12">
<h4><b>Keyword:</b></h4>
<input name="search_keyword" id="search_keyword" autocomplete="off" placeholder="Enter your keyword..." />
</div>
<div class="col-md-12 col-sm-12 col-xs-12">
<input name="xpath_title" id="xpath_title" type="hidden" />
</div>
<br>
<div class="col-md-12 col-sm-12 col-xs-12 text-center">
<input name="get_news" type="submit" id="get_news" value="Get News"/>
</div>
</form>
Or fiddle link: https://jsfiddle.net/f7zy0694/2/
I want when the user types any text in textbox search_keyword. Will execute action searchNews.
Usually, the user only clicks button Get News default execute action getNews.
I tried a solution in my controller/action:
public function getNews(){
$xpath_title = $this->input->post('xpath_title');
}
public function searchNews() {
$keyword = $this->input->post('search_keyword');
if(empty($keyword)) {
$this->getNews();
} else {
// execute my code at here
}
}
... is check if $keyword don't have value it will execute function $this->getNews but problem is:
I have some <input> hidden, seem the call to function getNews it not working.
I also tried with seft:redirect("/getNews").
Thanks.
In that you can use Jquery ajax with keyUp or keyDown like:
$(document).ready(function(){
$('#searchbox_id').keyUp(function(){
// get the user entered string
var searchTxt = $(this).val();
$.ajax({
url: 'process_file.php',
type: 'get',
data: {
searchTxt :searchTxt
},
success: function(response){
// do your stuff here
}
});
});
});

How to get value from multiple input with codeigniter [duplicate]

This question already has answers here:
Getting data from post array in CodeIgniter
(5 answers)
Closed 6 years ago.
I have a problem to send multiple data to controller.
$target is result from post('warna'). How do I get all data?
<form action="http://localhost/starsc/trueaccon2194/opsional" id="form" method="post" accept-charset="utf-8">
<div class="row">
<div class="col-md-12 input group kolom">
<div id="warna1" style="padding-left:0;padding-right:0;" class="col-md-12 col-sm-12 col-xs-12">
<input type="text" id="warna1" name="warna[]" class="joss form-control">
<br>
</div>
<div id="warna2" style="padding-left:0;padding-right:0;" class="col-md-12 col-sm-12 col-xs-12">
<input type="text" id="warna2" name="warna[]" class="joss form-control">
<br>
</div>
<div id="warna3" style="padding-left:0;padding-right:0;" class="col-md-12 col-sm-12 col-xs-12">
<input type="text" id="warna3" name="warna[]" class="joss form-control">
<br>
</div>
<button type="button" class="simpan_warna btn btn-primary">Simpan</button>
</form>
$('.simpan_warna').click(function() {
var UrlToPass = $("#form").serialize();
$.ajax({ // Send the credential values to another checker.php using Ajax in POST menthod
type: "POST",
data: UrlToPass,
url: baseURL + "trueaccon2194/opsional/proses_tambah_opsi_warna",
beforeSend: function() {
$('.simpan_warna').prop('disabled', true);
$('.simpan_warna').html('sedang menyimpan...'); //Loading button text
},
success: function(success) { // Get the result and asign to each cases
$('.simpan_warna').prop('disabled', false);
$('.simpan_warna').html('Simpan'); //reset button text to original text
alert('Data Berhasil disimpan!');
$('#modal_form').modal('hide');
location.reload();
},
error: function() {
$('.simpan_warna').prop('disabled', false);
$('.simpan_warna').html('Simpan'); //reset button text to original text
alert('Data gagal disimpan!');
}
});
return false;
});
my controller is :
function proses_tambah_opsi_warna(){
$target = $this->input->post('warna[]');
if($this->input->post()){
$data = $this->input->post();
$data['nama_depan'] = $this->data['nama_depan'];
$this->opsional_adm->add_warna($data);
log_helper("warna", "Menambah Warna ".$target."");
}else{
log_helper("warna", "Gagal Menambah warna baru");
}
}
Try to get the 'warna' post value, not the 'warna[]' :
$target = $this->input->post('warna');
With this, $target will be an array and you'll able to access values with a loop like this :
foreach ($target as $id => $value) {
echo $value;
}

jQuery function works intermittently

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());
});
});

Categories