I know this may be the [insertLongNumber]th time someone's ask this question, I did my research but I can't find another answer that fits my problem. So here it is.
I'm working on a dynamic dropdown with php and ajax, in codeigniter. I'm new to CI and I have a basic knowledge of Ajax.
What I have noticed so far is that in the console, it is not recognizing the value coming from the first dropdown, so i get departamento_id : undefined
This makes me thing problem comes from ajax script (i got it of the web)
My view, with the ajax code included
<?php
$this->load->helper('html');
?>
<html>
<head>
<title>Buscador</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#dpto-dropdown select').change(function () {
var selDpto = $(this).attr('value');
console.log(selDpto);
$.ajax({
url: "test/ajax_call",
async: false,
type: "POST",
data: "departamento_id="+selDpto,
dataType: "html",
success: function(data) {
$('#ciudad').html(data);
}
})
});
});
</script>
</head>
<?php echo form_open('test/buscar');?>
<?php
<div id='dpto-dropdown'><?php print form_dropdown('departamentos', $departamento) ?></div>
<div id="ciudad"><select><option value=''>-</option></select></div>
//rest of code...
This is my Controller code:
class Test extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('buscador_model');
}
function index()
{
$departamentos = $this->buscador_model->traerInfoDptos();
$precios = $this->buscador_model->traerPrecioHoteles();
foreach($departamentos as $departamento){
$dpto_final[$departamento->id] = $departamento->nom_departamento;
}
$info = array(
'departamento' => $dpto_final,
'precios' => $precios,
);
$this->load->view('buscador_view', $info);
}
function ajax_call()
{
//check to see people wont go directly
if (isset($_POST) && isset($_POST['departamento_id']))
{
$dpto = $_POST['departamento_id'];
$ciudad = $this->buscador_model->traerCiudadPorDpto($dpto);
foreach ($ciudad as $c)
{
$ciudadfinal[$c->cod_ciudad] = $c->nom_ciudad;
}
//dropdown
echo form_dropdown('Ciudades', $ciudadfinal);
}
else
{
redirect('index');
}
}
}
this is my model:
Class Buscador_model extends CI_Model
{
function traerInfoDptos()
{
$this->db->select('id, nom_departamento');
$this->db->from('departamento');
$query = $this->db->get();
if ($query->num_rows > 0)
{
return $query->result();
}
}
function traerCiudadPorDpto($dpto)
{
$query = $this->db->query("SELECT nom_ciudad, cod_ciudad FROM ciudad WHERE departamento_id = '{$dpto}'");
if ($query->num_rows > 0)
{
return $query->result();
}
}
}// end buscador model class
See this page: http://www.onerutter.com/open-source/jquery/jquery-tips-how-to-get-value-of-selected-option-in-select-box.html
You need to use .val() instead of .attr('value')
<script type="text/javascript">
$(document).ready(function () {
$('#dpto-dropdown select').change(function () {
var selDpto = $(this).val(); // <-- change this line
console.log(selDpto);
$.ajax({
url: "test/ajax_call",
async: false,
type: "POST",
data: "departamento_id="+selDpto,
dataType: "html",
success: function(data) {
$('#ciudad').html(data);
}
})
});
});
</script>
Related
This is my OpenCart code I don't know what the problem in this code is, but it cant return the value from php ajax page. I tried many ways it wont work so please help me for this problem .
Here is my ajax in OpenCart:
<script type="text/javascript">
$('.list-group-item').on('click', function () {
var href = $(this).attr("href");
var arr = href.split('path=');
var cat_id = arr[1];
//alert("hai");
$.ajax({
type: 'post',
url: 'index.php?route=ajax/ajaxcat/index',
data: format_data,
dataType: 'json',
success: function (json) {
if (json['success']) {
//$('#messages').html(json['success']);
alert(json['success']);
}
}
});
});
</script>
Here is my php code:
<?php
class ControllerAjaxAjaxcat extends Controller {
function index() {
$json['success'] = 'This is the returned results color_adjust.php';
$this->response->setOutput(json_encode($json));
}
}
?>
I don't know what is wrong with that code it cant return the value.
I want to display data when window load by ajax into codeigniter view div.
Here is my code please find below and please help me.
In my views.php
<script type='text/javascript' language='javascript'>
$(window).load(function()
{
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>colleges/index",
success: function(server_response
{
if(server_response == 'success')
{
$("#fillgrid").html(server_response);
}
else{
alert('Not OKay');
}
}
}); //$.ajax ends here
});
</script>
In my controller.php
public function index()
{
$list['college'] = $this->Colleges_model->get_all_college();
$this->load->view('header');
$this->load->view('Colleges/all_colleges', $list);
$this->load->view('footer');
}
In my model.php
public function get_all_college()
{
$this->db->order_by("id","DESC");
$query = $this->db->get("tbl_colleges");
return $query->result_array();
}
First of all set ajax success function as
success: function(server_response)
close bracket after success variable.
In your controller:
$list['college'] = $this->Colleges_model->get_all_college();
$html = $this->load->view('Colleges/all_colleges', $list, TRUE);
echo $html;
Controller code:
public function auto_search() {
$search_data = $this->input->post('search_data');
//print_r($search_data); die();
$query = $this->search_model->autocomplete($search_data);
print_r($query); die();
foreach ($query->result() as $row):
echo $row->uid ;
echo $row->name ;
endforeach;
}
The javascript:
<script type="text/javascript" src="js/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
function ajaxSearch() {
var input_data = $('#search_data').val();
$.ajax({
type: "POST",
url: "/search/auto_search",
data: {search_data:input_data},
success: function(data1) {
alert(data1);
if (data1.length > 0) {
$('#suggestions').show();
$('#autoSuggestionsList').addClass('auto_list');
$('#autoSuggestionsList').html(data1);
}
}
});
}
</script>
In controller when i print the search_data that is print_r($search_data); die(); i did not get any result.
I think ajax call is not get in to the controller Please provide solution for this
Moreover, when I echo out the query in controller that is print_r($query) ; I did not get any result. Also autosearch is not working. Please provide solution for this.
I think it is ajaxSearch function not runing.
your try
public function auto_search()
{
$search_data = $this->input->post('search_data');
$query = $this->search_model->autocomplete($search_data);
if (!empty($query)) {
foreach ($query->result() as $row) {
echo $row->uid;
echo $row->name;
}
} else {
echo '';
}
}
<script type="text/javascript" src="js/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(function () {
function ajaxSearch() {
var input_data = $('#search_data').val();
$.ajax({
type: "POST",
url: "/search/auto_search",
data: {search_data: input_data},
success: function (data1) {
alert(data1);
if (data1.length > 0) {
$('#suggestions').show();
$('#autoSuggestionsList').addClass('auto_list');
$('#autoSuggestionsList').html(data1);
}
}
});
}
// start ajaxSearch
ajaxSearch();
});
</script>
Thank you
You need to pass all ur data into array and then convert it into json_encode for more referrence about encoding -> http://php.net/manual/en/function.json-encode.php..
here is sample code for you.
public function auto_search() {
$search_data = $this->input->post('search_data');
//print_r($search_data); die();
$query = $this->search_model->autocomplete($search_data);
//print_r($query); die(); <- you should replace the die.
$myArray = [];
foreach ($query->result() as $key => $row):
$myArray['keyname'] = $row->uid;
$myArray['keyname1'] = $row->name;
endforeach;
//data retrieves by jquery
echo json_encode($myArray);
}
In you jquery.
$.ajax({
type: "POST",
url: "/search/auto_search",
data: {search_data:input_data},
success: function(data1) {
console.log(data1);
console.log(data1.keyname);
console.log(data1.keyname1);
if (data1.length > 0) {
$('#suggestions').show();
$('#autoSuggestionsList').addClass('auto_list');
$('#autoSuggestionsList').html(data1);
}
}
});
try to look at you're browser console panel. and see the retrieved data in your function and also try to check if your ajax url is correct.
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
}
I am trying to integrate an AJAX search function but I am having trouble getting the Zend Framework portion right. I have the following Controller and Action.
class IndexController extends Zend_Controller_Action
{
public function indexSearchAction()
{
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
if ($this->getRequest()->isXmlHttpRequest()) {
if ($this->getRequest()->isPost()) {
$search = new Model_Index();
$this->_helper->json($search->indexSearch());
$this->view->indexSearch = $result;
}
} else {
//regular controller logic goes here
echo "regular controller";
}
}
Copy of my Ajax call is as follows:
$.ajax({
type: "POST",
url: "/index/index-search/format/json",
data: dataString,
dataType: "json",
cache: false,
success: function(html)
{
I just want the model to return a simple message to ensure that it is working up to this point. with that said, here is a copy of my function in the model:
public function indexSearch()
{
$testMessage = "this was returned via ajax";
return $testMessage;
}
Code that triggers the Ajax call:
$(document).ready(function(){
$(".search").keyup(function()
{
var searchbox = $(this).val();
var dataString = 'searchword='+ searchbox;
if(searchbox=='')
{
}
else
{
$.ajax({
type: "POST",
url: "/index/index-search/format/json",
data: dataString,
dataType: "json",
cache: false,
success: function(html)
{
$("#display").html(html).show();
}
});
}
return false;
});
});
I dont know what I am missing, this is my first attempt to getting AJAX calls to work in ZF2 and its not working out.
Any help would be greatly appreciated! cheers!
The issue was that I was returning html when I was expecting json... I've since changed this:
here is the controller action:
public function indexSearchAction()
{
$this->_helper->layout('homelayout')->disableLayout();
if ($this->getRequest()->isXmlHttpRequest()) {
if ($this->getRequest()->isPost()) {
$q=$_POST['searchword'];
$indexSearch = new Model_Index();
$result = $indexSearch ->indexSearch ($q);
$this->view->indexSearch = $result;
}
} else {
//regular controller logic goes here
}
}
jQuery Ajax handling code:
$(document).ready(function(){
$(".search").keyup(function() {
var searchbox = $(this).val();
var dataString = 'searchword='+ searchbox;
if(searchbox==''){
$("#display").hide();
} else
{
$.ajax({
type: "POST",
url: "/user/user-search/",
data: dataString,
cache: false,
success: function(html)
{ $("#display").html(html).show(); }
});
}return false;
});
});
jQuery(function($){
$("#searchbox").Watermark("Search");
});
Model_index function indexSearch() script:
public function indexSearch($q)
{
$select = $this->select()
->from($this)
->where('username LIKE ?', '%' . $q . '%');
$row = $this->fetchAll($select);
return $row;
}
Here is the input box element for users to search with:
<input type="text" class="rounded search" id="searchbox" /><br />
<div id="display">
</div>
view script (index-search.phtml) which displays the contents in the div:
<div class="display_box" align="left">
<ul class="index-list">
<?php echo $this->partialLoop('user/search-dropdown.phtml', $this->indexSearch);?>
</ul>
and last but not least, the view script that is mentioned in the partial loop above that iterates through the returns contents of the database and into a format that can be displayed within the dropdown. below is search-dropdown.phtml:
<li class="user-list-item" >
<div class="search-list-item-container" >
<?php
$validator = new Zend_Validate_File_Exists();
$validator->addDirectory('users/');
if ($validator->isValid('/' . $this->username . '/' . $this->username . '.jpg')) { ?>
<div class="search-list-item-picture">
<img class='search-pic' src="..\users\<?=$this->username ?>\<?=$this->username ?>.jpg?t=<?=time(); ?>">
</div>
<?php } else { ?>
<div class="search-list-item-picture">
<img class='search-pic' src="..\skins\blues\images\f1.png">
</div>
<?php }?>
<div class="search-list-item-name">
<?php echo $this->username; ?>
</div>
</div>
The end result is as follows:
thanks to everyone who assisted here! MUCH APPRECIATED
Most likely it is because of this line
$this->_helper->viewRenderer->setNoRender(true);
Followed by your attempt to use a view with this line
$this->view->indexSearch = $result;
If you're going to turn your views off, then you'll need to echo out your content. So something like echo $result;
On top of that, your ajax function is expecting JSON data to be returned, but you're actually returning plain text/html. If you know that you're ultimately going to be returning/echoing json, then during your testing, you can simply comment out the line dataType: "json", until you are done with your initial testing, and then add it back. If you are not going to be using json at all, simply remove that line.
See this simple JSFiddle example