I have done to make control autocomplete, but I have a problem to post data with jquery.
<input type="text" id="matakuliah" class="med" name="matakuliah">
<script type="text/javascript">
$(this).ready( function() {
$("#matakuliah").autocomplete({
minLength: 1,
source:
function(req, add){
$.ajax({
url: "<?php echo site_url('bahanAjar/lookup'); ?>",
dataType: 'json',
type: 'POST',
data:req,
success:
function(data){
if(data.response =="true"){
add(data.message);
}
},
});
},
});
});
</script>
on my controller
function lookup(){
// process posted form data (the requested items like province)
$keyword = $this->input->post('term');
$data['response'] = 'false'; //Set default response
$query = $this->matakuliah_model->lookup($keyword); //Search DB
if( ! empty($query) )
{
$data['response'] = 'true'; //Set response
$data['message'] = array(); //Create array
foreach( $query as $row )
{
$data['message'][] = array(
'id_matakuliah'=>$row->id,
'value' => $row->matakuliah,
''
); //Add a row to array
}
}
if('IS_AJAX')
{
echo json_encode($data); //echo json string if ajax request
}
else
{
$this->load->view('admin/bahan_ajar/form_manage_file_view', $data); //Load html view of search results
}
}
The code work it well, but I want to add parameter to call database.
$query = $this->matakuliah_model->lookup($keyword, $id_matakuliah);
like this. how I can get
$this->input-<post('id_matakuliah')
from jquery before.;
and I have another textbox for fill value of autocomplete from textbox matakuliah.
`<input type="hidden" id="matakuliah_post" class="med" name="matakuliah_post">`
When I'm use autocomplete textbox automatic fill another textbox, please help me.
In this case req will contain {term:"your search term"}. Your can extend this javascript object to pass extra data. If you want to post id_matakuliah, you can assign its value like following before $.ajax call:
req.id_matakuliah = "Whatever you want to send";
Related
I'm trying to send a username from the view to the controller through Ajax like this :
$('#exampleFormControlSelect1').change(function(){
var username =$('#exampleFormControlSelect1').val();
$.ajax({
type: 'POST',
dataType: "json",
url: "Panier/loadPanier",
data: {username: username},
success: function(result){
$("#tbodyid").empty();
var data1 = JSON.parse(result);
console.log(data1) ;
},
});
});
and I try to use the sent value to do some work:
public function loadPanier()
{
$res = [];
$username = $this->input->post('username');
$panier_data = $this->model_panier->getPanierData($username);
foreach ($panier_data as $k => $v) {
$idPiece = $v['idPiece'];
$qte = $v['quantity'];
$piece_data = (array)$this->model_catalogue->getDetail($idPiece);
$price = (int)$piece_data['Unit Price'];
$montant = $qte * $price;
array_push($res, array(
'idPiece' => $idPiece,
'Description' => $piece_data['Description'],
'qte' => $qte,
'prix HT' => round($piece_data['Unit Price'], 3),
'montant' => $montant
));
}
return $res;
}
In my URL I'm getting this error :
Invalid argument supplied for foreach()
but here's what I'm noticing by doing var_dump($username):
C:\wamp64\www\PortalDealer\application\controllers\Panier.php:66:null
So my data is not passing!
Can you help me with this?
EDIT
showcase the result of this part of the code :
var_dump($_REQUEST);
$res = [];
$username = $this->input->post('username');
var_dump($username);
$panier_data = $this->model_panier->getPanierData($username);
var_dump($panier_data);
The below code should send your data to Panier/loadPanier/.
$('#exampleFormControlSelect1').change(function(){
var val1 =$('#exampleFormControlSelect1').val();
$.ajax({
method: "POST",
url: "Panier/loadPanier/",
data: { username: val1}
}).done(function( result ) {
$("#tbodyid").empty();
var data1 = JSON.parse(result);
console.log(data1) ;
});
});
You were seeing null every time you did var_dump() because you were trying to load the page independently. The page will only give you the POST value if you are going to the page thru the form, in this case, the form is javascript. When you load a page with POST method in javascript, the response is sent to the same page with ajax so you can work with your code without having to refresh the page.
Also: You cannot return data to javascript. You have to print it out to client side so that your javascript's JSON parser can read it. Therefore, instead of return $res; :
echo json_encode($res);
I am using echo json_encode($data); to send an array back to jquery ajax. I want to get data from json and retrieve it on input text and I got this error like: The URI you submitted has disallowed characters.
I don't know on how to pass data in model. Btw, I'm using codeigniter.
Once I click the edit button, a modal will appear. Please, help me guys!!
Button
<a onclick="edit_content_by_id('.$row->post_id.')" title="Edit"><span class="ti-pencil"></span>
Model
public function GetContentById($id) {
$query = $this->db->select('*')->from('cms_posts_tbl cpt')->
join('cms_contents_tbl cct', 'cct.post_id = cpt.post_id')->
join('cms_category_tbl ccat', 'ccat.post_category_id = cpt.post_category')->
where('post_id', $id)->get();
foreach($query as $row) {
$data = $row;
}
echo json_encode($data);
}
jQuery Ajax
function edit_content_by_id(id) {
var data = { content_id : id };
$.ajax({
type: 'POST', url: 'http://localhost:81/ci_sample/model/GetContentById('+ id +')',
data: data, dataType: 'json',
cache: false,
success:function(data) {
$('#modal_content').modal('show');
$('#modal_content').find($('post_title')).val(data.post_title);
}
});
}
header('Access-Control-Allow-Origin:*');
Go to config.php and configure this variable.
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-#\=';
I want to click checkbox to show the data what i want fetch through ajax call, but it is showing database all data automatically show whats the problem please find out and help me (just i want ajax call)
Controller
//This is my controller
public function laptops()
{
$this->load->model('feature_model');
$filter = array(
'price' => $this->input->get('price'),
'name' =>$this->input->get('name')
);
$data['laptop'] = $this->feature_model->laptops_m($filter);
//echo json_encode($this->feature_model->laptops_m($filter));
$this->load->view('feature/checkbox',$data);
}
//This is my model
function laptops_m($filter = null){
$this->db->select('*')
->from('mobile_phones');
// $query = $this->db->get('laptop_notebook')->result();
// return $query;
if($filter['name']){
$this->db->where('name', $filter['name']);
}
if($filter['price']){
$this->db->where('price', $filter['price']);
}
$query = $this->db->get()->result();
return $query;
}
//This is my view
<input type="checkbox" name="name" value="acer">
<input type="checkbox" name="name" value="lenovo">
<input type="checkbox" name="price" value="1000">
<table>
<tbody>
<?php foreach ($laptop as $laptops_all) { ?>
<tr>
<td><p>Laptop <?php echo $laptops_all->name ?> </p>
</td>
</tr>
<?php } ?>
</tbody>
</table>
Ajax script:
// This is the ajax script function
<script>
$("input[checkbox]").change(function(){
$.ajax({
url: localhost/ci35/feature/laptops,
dataType: 'json',
success: function(data){
$.each(data, function(index, element) {
$("tbody").empty();
$("tbody").append("<tr><td>"+
"Laptop "+element.brand+""+
"</td></tr>");
});
}
});
You try to get data to display from GET array here:
$filter = array(
'price' => $this->input->get('price'),
'name' =>$this->input->get('name')
);
But your GET array is empty because of you don't send any data with your json request. From jQuery documentation:
data
Type: PlainObject or String or Array
Data to be sent to the
server. It is converted to a query string, if not already a string.
It's appended to the url for GET-requests. See processData option to
prevent this automatic processing. Object must be Key/Value pairs. If
value is an Array, jQuery serializes multiple values with same key
based on the value of the traditional setting (described below).
So you should iterate over checked checkboxes and add it's values to array. Then send this array via data property of ajax request.
Try this..add class="searchType" to html checkbox element, then in jquery
$('.searchType').click(function() {
alert($(this).attr('id')); //-->this will alert id of checked checkbox.
if(this.checked){
$.ajax({
url: localhost/ci35/feature/laptops,
dataType: 'json',
success: function(data){
$.each(data, function(index, element) {
$("tbody").empty();
$("tbody").append("<tr><td>"+
"Laptop "+element.brand+""+
"</td></tr>");
});
}
});
}
});
as you are printing the data through success ajax call, no need to use foreach again in view.
Also in your controller, you have to print json data.
public function laptops()
{
$this->load->model('feature_model');
$filter = array(
'price' => $this->input->get('price'),
'name' =>$this->input->get('name')
);
$data['laptop'] = $this->feature_model->laptops_m($filter);
echo json_encode( $data['laptop'] );
// $this->load->view('feature/checkbox',$data);
}
I'm creating my project using OOP. I need to pass all the values inserted in the database in the form of array. And it's a multidimensional array. SO when I pass now via ajax as a 'text' datatype it displays array in console.log(). But I'm unsure if this is the correct way and how to display the value in a table form in jquery.
Below are the functions where the values returned to the object in another page.
public function selectType()
{
$sql="SELECT * FROM car_type";
$stmt =connection::$pdo->prepare($sql);
$stmt->execute();
$carType=array();
while($row = $stmt->fetch())
{
array_push($carType,$row['car_type']);
}
return $carType;
}
public function selectMaker()
{
$sql="SELECT * FROM car_maker";
$stmt =connection::$pdo->prepare($sql);
$stmt->execute();
$carMaker=array();
while($row = $stmt->fetch())
{
array_push($carMaker,$row['car_maker']);
}
return $carMaker;
}
ANd this is how I'm fetching the values to be passed to another page to be displayed to the user.
$setting = new setting($car_type,$car_maker,$rental_type,$rental);
//$setting->connection;
$setting->addCarType();
$setting->addCarMaker();
$setting->addRentalBy();
$carType=$setting->selectType();
$carMaker=$setting->selectMaker();
$json=array();
array_push($json,array("type"=>$carType,"maker"=>$carMaker));
echo $json;
Finally ajax to fetch and display data
$("#submit").on("click",function()
{
$("#set_setting").submit(function(){
data = $(this).serialize()
$.ajax({
type: "POST",
dataType: "html",
url: "submit_setting.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
//hide the form
$("#set_setting").slideUp("slow");
//show the result
for (i = 0; i < data.length; i++) {
console.log(data);//outputs array
$(".the-return").html(data);
}
}
});
return false;
});
});
You need to pass array as JSON and post it using name value pairs.
var data = {a:{'foo':'bar'},b:{'this':'that'}};
$.ajax({ url : '/',
type : 'POST',
data : {'data':JSON.stringify(data)},
success : function(){ }
});
And in backend (PHP):
$data = json_decode($_POST['data']);
print_r($data);
// Result:
// Array( "a" => Array("foo"=> "bar"), "b" => Array("that" => "this"))
Can someone tell me what I'am doing wrong here, console.log() returns me an empty string instead of an array ?
I want to update the second selectbox once onChange is triggered on first selectbox but I can't retrieve the data. When I'am doing a var_dump($results) it successfully shows an array of items, but return $results returns me an empty string.
Here how it looks like:
a javascript:
function _getNestedSelectOptions(activeComponent){
$.ajax({
type: "POST",
url: "/backend/categories/get_nested_options/" + activeComponent
}).done(function(html){
console.log(html);
});
}
And this is a php code controllers/backend/categories.php:
public function get_nested_options($cid = FALSE){
if($cid == FALSE)
$cid = $this->activeComponent;
$categoriesResult = $this->categories_model->get_categories_tree_by_com($cid);
$categoriesDropdownOptions = array();
$this->categories_model->get_nested_options($categoriesDropdownOptions, $categoriesResult);
var_dump($categoriesDropdownOptions); // <-- THIS WORKS AND SHOWS AN ARRAY OF ITEMS
//return $categoriesDropdownOptions; // <-- THIS DOES NOT WORKING
}
here is an output on console.log():
array (size=3)
7 => string 'Administrators' ->(length=14)
8 => string 'Managers' ->(length=8)
9 => string 'Users' ->(length=5)
You can try to get json in js, use
In controller:
public function getNestedOptions($cid = FALSE){
if($cid == FALSE)
$cid = $this->activeComponent;
$categoriesResult = $this->categories_model->get_categories_tree_by_com($cid);
$categoriesDropdownOptions = array();
$this->categories_model->getNestedOptions($categoriesDropdownOptions, categoriesResult);
echo json_encode($categoriesDropdownOptions); exit;
}
$.ajax({
dataType: "json",
type: "POST",
url: "/backend/categories/get_nested_options/" + activeComponent
data: data
}).done(function(data){
response = jQuery.parseJSON(data);
console.log(response);
});
you will get data in json format.
I managed to work it out by helps of #KA_lin (jQuery.parseJSON() didn't work, idk why) and #RameshMhetre, so thank you guys for your helps.
This is an AJAX in categories.js:
function _getNestedSelectOptions(activeComponent, targetName){
// Url in proper JSON format with datas
var url = "/backend/categories/get_nested_options/";
// Target selectbox to apply modifications on it
var ddb = $(targetName);
// Save first dummy/null option
var top = ddb.find('option:first');
$.ajax({
type: 'POST',
url: url + activeComponent,
dataType: 'json',
beforeSend: function(){
// Disable selectbox
ddb.prop('disabled', true);
},
success: function(data){
// Insert saved first dummy/null option
ddb.empty().append(top);
$.each(data, function (index, value) {
// Append html data to target dropdown element
ddb.append('<option val="'+ value.id +'">'+ value.title +'</option>');
});
// Re-enable selectbox
ddb.prop('disabled', false);
}
});
}
controllers/backend/categories.php:
public function get_nested_options($cid = FALSE){
if($cid == FALSE)
$cid = $this->activeComponent;
// Get an array of properly constructed parents and childs
$categoriesResult = $this->categories_model->get_categories_tree_by_com($cid);
// Prepare an array of dropdown option values (without keys)
$categoriesDropdownOptions = array();
// Fill in an array with appropriate values for use with form_dropdown($array)
$this->categories_model->get_nested_options($categoriesDropdownOptions, $categoriesResult);
// Prepare an array for JSON output (with keys)
$results = array();
// Modify a raw array with specific keys for use in JSON
foreach($categoriesDropdownOptions as $id => $title){
$results[] = array(
'id' => $id,
'title' => $title
);
}
// Set a proper page content and output JSON results
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($results));
}
And the views/backend/categories/form.php:
<fieldset>
<legend>Attributes</legend>
<label class="control-label" for="formCatCid">
Component name:
<div class="controls">
<?php
$componentDropdownExtra = 'class="span12" onChange="categories.getNestedSelectOptions(this.value, formCatPid);"';
echo form_dropdown('formCatCid', $componentDropdownOptions, set_value('formCatCid', $formCatCid), $componentDropdownExtra);
?>
</div>
</label>
<label class="control-label" for="formCatPid">
Category parent:
<div class="controls">
<?php
$categoriesDropdownExtra = 'class="span12"';
echo form_dropdown('formCatPid', $categoriesDropdownOptions, set_value('formCatPid', $formCatPid), $categoriesDropdownExtra);
?>
</div>
</label>
</fieldset>