Design page code:
<input type="text" class="form-control " placeholder="Bill.No"name="billno" id="AcNo" value="" required>
Ajax code:
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "POST",
url: "<?php echo base_url();?>TipUp_Loan/get_AcNo",
data:{id:$(this).val()},
datatype:'json',
success: function (data) {
var res = jQuery.parseJSON(data);
$("#AcNo").val(res);
alert(ok);
}
});
});
</script>
Controller code:
public function get_AcNo()
{
$query = $this->db->query('SELECT MAX(no) AS `AcNo` FROM `salesbill` ORDER BY no DESC LIMIT 1')->row_array();
//print_r($query);
if($query['AcNo'] == "")
{
$message = 1;
}
else
{
$message = $query['AcNo']+1;
}
echo json_encode ($message);
}
My problem is the bill no is constantly showing 2 how to auto increment the bill no once the form is submited
Try this one
$(document).ready(function(){
$.ajax({
type: "POST",
url: "TipUp_Loan/get_AcNo",
data:{id:$(this).val()},
datatype:'json',
success: function (data) {
$("#AcNo").val(data);
alert(ok);
}
});
});
public function get_AcNo()
{
$query = $this->db->query('SELECT MAX(no) AS `AcNo` FROM `salesbill` ORDER BY no DESC LIMIT 1')->row_array();
//print_r($query);
if ($query['AcNo'] == ""){
$message = 1;
} else {
$message = $query['AcNo']+1;
}
echo $message;
}
edit it like this
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "POST",
url: "<?php echo base_url();?>TipUp_Loan/get_AcNo",
data:{id:$(this).val()},
datatype:'json',
success: function (data) {
$("#AcNo").val(data);
alert('ok');
}
});
});
</script>
public function get_AcNo()
{
$query = $this->db->query('SELECT MAX(no) AS `AcNo` FROM `salesbill` ORDER BY no DESC LIMIT 1')->row_array();
//print_r($query);
if ($query['AcNo'] == ""){
$message = 1;
} else {
$message = $query['AcNo']+1;
}
echo $message;
}
You can try this sql query:
$query = $this->db->query('SELECT MAX(no) AS "AcNo" FROM "salesbill"')->row_array();
or you can try this query as well:
$query = $this->db->query('SELECT count(no) AS "AcNo" FROM "salesbill"')->row_array();
Related
I have two textboxes namely no_id and customer_name. when the user enters no_id, customer_name is filled in automatically.
Form
<form>
<input type="text" name="no_id" onkeyup="autofill()" id="no_id">
<input type="text" name="customer_name" id="customer_name" readonly>
<!--textbox customer_name is readonly-->
</form>
Javascript
<script type="text/javascript">
function autofill(){
var no_id = $("#no_id").val();
$.ajax({
url: 'ajax.php',
data:"no_id="+no_id ,
}).success(function (data) {
var json = data,
obj = JSON.parse(json);
$('#customer_name').val(obj.customer_name);
});
}
</script>
ajax.php
include 'conn.php';
$npwp = $_GET['no_id'];
$query = mysqli_query($conn, "select * from ms where no_id='$no_id'");
$ms = mysqli_fetch_array($query);
$data = array(
'customer_name' => $ms['customer_name']);
echo json_encode($data);
The scripts above works for me.
Now I want to modify it.
When the no_id entered is NOT stored in the database, the customer_name box attribute becomes readonly=false, so the user can fill in customer_name box.
you can use jquery onChange method on no_id input to send no_id value and search it's stored in the database or not and return true or false (0 or 1)like this code:
$('#no_id')onchange(function(){
var no_id = $(this).val();
$.ajax({
url: 'ajax.php',
data:"no_id="+no_id ,
}).success(function (data) {
if(data == true){
$('#customer_name').attr('readonly');
}else if(data == false){
$('#customer_name').removeAttr('readonly');
}
});
});
I prefer to create another function for no_id onChange method
Here I am counting rows in mysql and if rows == 0, then removing readonly attribute
Javascript
<script type="text/javascript">
function autofill(){
var no_id = $("#no_id").val();
$.ajax({
url: 'ajax.php',
data:"no_id="+no_id ,
success : function (data) {
var json = data;
obj = JSON.parse(json);
if(obj.success=='true') {
$('#customer_name').val(obj.customer_name).attr("readonly", true);
} else {
$('#customer_name').val("").attr("readonly", false);
}
}
})
}
</script>
AJAX.php
include 'conn.php';
$npwp = $_GET['no_id'];
$query = mysqli_query($conn, "select * from ms where no_id='$npwp'");
if(mysqli_num_rows($query) >= 1 ) {
$ms = mysqli_fetch_array($query);
$data = array('customer_name' => $ms['customer_name'], 'success'=>'true');
echo json_encode($data);
} else {
$data = array('success'=>'false');
echo json_encode($data);
}
im trying to send some data through ajax jQuery to a php file with POST but i keep getting POST 405 Method Not Allowed error, any ideas to solve this issue will be appreciated, heres the function that makes the call
function manageData(key) {
var name = $("#countryName");
var abbrev = $("#countryAbbrev");
var desc = $("#countryDesc");
if (isNotEmpty(name) && isNotEmpty(abbrev) && isNotEmpty(desc)) {
$.ajax({
url: 'http://127.0.0.1:5500/ajax.php',
method: 'POST',
dataType: 'text',
data: {
key: key,
name: name.val(),
abbrev: abbrev.val(),
desc: desc.val()
},
success: function (response) {
alert(response);
}
});
}
}
and here is the ajax.php file code
<?php
if (isset($_POST['key'])) {
$conn = new mysqli(host:'localhost', username:'root', passwd:'root',
dbname:'mysqldatamanager');
$name = $conn->real_escape_string($_POST['name']);
$abbrev = $conn->real_escape_string($_POST['abbrev']);
$desc = $conn->real_escape_string($_POST['desc']);
if($_POST['key'] == 'addNew') {
$sql = $conn->query(query:"SELECT id FROM country WHERE
countryName = '$name'");
if ($sql->num_rows > 0) {
exit("Country already exists!");
} else {
$conn->query("INSERT INTO country (countryName,
countryAbbrev, countryDesc) VALUES ('$name', '$abbrev',
'$desc')");
exit("Country has been added succesfully!");
}
}
}
?>
Please try below code.
function manageData(key) {
var name = $("#countryName");
var abbrev = $("#countryAbbrev");
var desc = $("#countryDesc");
if (isNotEmpty(name) && isNotEmpty(abbrev) && isNotEmpty(desc)) {
$.ajax({
url: 'http://localhost/ajax.php',
type: "POST",
data: {
key: key,
name: name.val(),
abbrev: abbrev.val(),
desc: desc.val()
},
success: function (response) {
alert(response);
}
});
}
}
I am trying to login with ajax. The script is working well and I am getting logged in but I am not getting redirected to the dashboard.php file. Codes are given below. Please try to help me out.
Ajax call
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function() {
var dataString = {
username: $("#username").val(),
password: $("#password").val(),
};
$.ajax({
type: "POST",
url: "login-process.php",
data: dataString,
cache: true,
beforeSend: function(){
$('#loading-image').show();
},
complete: function(){
$('#loading-image').hide();
},
success: function(html){
$('.message').html(html).fadeIn(500);
}
});
return false;
});
});
</script>
login-process.php
<?php
include'config/db.php';
$msg = null;
$date = date('Y-m-d H:i:s');
$uname = (!empty($_POST['username']))?$_POST['username']:null;
$pass = (!empty($_POST['password']))?$_POST['password']:null;
if($_POST){
$stmt = "SELECT * FROM members WHERE mem_uname = :uname";
$stmt = $pdo->prepare($stmt);
$stmt->bindValue(':uname', $uname);
$stmt->execute();
$checklgn = $stmt->rowCount();
$fetch = $stmt->fetch();
if($checklgn > 0){
if(password_verify($pass, $fetch['mem_pass'])){
session_start();
$_SESSION['sanlogin'] = $fetch['mem_id'];
$msg = "<div class='message-success'>Access Granted! Please wait...</div>";
$go_login = header("refresh:2; url=dashboard.php");
}else{
$msg = "<div class='message-error'>Password mismatch. Please try again!</div>";
}
}else{
$msg = "<div class='message-error'>User not found. Please try again!</div>";
}
}
echo $msg;
echo $go_login;
?>
If you use AJAX to log in, you must use javascript to redirect. Redirecting PHP will only result in the AJAX call being redirected which doesn't produce the desired result.
In your success clause of the ajax request you can add window.location.replace("dashboard.php");
In you ajax success:
use window.location.href="/uri/to/redirect";
setTimeout(function(){
window.location.href="/uri/to/redirect";
},2000);
You cannot use header PHP function in this situation.
You should redirect in your $.ajax function like this:
1) You should return JSON in your login-process.php:
...
$result = array();
if($_POST){
$stmt = "SELECT * FROM members WHERE mem_uname = :uname";
$stmt = $pdo->prepare($stmt);
$stmt->bindValue(':uname', $uname);
$stmt->execute();
$checklgn = $stmt->rowCount();
$fetch = $stmt->fetch();
if($checklgn > 0){
if(password_verify($pass, $fetch['mem_pass'])){
session_start();
$_SESSION['sanlogin'] = $fetch['mem_id'];
$result = array(
'msg' => "<div class='message-success'>Access Granted! Please wait...</div>",
'redirect' => 'dashboard.php',
);
}else{
$result = array(
'msg' => "<div class='message-error'>Password mismatch. Please try again!</div>",
);
}
}else{
$result = array(
'msg' => "<div class='message-error'>User not found. Please try again!</div>",
);
}
}
echo json_encode($result);
exit;
2) You should add parameter dataType into your $.ajax call and process attribute redirect of the server answer (if this attribute exists):
$(document).ready(function () {
$("#submit").click(function () {
var dataString = {
username: $("#username").val(),
password: $("#password").val(),
};
$.ajax({
dataType: 'json', // <-- set expected dataType here
type: "POST",
url: "login-process.php",
data: dataString,
cache: true,
beforeSend: function () {
$('#loading-image').show();
},
complete: function () {
$('#loading-image').hide();
},
success: function (data) {
$('.message').html(data.message).fadeIn(500);
// if we have attribute "redirect" in answer
if(typeof data.redirect !== 'undefined'){
// redirect here after 2 seconds
setTimeout(function(){
document.location.href = data.redirect;
},2000);
}
}
});
return false;
});
});
I have a page with list of buttons, when each button is clicked, it's value is captured and ajax call in made. PHP does DB updates on ajax call. I want to return data to ajax call. The data is obtained from DB. But I'm unable to point out what's the error in below code.
Here is PHP code:
if (isset($_GET['val']))
{
$chapter_id=$_GET['val'];
$sql= "SELECT file_name,edit_link,name,email FROM `chapter_list` where chapter_id='$chapter_id'";
$result = mysql_query($sql,$rst);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$vol_name = $row["name"];
$vol_email= $row["email"];
$vol_link= $row["edit_link"];
}
$update=mysql_query("UPDATE `chapter_list` SET `status` = '$update_status' WHERE `chapter_list`.`chapter_id` = '$chapter_id';");
header('Content-Type: application/json');
echo json_encode(array("name"=>$vol_name,"email"=>$vol_email,"link"=>$vol_link));
}
Here is the AJAX request
$(document).ready(function(){
$('.btn').click(function(){
var clickBtnValue = $(this).val();
$.ajax ({
url: '',
data: { val : clickBtnValue},
dataType:'JSON',
success: function(res) {
alert(res.name);
}
});
});
});
I'm not getting the alert!
Try like this.
Maybe response data is null.check your php code(query lines).
Here My php code is :
if (isset($_GET['val'])) {
$vol_name = 'dummy_name';
$vol_email = 'dummy_email';
$vol_link = 'dummy link';
header('Content-Type: application/json');
echo json_encode(array("name"=>$vol_name,"email"=>$vol_email,"link"=>$vol_link));
exit;
}
My javascriptcode is :
<input type="text" class="btn" value="test" />
<script type="text/javascript">
if('addEventListener' in document){
document.addEventListener("DOMContentLoaded", function(e){
//dom loaded
$(document).on("click",".btn",function(e){
e.preventDefault()
var e_val = $(this).val();
console.log('my value is :' + e_val);
if(e_val){
$.ajax({
type: "get",
dataType: 'json',
url: 'here your url or slash',
data: { // request e_val
val : e_val,
}
}).done(function(xhr) {
// console.log(xhr);
if(xhr.name){
alert('response data is '+ xhr.name);
}
})
}
})
},false)
}
</script>
try this..
while($row = mysql_fetch_assoc($result))
{
$vol_name = $row["name"];
$vol_email= $row["email"];
$vol_link= $row["edit_link"];
$ret[$vol_name]= array(
'email'=>$vol_email,
'link'=>$vol_link
);
}
then use in the return statement..
echo json_encode($ret);
You can send parameters in HTML
<button class="btn" atribute_id="21543">Button</button>
$(document).ready(function() {
$('.btn').click(function() {
var Value_of_Btn= $(this).attr("atribute_id"); <-------
$.ajax({
url: '',
data: {
val: clickBtnValue
},
dataType: 'JSON',
success: function(res) {
alert(res.name);
}
});
});
});
In the below codeigniter code i have placed controller,model and view.My aim when i select exam name it should drop corresponding course code from examcourse table.But my actual result when i select exam name it is not droping the dropdown .Pls help me to do this.
Controller:import
public function index()
{
//echo "inside form upload";
$data = array();
//$college_name = $this->session->userdata('college_name');
if($query = $this->import_model->get_exam_data())
{
$data['exam_data'] = $query;
}
//$this->load->view('student_view', $data);
$this->load->view('form_upload',$data);
}
function subjectcodedetails()
{
$data = array();
//$college_name = $this->session->userdata('college_name');
$exam_name = $this->input->post('exam_name');
//$course_name = $this->input->post('course_name');
if($query = $this->import_model->get_subject_records($exam_name))
{
$data['course_code'] = $query;
}
$this->load->view('subject_view', $data);
}
model:
function get_exam_data()
{
$this->db->distinct();
$this->db->select("CONCAT(exam_name) AS fullexamname", FALSE);//this will concat the value
//$this->db->where('college_name',$college_name);
$query = $this->db->get('examcourse');
return $query->result();
}
function get_subject_records($exam_name)
{
//echo "exam_name inside get_subject_records".$exam_name;
$this->db->select('course_code');
//$this->db->where('exam_name',$exam_name);
$this->db->where('fullexamname',$exam_name);
//$this->db->where('college_name',$college_name);
$query = $this->db->get('examcourse');
return $query->result();
}
view:
form_upload
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".dropdown_class").change(function()
{
var id=$(this).val();
// Please find the course_code, course_code was not found
var dataString = 'course_code='+ id;
$.ajax
({
type: "POST",
url: "import/subjectcodedetails",
data: dataString,
cache: false,
success: function(html)
{
$(".dropdown_class12").html(html);
}
});
});
</script>
<form action="http://localhost/CodeIgniter/index.php/import/upload" method="post" accept-charset="utf-8" enctype="multipart/form-data"> <?php
$data = array();
$data["Select Exam Name"] = "Select Exam Name";
foreach ($exam_data as $row)
{
$data[$row->fullexamname] = $row->fullexamname;
}
echo form_dropdown('exam_name', $data, 'small', 'class="dropdown_class" id="exam_name_id" ');
?>
view:subject_view
<?php
$data = array();
foreach ($course_records as $row)
{
$data[$row->course_code] = $row->course_code;
}
echo form_dropdown('course_name', $data, 'small','class="dropdown_class12" id="course_name_id"');
?>
$(document).ready(function () {
$(".dropdown_class").change(function () {
var id = $(this).val();
// Please find the course_code, course_code was not found
var dataString = 'course_code=' + id;
$.ajax({
type: "POST",
url: "import/subjectcodedetails",
data: dataString,
cache: false,
success: function (html) {
$(".dropdown_class12").html(html);
}
});
});
};
Missing } at the end of $(document).ready block