How to get array in ajax response to another field - php

i have an array like
[{"id_pelanggan":"1","id_tipe":"5","nama_pelanggan":"ASD","alamat_jalan":"DS","alamat_kota":"1","alamat_provinsi":"ATA","kontak_pelanggan":"45454"}]
and my ajax
$(function() {
$("#autocomplete").change(function(){
var namaagen = $("#autocomplete").val();
$.ajax({
url: '<?php echo site_url('Pelanggan/tampil_where'); ?>',
type: 'POST',
dataType: 'json',
data: {
'namaagen': namaagen
},
success: function (agen) {
$("#napem").val(agen['nama_pelanggan']);
}
});
});
});
});
});
controller :
public function tampil_where(){
$nama = $this->input->post('namaagen');
$query = $this->pelanggan_m->tampilwhere($nama);
echo json_encode($query);}
models:
public function tampilwhere($nama){
$this->db->select('*');
$this->db->from('nm_pelanggan');
$this->db->where('nama_pelanggan',$nama);
$this->db->order_by('id_pelanggan', 'ASC');
$query = $this->db->get()->result_array();
return $query;
}
but nothing happen and i already add alert(agen['nama_pelanggan']); in response success and show alert undefined pls help , thanks for advance

Please change your alert code, right now you don't access response array in the proper way:-
alert(agen[0]['nama_pelanggan']);
Instead of:-
alert(agen['nama_pelanggan']);
Thanks

Related

Retrieve value from ajax call

I have seen many topics like mine but I can't resolve my problem who seems so simple.
I have this function in JS :
function displayFullDesignation(id, select) {
var fullDesignation = $('option:selected', select).data('idacc');
var myId = parseInt(fullDesignation);
$.ajax({
url: '<?php echo $this->url(array('controller' => 'catalog', 'action' => 'fullname'));?>',
type: 'POST',
datatype: 'json',
data: {'id': myId},
success: function(data) {
if(data.success){
console.log(data.success);
}
}
});
return fullDesignation;
}
And in my controller :
/**
* AJAX Action
*/
public function fullnameAction($params) {
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('fullname', 'json')->initContext();
$response = array();
$params = $this->getAllParams();
$listModels = Application_Model_Catalog_Accessory_List::getDesignationComplet($params['id']);
$response['success'] = true;
$response['aaData'] = $listModels;
$this->getHelper('json')->sendJson($response);
}
I don't know why I can't get anything from this ajax call. If I try to do a var_dump inside my function, it does nothing at all so I think that my call isn't good, but I have other calls who work like this.
What am I doing wrong please ?
And if I do a console.log of 'data', it gives me HTML. data.success gives me undefined.
Thanks !!

How to access array sending from controller to ajax success?

as i am new to codeigniter and ajax please can any one do favor for me.I am sending array from my controller to ajax function but how can i access that array element.I am posting here my code.
Thanks in advance.
public function index()
{
$Modules = $this->General_model->AllMoudules();
$data['result'] = $this->printTree($Modules);
$output = array(
'html'=>$this->load->view("Add_user",$data),
'data' => $data
);
echo json_encode($output);
}
and ajax function
$("#user").on("click",function(){
var url=static_url+'/User';
$.ajax({
type:"POST",
url:url,
success:function(output)
{
$(output).each( function (index, o) {
alert (o.data);
});
}
});
});
controller:
public function index()
{
$Modules = $this->General_model->AllMoudules();
$data['result'] = $this->printTree($Modules);
$output = array(
'html'=>$this->load->view("Add_user",$data,true),
'data' => $data
);
echo json_encode($output);
}
**Javascript:**
$("#user").on("click",function(){
var url=static_url+'/User';
$.ajax({
type:"POST",
url:url,
success:function(output)
{
console.log(output.data);
console.log(output.html);
});
}
});
Try this.
To load view in the string you have add third parameter to load view as below:
$output = array(
'html'=>$this->load->view("Add_user", $data, true),
'data' => $data
);
To access your ajax response try the below code
success:function(output)
{
console.log(output.html);
}
Just get the length of array using array.length.
Then for loop it
You should use ajax datatype as json like this
$.ajax({
type:"POST",
url:url,
dataType: 'json',
success: function (data) {
alert(data.key);
}
});

