While inserting Data into MySQL using Ajax and PHP, taking limited data from rich textarea,Is there any problem?
JQuery Script
$('#adddesc').click(function(e)
{
e.preventDefault();
var txtcategoryname=tinyMCE.get('txtcategoryname').getContent();
var txttitle=$('#txttitle').val();
var selectError1=$("#selectError1").val();
var selectError2=$("#selectError2").val();
var selectError3=$("#selectError3").val();
//var fimage=$("#fimage").val();
//alert($("#selectError2").val().length);
var dataString;
var err;
err=(txttitle!='' && txtcategoryname!='' && $("#selectError1").val()!='0' && $("#selectError2").val()!='0' && $("#selectError3").val()!='0')?'0':'1';
// var dataString1="txttitle="+txttitle+"& description="+txtcategoryname+"& catname="+selectError1+"& tags="+selectError2;
//dataString1="txttitle="+txttitle+"& description="+txtcategoryname+"& catname="+selectError1+"& tags="+selectError2+"& subcat="+selectError3;
// alert(dataString1);
if(err=='0')
{
dataString="txttitle="+txttitle+"& description="+txtcategoryname+"& catname="+selectError1+"& tags="+selectError2+"& subcat="+selectError3;
//alert(dataString);
$.ajax({
type: "POST",
url: "aAddDescription.php",
data: dataString,
cache: true,
beforeSend: function(){ $("#adddesc").val('Adding Des.....');},
success: function(html){
//$("#txtcategoryname").val('');
tinyMCE.get('txtcategoryname').setContent('');
$("#txttitle").val('');
//$("#selectError1").get(0).selectedIndex = 0;
//$("#error").removeClass("alert alert-error");
$("#error").addClass("alert alert-success");
$("#error").html("<span style='color:#cc0000'>Success:</span> Description Added Successfully. ").fadeIn().delay(3000).fadeOut();
}
});
HTML Form script
<form class="form-horizontal" method="POST" action="" enctype="multipart/form-data" autocomplete="off">
<fieldset>
<div class="control-group">
<label class="control-label" for="selectError">Select Cateogry</label>
<div class="controls">
<?php
$result=mysqli_query($db,"SELECT * FROM categories ");
//$count=mysqli_num_rows($result);
$op="<option value='0'>Select Category</option>";
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC))
{
$op.="<option value='".$row['id']."'>".$row['title']."</option>";
}
?>
<select id="selectError1" >
<?php echo $op; ?>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="selectError">Select Sub Cateogry</label>
<div class="controls">
<select id="selectError3">
<option selected="selected" value="0">--Select Sub--</option>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="focusedInput">Enter Title:: </label>
<div class="controls">
<input class="form-control" type="text" id="txttitle" name="txttitle" value="" placeholder="Enter Title"><span id="user-availability-status"></span> <img src="LoaderIcon.gif" id="loaderIcon" style="display:none;width:20px;height:20px;" />
</div></div>
<div class="control-group">
<textarea rows="10" cols="20" name="content" style="width:100%; height:150px" id="txtcategoryname"></textarea>
</div>
<div class="control-group">
<label class="control-label" for="selectError1">Tags(select All with Press Ctrl)</label>
<div class="controls">
<?php
$result=mysqli_query($db,"SELECT * FROM tags ");
//$count=mysqli_num_rows($result);
$op1='';
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC))
{
$op1.="<option value='".$row['title']."'>".$row['title']."</option>";
}
?>
<select id="selectError2" multiple >
<?php //echo $op1; ?>
</select>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary" id="adddesc">Save changes</button>
<button class="btn">Cancel</button>
</div>
</fieldset>
</form>
aAddDescription.php
<?php
include("common/db.php");
session_start();
if(isSet($_POST['description']) && isSet($_POST['txttitle']))
{
// username and password sent from Form
$description=$_POST['description'];
$txttitle=mysqli_real_escape_string($db,$_POST['txttitle']);
$catname=mysqli_real_escape_string($db,$_POST['catname']);
$subcat=mysqli_real_escape_string($db,$_POST['subcat']);
$tags=mysqli_real_escape_string($db,$_POST['tags']);
//$fimage=$_FILES['fimage']['name'] ;
$cby=$_SESSION['login_user'];
//$result=mysqli_query($db,"SELECT * FROM categories WHERE title='$categoryname'");
//$count=mysqli_num_rows($result);
//$target_dir = "uploads/";
//$target_file = $target_dir.$_FILES['fimage']['name'];
//move_uploaded_file($_FILES['fimage']['tmp_name'],$target_file);
//$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
// If result matched $myusername and $mypassword, table row must be 1 row
/*if($count>0)
{
echo "0";
}
else
{
mysqli_query($db,"INSERT INTO categories(title) VALUES('".$categoryname."')");
echo "1";
}*/
//date_default_timezone_set('Asia/Delhi');
mysqli_query($db,"INSERT INTO description(title,description,cat_id,tags_id,created,modified,createdby,modifiedby,subcat_id) VALUES('".$txttitle."','".$description."','".$catname."','".$tags."','".date("Y-m-d H:i:s")."','".date("Y-m-d H:i:s")."','".$cby."','".$cby."','".$subcat."')");
$cid=mysqli_insert_id($db);
$cresult=mysqli_query($db,"SELECT * FROM counter WHERE cont_id='$cid'");
$ccount=mysqli_num_rows($cresult);
if($ccount==0)
{
mysqli_query($db,"INSERT INTO counter(cont_id) VALUES(".$cid.")");
}
echo "1";
}
?>
Please help me any thing wrong in this code?...even i changed cache to false also getting same problem. if i type 1000/less or more lines data, always it is taking limited data. Please help me. thanks in Advance
I'd be willing to bet that your text has characters in it that are interfering with the url like "&", "?", "/", "=", etc.
You should encode your text with encodeURIComponent() like this:
var txtcategoryname=encodeURIComponent(tinyMCE.get('txtcategoryname').getContent());
var txttitle=encodeURIComponent($('#txttitle').val());
var selectError1=encodeURIComponent($("#selectError1").val());
var selectError2=encodeURIComponent($("#selectError2").val());
var selectError3=encodeURIComponent($("#selectError3").val());
Related
I used this script (https://www.webslesson.info/2020/02/instant-search-with-pagination-in-php-mysql-jquery-and-ajax.html) and I would like to add a form to directly access a page number.
I tried this but it doesn't work !
<div class="goto-page">
<form action="" method="POST" onsubmit="return pageValidation()">
<input type="submit" class="goto-button" value="Go to page">
<input type="text"
class="enter-page-no" maxlength="4" size="3"
name="goto" min="1"
required >
</form>
</div>
PHP Code modified
if (isset($_POST['goto'])) {
$start = (($_POST['page'] - 1) * $limit);
$page = $_POST['goto'];
}
else
{
if($_POST['page'] > 1)
{
$start = (($_POST['page'] - 1) * $limit);
$page = $_POST['page'];
}
else
{
$start = 0;
}
}
Consider the following example. This expands on the jQuery already in use in the example you linked to.
$(function() {
function load_data(page, query = '') {
$.ajax({
url: "fetch.php",
method: "POST",
data: {
page: page,
query: query
},
success: function(data) {
$('#dynamic_content').html(data);
}
});
}
load_data(1);
$(document).on('click', '.page-link', function() {
var page = $(this).data('page_number');
var query = $('#search_box').val();
load_data(page, query);
});
$('#search_box').keyup(function() {
var query = $('#search_box').val();
load_data(1, query);
});
$(".goto-page form").submit(function(evt) {
evt.preventDefault();
load_data(parseInt($(".goto-page input[name='goto']").val()));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<br />
<div class="container">
<h3 align="center">Live Data Search with Pagination in PHP Mysql using Ajax</h3>
<br />
<div class="card">
<div class="card-header">Dynamic Data</div>
<div class="card-body">
<div class="form-group">
<input type="text" name="search_box" id="search_box" class="form-control" placeholder="Type your search query here" />
</div>
<div class="table-responsive" id="dynamic_content">
</div>
<div class="goto-page">
<form>
<button type="submit">Go To Page</button>
<input type="text" class="enter-page-no" maxlength="4" size="3" name="goto" value="1" required>
</form>
</div>
</div>
</div>
</div>
When Enter is hit or the Button pressed, the form is submitted. The submit callback will gather the value and use load_data() to load that page.
I want to update multiple or single row in database in one query where multiple ids or single id post from the form. I couldn't find it works in update batch. I don't know how to do it. I have already searched on google on how to make it but I have no luck. Your answer is very much appreciated.
Html and AJAX
<form class="form-horizontal" enctype="multipart/form-data" method="POST">
<div class="form-group">
<label class="col-sm-3 control-label" for="name"><?php echo $this->lang->line('Select Lead Contacts'); ?>
</label>
<div class="col-sm-9 col-md-6 col-lg-6">
<select id="chkveg" name="mySelect[]" class="form-control" multiple="multiple">
<?php foreach($list_of_leads_contact as $lc) {
?>
<option value="<?php echo $lc->id ?>"><?php echo $lc->first_name ?> <?php echo $lc->last_name ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label" ><?php echo $this->lang->line('Contact Group'); ?> *
</label>
<div class="col-sm-9 col-md-6 col-lg-6">
<?php if(isset($group_checkbox)) echo $group_checkbox; ?>
<span class="red">
<?php
if($this->session->userdata('group_type_error')==1){
echo '<b>'.$this->lang->line('Contact Group').'</b>'.str_replace("%s","", $this->lang->line("required"));
$this->session->unset_userdata('group_type_error');
}
?>
</span>
</div>
</div>
</div>
<button name="submit" id="submitButton" type="button" class="btn btn-primary btn-lg"><i class="fa fa-save"></i> <?php echo $this->lang->line('Save');?></button>
</form>
<script type="text/javascript">
$j(function() {
$( ".datepicker" ).datepicker();
});
$(function() {
$('#submitButton').click(function() {
var dataString = $('.form-horizontal').serialize();
$.ajax({
type: 'POST',
url: base_url +'lead/insert_leads_in_groups', // your php url would go here
data: dataString,
}).done(function(msg) {
});
});
});
</script>
Controller Code
public function insert_leads_in_groups()
{
$user_id = $this->input->post('mySelect');
$contact_group_id = $this->input->post('contact_type_id');
foreach($user_id as $row ) {
$data = array(
array(
'contact_group_id' => $contact_group_id,
),
);
$this->db->update_batch('leads', $data, 'id');
}
}
Error
A Database Error Occurred
One or more rows submitted for batch updating is missing the
specified index.
In CI docs you can read
the third parameter is the where key.
and below see the resulting query example. From that its't obviouse that each sub-array should contain a corresponding value for that key.
So, in your case, you need to put the id value to each sub-array.
public function insert_leads_in_groups()
{
$user_id = $this->input->post('mySelect');
$contact_group_id = $this->input->post('contact_type_id');
$data = [];
foreach($user_id as $id ) {
$data[] = [
'id' = > $id,
'contact_group_id' => $contact_group_id,
];
}
$this->db->update_batch('leads', $data, 'id');
}
I have created one IMS System. In that i have to create bill on order page and in order page when i select customer name from drop down than customer_address,customer_phone and gst number should automatically fill in text box.In database i have created one table named partys in that all data are available(Customer_name,Customer_address,customer_phone and gst) If anybody knows solution than please help. Below is my code
<div class="form-group">
<label for="gross_amount" class="col-sm-5 control-label" style="text-align:left;">Customer Name</label>
<div class="col-sm-7">
<select name="customer_name" id="client" style="width:100%;">
<?php
$dbc = mysqli_connect('localhost', 'root', '', 'stock')
or die('Error connecting to MySQL server.');
$query = "SELECT * FROM partys";
$result = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_array($result)) {
?>
<option value="<?php echo $row['party_name'] ?>"><?php echo $row['party_name'] ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="form-group">
<label for="gross_amount" class="col-sm-5 control-label" style="text-align:left;">Customer Address</label>
<div class="col-sm-7">
<input type="text" class="form-control" id="customer_address" name="customer_address" placeholder="Enter Customer Address" autocomplete="off">
</div>
</div>
<div class="form-group">
<label for="gross_amount" class="col-sm-5 control-label" style="text-align:left;">Customer Phone</label>
<div class="col-sm-7">
<input type="text" class="form-control" id="customer_phone" name="customer_phone" placeholder="Enter Customer Phone" autocomplete="off">
</div>
</div>
<div class="form-group">
<label for="gstin" class="col-sm-5 control-label" style="text-align:left;">GSTIN</label>
<div class="col-sm-7">
<input type="text" class="form-control" id="gstin" name="gstin" placeholder="Enter GST Number" autocomplete="off">
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
// On change of the dropdown do the ajax
$("#client").change(function() {
$.ajax({
// Change the link to the file you are using
url: '/create.php',
type: 'post',
// This just sends the value of the dropdown
data: {customer_name : party_name},
dataType: 'json',
success: function(response) {
// Parse the jSON that is returned
// Using conditions here would probably apply
// incase nothing is returned
var response = JSON.parse(response);
// These are the inputs that will populate
$("#customer_address").val(response.customer_address);
$("#customer_phone").val(response.customer_phone);
$("#gstin").val(response.gstin);
}
});
});
});
</script>
create separate php file as customer.php and write following code
$content = file_get_contents("php://input");
$customer_data = json_decode($content, true);
$customer_name = $customer_data['customer_name'];
//using mysql query fetch all data of particular customer
$query = mysqli_query($dbc,"SELECT * FROM partys WHERE party_name=$customer_name");
$result = mysqli_fetch_array($query);
echo json_encode($result);
after getting this alert json response in ajax call. This will give customer data.
and modify your ajax call as
<script>
$(document).ready(function() {
// On change of the dropdown do the ajax
$("#client").change(function() {
$.ajax({
// Change the link to the file you are using
url: 'customer.php',
type: 'post',
// This just sends the value of the dropdown
data: {customer_name : party_name},
dataType: 'json',
success: function(response) {
alert(response);
// Parse the jSON that is returned
// Using conditions here would probably apply
// incase nothing is returned
var response = JSON.parse(response);
// These are the inputs that will populate
$("#customer_address").val(response.customer_address);
$("#customer_phone").val(response.customer_phone);
$("#gstin").val(response.gstin);
}
});
});
});
I want to validate my form's input with database, so when user type on form's input and contain email already in use or exists it will display an alert and cant submit. I use CodeIgniter framework and jQuery.
I've tried using the code below to check if name exists and this could work. But when I apply it to the other case for email, it doesn't work and display message "The URI you submitted has disallowed characters."
How is the correct way to fix this?
View (kasir_halaman.php) :
<div id="addModal" class="modal fade" role="modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title"><span class="glyphicon glyphicon-plus"></span> Tambah Kasir</h3>
</div>
<div class="modal-body">
<form action="<?php echo site_url('admin/kasir/addpetugas'); ?>" method="post" enctype="multipart/form-data">
<div class="form-group">
<label>Nama</label>
<input type="text" id="nama" name="nama" class="form-control" maxlength="100" required>
</div>
<div class="form-group">
<label>E-mail</label>
<input type="email" id="email" name="email" class="form-control" maxlength="150" required>
</div>
<div class="form-group">
<label>Kategori</label>
<select class="form-control" name="kategoripetugas" required>
<option value=""> -- Pilih Kategori -- </option>
<option value="1">Admin</option>
<option value="2">Kasir</option>
</select>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control" maxlength="30">
</div>
<div class="form-group">
<label>Ulangi Password</label>
<input type="password" name="confirmpassword" class="form-control" maxlength="30">
</div>
<button type="submit" class="btn btn-primary" style="width:100%;">Tambah</button>
</form>
</div>
</div>
</div>
</div>
Controller (kasir.php) :
public function cekData($table, $field, $data)
{
$match = $this->Crud->read($table, array($field=>$data), null, null);
if($match->num_rows() > 0){
$report = 2;
}else{
$report = 1;
}
echo $report;
}
public function register_email_exists()
{
if (array_key_exists('email',$_POST)) {
if ($this->Crud->email_exists($this->input->post('email')) == TRUE ) {
echo false;
} else {
echo true;
}
}
}
Model (Crud.php) :
function email_exists($email)
{
$this->db->where('email', $email);
$query = $this->db->get('petugas');
if( $query->num_rows() > 0 ){ return TRUE; } else { return FALSE; }
}
jQuery AJAX (petugas.js) :
$(document).ready(function(){
var check1=0; var id;
$("#nama").bind("keyup change", function(){
var nama = $(this).val();
$.ajax({
url:'kasir/cekData/petugas/nama/'+nama,
data:{send:true},
success:function(data){
if(data==1){
$("#report1").text("");
check1=1;
}else{
$("#report1").text("*nama petugas sudah terpakai");
check1=0;
}
}
});
});
var check2=0;
$("#email").bind("keyup change", function(){
//var email = $(this).val();
$.ajax({
url:'kasir/register_email_exists',
data:{send:true},
success:function(data){
if(data==1){
$("#report2").text("");
check2=1;
}else{
$("#report2").text("*email sudah terpakai");
check2=0;
}
}
});
});
var check4=0;
$("#confirmpassword").bind("keyup change", function(){
var password = $("#password").val();
var confirmpassword = $(this).val();
if (password == confirmpassword){
$("#report4").text("");
check4=1;
}else{
$("#report4").text("*Password tidak sama");
check4=0;
}
});
$("#submit").click(function(event){
if(check1==0){
event.preventDefault();
}
if(check4==0){
event.preventDefault();
}
});
});
Use ajax post method instead and take data at php side from POST request
you can check more about jquery ajax here: http://api.jquery.com/jquery.post/
and about php post here: http://php.net/manual/en/reserved.variables.post.php
//JS
$("#email").bind("keyup change", function(){
var email = $(this).val();
$.ajax({
url:'kasir/register_email_exists',
type: "POST",// <---- ADD this to mention that your ajax is post
data:{ send:true, email:email },// <-- ADD email here as pram to be submitted
success:function(data){
if(data==1){
$("#report2").text("");
check2=1;
}else{
$("#report2").text("*email sudah terpakai");
check2=0;
}
}
});
});
// PHP
// At php side take your data from $_POST
$send = $_POST['send'];
$email = $_POST['email'];
...
I have this script that allows me to send data to the database without reloading the page. The form data is sent to file process.php.
At the end of the process, inside the div box of the form is printed a notice that everything went ok
<script type="text/javascript">
$(document).ready(function(){
$(document).on('submit', '.formValidation', function(){
var data = $(this).serialize();
$.ajax({
type : 'POST',
url : 'submit.php',
data : data,
success : function(data){
$(".formValidation").fadeOut(500).hide(function(){
$(".result").fadeIn(500).show(function(){
$(".result").html(data);
});
});
}
});
return false;
});
});
</script>
Page success.php:
foreach( $_POST as $key => $value ) {
$sql = "INSERT INTO tbl_".$key."(nome_".$key.") VALUES ('$value')";
$result = dbQuery($sql);
}
print "ok";
And the div box for the notice <div class="result"></div>
The problem: I have many div box with a form and when I print the notice of success, it happen into all the <div>, because the call notification is always .result
success: function(data){
$(".formValidation").fadeOut(500).hide(function(){
$(".result").fadeIn(500).show(function(){
$(".result").html(data);
});
});
}
What I want: Print the success notice in its own div depending on the form that I sent.
Thanks
EDIT: The html interested
<form id="myform2" class="formValidation" name="myform2" action="" method="post"></form> <!-- this is the form for the <div> in html5 -->
<div class="widget-body">
<div class="widget-main">
<div>
<label for="form-field-select-1">Comune</label>
<select name="comune" class="form-control" id="form-field-select-1" form="myform2">
<option value="">Seleziona...</option>
<?php
$comune = "SELECT * FROM tbl_comune ORDER BY nome_comune ASC";
$result_comune = dbQuery($comune);
if (dbNumRows($result_comune) > 0) {
while($row_comune = dbFetchAssoc($result_comune)) {
extract($row_comune);
?>
<option value="<?php echo $id_comune; ?>"><?php echo $nome_comune; ?></option>
<?php
}
} else {
?>
<option value="">Non ci sono dati</option>
<?php
}
?>
</select>
</div>
<hr>
<div class="widget-body">
<div class="widget-main">
<div>
<input type="text" name="comune" id="comune" value="" placeholder="Aggiungi Comune" form="myform2">
<input type="submit" name="submit" value="Submit" class="btn btn-sm btn-success" form="myform2">
<div class="result"></div>
</div>
</div>
</div>
</div>
</div>
If the form is in a div and the result is next to the form, you can do sibling:
$form.next(".result").html(data);
or elsewhere in the same parent:
$form.parent().find(".result").html(data);
or in your case
$form.find(".result").html(data);
Like this - note I have removed all the unnecessary hiding.
$(function() {
$(document).on('submit', '.formValidation', function(e) {
e.preventDefault();
var data = $(this).serialize();
$form = $(this); // save a pointer to THIS form
$result = $form.find(".result");
$.ajax({
type: 'POST',
url: 'submit.php',
data: data,
success: function(data) {
$result.html(data);
$form.fadeOut(500, function() {
$result.fadeIn(500)
});
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="myform2" class="formValidation" name="myform2" action="" method="post"></form>
<!-- this is the form for the <div> in html5 -->
<div class="widget-body">
<div class="widget-main">
<div>
<label for="form-field-select-1">Comune</label>
<select name="comune" class="form-control" id="form-field-select-1" form="myform2">
<option value="">Seleziona...</option>
</select>
</div>
<hr>
<div class="widget-body">
<div class="widget-main">
<div>
<input type="text" name="comune" id="comune" value="" placeholder="Aggiungi Comune" form="myform2">
<input type="submit" name="submit" value="Submit" class="btn btn-sm btn-success" form="myform2">
<div class="result"></div>
</div>
</div>
</div>
</div>
</div>