$Ajax request in codeigniter also check if request is correct

I have tried a lot and search a lot and i did the same as i see but i do not know where i am going wrong i am new to codeigniter. Can you please tell me where i am going wrong on the code ? I want to set the product name in my input field according to the barcode selected. I am trying to fetch the product name and try to set it using AJAX but it is not working. Please you tell where is the bug in my code?
Here is my Controller Function in Main.php
public function get_product()
{
if (!$this->input->is_ajax_request()) {
exit('No direct script access allowed');
}
$barcode = $_POST['barcode'];
echo $barcode;
exit;
$data['result'] = $this->Item_model->get_product_using_barcode($barcode);
print_r($data);
exit;
}
My Ajax Code in js file :
$("#brcode").each(function(){
$("#brcode").change(function(){
let value = $("#brcode").val();
$.ajax({
url: '<?php echo site_url("main/get_product"); ?>',
type: 'POST',
data: {'barcode': $('#brcode option:selected').val() },
dataType: 'json',
success: function(data) {
//console.log(data);
alert(data);
}
})
});
});
Model Function :-
public function get_product_using_barcode($barcode){
$query = $this->db->get_where('items',array('barcode' => $barcode));
$result = $query->row();
return $result;
}
Please tell me where i am going wrong in my code?
Try this code Its works for me. Hope this will help you.
JQuery:
$(document).ready(function() {
$("#brcode").change(function(){
let value = $("#brcode").val();
$.ajax({
// URL should be include index.php
url: '<?php echo site_url("index.php/main/get_product"); ?>',
type: 'POST',
data: {'barcode': $('#brcode option:selected').val() },
dataType: 'json',
success: function(data) {
//console.log(data);
alert(data);
}
})
});
});
Controller:
public function get_product()
{
if (!$this->input->is_ajax_request()) {
exit('No direct script access allowed');
}
$barcode = $_POST['barcode'];
$data['result'] = $this->Item_model->get_product_using_barcode($barcode);
return json_encode $data;
}
Model:
public function get_product_using_barcode($barcode){
$query = $this->db->get_where('items',array('barcode' => $barcode));
$result = $query->row();
return $result;
}
Greetings!
Can you change js code as like this. and try to see on console.
$(document).ready(function() {
$("#brcode").change(function(){
var value = $("#brcode").val();
$.ajax({
url: '<?php echo site_url("main/get_product"); ?>',
type: 'POST',
data: {'barcode': $('#brcode option:selected').val() },
success: function(data) {
//console.log(data);
alert(data);
}
})
});
});
You are going wrong in this section as you are using dataType: 'json', Your ajax should return a json object.
PHP Tag won't work in js file, so you should put your ajax request either in footer of the page or hardcode your url. For example : url:"http://localhost/retail/main/get_product"
Also i think let value = $("#brcode").val(); should be var value = $("#brcode").val();
So your controller code should be
public function get_product()
{
$data = array();
if (!$this->input->is_ajax_request()) {
exit('No direct script access allowed');
}
$barcode = $_POST['barcode'];
$data['result'] = $this->Item_model->get_product_using_barcode($barcode);
echo json_encode(array("posted_data"=>$_POST,"database_data"=>$data['result']));
exit;
}
And in success of ajax use this
success: function(data) {
console.log("Posted data");
console.log(data.posted_data);
console.log("Database data");
console.log(data.database_data);
}

codeigniter send id and get database values without refresh

I need to send id and get database values according to the id without page refresh.and display data in my view,
here is my view,
<div>
Click on me
</div>
<script type="text/javascript">
function getSummary(id)
{
$.ajax({
type: "POST",
url: '<?php echo site_url('ajax_controller/getBranchDetails'); ?>',
cache:false,
data: "id=" + id, // appears as $_GET['id'] # ur backend side
success: function(data) {
// data is ur summary
$('#summary').html(data);
}
});
}
</script>
controller
public function getBranchDetails(){
$b_id = $this->input->post('branch_id');
$this->load->model('ajax_model');
$data['results'] = $this->ajax_model->getRecords($b_id);
//echo json_encode(array('data'=>$data));
}
I need to display $data['results'] in my view
model
<?php
class Ajax_model extends CI_model{
function getRecords($id)
{
$this->load->database();
$query = $this->db->query("SELECT * FROM companydetails WHERE id='$id'");
return $query->result();
}
}
Try this code ,It is working .
<script type="text/javascript">
function getSummary(id)
{
$.post("<?php echo site_url('ajax_controller/getBranchDetails'); ?>",
{branch_id:id},function(data,status){
$('#summary').html(data);
});
}
</script>
Note : Check whether you have included jquery.min.js . If not mention the below code in view part header
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
Try this instead:
<script type="text/javascript">
function getSummary(id) {
$.ajax({
type: 'POST',
url: "<?php echo site_url('ajax_controller/getBranchDetails'); ?>", // <-- properly quote this line
cache: false,
data: {branch_id: id}, // <-- provide the branch_id so it will be used as $_POST['branch_id']
dataType: 'JSON', // <-- add json datatype
success: function(data) {
// if you need to present this in a html table,
// likely, you need to use $.each() and build the markup using the json response
$('#summary').html(data);
}
});
}
</script>
Model: (Don't directly use variables inside the query string)
$sql = 'SELECT * FROM companydetails WHERE id = ?';
$query = $this->db->query($sql, array($id));
Controller:
public function getBranchDetails()
{
$b_id = $this->input->post('branch_id', true);
$this->load->model('ajax_model');
$data['results'] = $this->ajax_model->getRecords($b_id);
echo json_encode($data); // <-- uncomment
}

Get a single row from the database using AJAX in CodeIgniter?

I wonder how to get data from database using AJAX in CodeIgniter. Could you please check the code below to find out the reason of problem? Nothing happens when I click on the link from my view.
Here is my view:
<?php echo $faq_title; ?>
Here is my controller:
public function get_faq_data() {
$this->load->model("model_faq");
$title = $_POST['title'];
$data["results"] = $this->model_faq->did_get_faq_data($title);
echo json_encode($data["results"]);
}
Here is my model:
public function did_get_faq_data($title) {
$this->db->select('*');
$this->db->from('faq');
$this->db->where('faq_title', $title);
$query = $this->db->get('faq');
if ($query->num_rows() > 0) {
return $query->result();
} else {
return false;
}
}
Here is my JavaScript file:
$(".faq_title").click(function() {
var title = $(this).text();
$.ajax({
url: 'faq/get_faq_data',
data: ({ title: title }),
dataType: 'json',
type: 'post',
success: function(data) {
response = jQuery.parseJSON(data);
console.log(response);
}
});
});
Try this:
$(function(){ // start of doc ready.
$(".faq_title").click(function(e){
e.preventDefault(); // stops the jump when an anchor clicked.
var title = $(this).text(); // anchors do have text not values.
$.ajax({
url: 'faq/get_faq_data',
data: {'title': title}, // change this to send js object
type: "post",
success: function(data){
//document.write(data); just do not use document.write
console.log(data);
}
});
});
}); // end of doc ready
The issue as i see is this var title = $(this).val(); as your selector $(".faq_title") is an anchor and anchors have text not values. So i suggested you to use .text() instead of .val().
The way I see it, you aren't using the anchor tag for its intended purpose, so perhaps just use a <p> tag or something. Ideally, you should use an id integer instead of a title to identify a row in your database.
View:
<p class="faq_title"><?php echo $faq_title; ?></p>
If you had an id integer, you could use a $_GET request an receive the id as the lone parameter of the get_faq_data() method.
Controller:
public function faqByTitle(): void
{
if (!$this->input->is_ajax_request()) {
show_404();
}
$title = $this->input->post('title');
if ($title === null) {
show_404();
}
$this->load->model('model_faq', 'FAQModel');
echo json_encode($this->FAQModel->getOne($title));
}
FAQ Model:
public function getOne(string $title): ?object
{
return $this->db->get_where('faq', ['faq_title' => $title])->row();
}
JavaScript:
$(".faq_title").click(function() {
let title = $(this).text();
$.ajax({
url: 'faq/faqByTitle',
data: {title:title},
dataType: 'json',
type: 'post',
success: function(response) {
console.log(response);
}
});
});
None of these snippets have been tested.

Categories