Select2 load data from database - CodeIgniter - php

I try to load database data in my Select2 input. (Im working on CI)
Here's my code from the controller : transforms array in echo json
class Ajax extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->model('client');
}
public function returnClientsAjax(){
echo json_encode($this->client->getClients());
}
}
Model : returning an array of results
function getClients(){
return $this->db->query("SELECT idclient AS id, CONCAT(societe,' [', nom,']') as text FROM du_client WHERE (societe != '' AND nom != '') AND evo2012 >=2 AND type_client != 'Particulier' AND statut_client = 'Demandeur' AND idclient = 6141;")->result_array();
}
My Select2 :
$("#sel_clients").select2({
placeholder: "Search for an Item",
ajax: {
dataType: "json",
url: "http://commexpert.dev.local/ajax/returnclientsajax",
results: function (data) {
return {results: data};
}
}
});
The input still empty so, don't know what to do.
Thnaks :D

I think something is missing on your data results method. Here is my code from working ajax select2 component:
results: function (data) {
var results = [];
var id1 = data.id;
var name = data.text;
$.each(data.data, function(index, item){
results.push({
id: item[id1],
text: item[name].trim()+' : '+ item[id1]
});
});
return {results: results};
}
also, I'm having somewhat diff data call also:
data: function (term) {
try {
mirko = $(this).closest('[rendered]').find( "input[fparamname$=" + $(this).attr('flookupfiltref') + "]" ).val();
if (mirko.indexOf(' : ') >=0 ) { // pocetna vrijednost
mirko = mirko.split(' : ')[1].trim();
}
} catch(e){
mirko = '';
}
return {
sp_name: $(this).attr('objectname'),
fl_name: $(this).attr('fparamname'),
node_id: $(this).attr('node_id'),
bound: mirko,
q: term,
};
},
I'm having somekind of manipulation before sending or returning q to server,, but I hope that can help you for your service :)
hth, k

Related

JSON.parse: unexpected end of data at line 1 column 1 of the JSON data laravel

Hello I have a problem when I wanna show my query result at my text fields
I tried to don't use JSON.parse but when I do it this doesn't show anything then I use an alert and show my undefined
this is the code using an alert to show the result
$(document).ready(function(){
$('#zip_code').blur(function()
{
var zip_code=$(this).val();
if(zip_code != '')
{
var _token = $('input[name="_token"]').val();
$.ajax({
url:"{{route('complete.zip')}}",
method:"POST",
data:{zip_code:zip_code,_token:_token},
success:function(data)
{
alert(data.value1);
}
});
}
});
});
when I try to convert the JSON in the console show me it
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
this is the code
$(document).ready(function(){
$('#zip_code').blur(function()
{
var zip_code=$(this).val();
if(zip_code != '')
{
var _token = $('input[name="_token"]').val();
$.ajax({
url:"{{route('complete.zip')}}",
method:"POST",
data:{zip_code:zip_code,_token:_token},
success:function(data)
{
var result = JSON.parse(data);
$('#estado').val(result.value1);
$('#municipio').val(result.value2);
}
});
}
});
});
the PHP files is the next
use DB;
class ClientBusinessController extends Controller
{
public function index()
{
return view("new_client.register_business");
}
public function receiveValueZip(Request $request)
{
if(!empty($request->get('zip_code')))
{
$result=DB::table('direccion')
->select('Calle1','Calle2')
->where('Id_Direccion','=',6)
->get();
foreach($result as $r)
{
json_encode(array("value1"=>$r->Calle1,"value2"=>$r->Calle2));
}
}
}
Does someone know how to resolve this problem? thanks so much
If you call json_encode multiple times you end up with invalid JSON. You should instead construct your array structure fully and call json_encode only once. However I recommend using response()->json and letting Laravel handle the JSON serialization:
public function index()
{
return view("new_client.register_business");
}
public function receiveValueZip(Request $request)
{
if(!empty($request->get('zip_code')))
{
$result=DB::table('direccion')
->select('Calle1','Calle2')
->where('Id_Direccion','=',6)
->get();
return response()->json(
$result->map(function ($row) {
return array("value1"=>$r->Calle1,"value2"=>$r->Calle2);
});
);
}
}

How to update MySQL database after view's value change

I got this sports website project written in Codeigniter/AngularJs and I'm stucked at the communication between view/controller/model.
There is this function that updates user points in view, then I should use this dataSavingHttp service to update the database also, but I'm really confused about its functionality
The View Angularjs controller
$scope.buy_salary_cap = function() {
$scope.remainSalary = parseInt($scope.contestDetails.salary_cap/10) + parseInt($scope.remainSalary);
$rootScope.profile_data.points_balance = parseInt($rootScope.profile_data.points_balance) + parseInt(1);
dataSavingHttp({
url: site_url+"lineup/update_user_points_balance",
data: {},
}).success(function (response) {
$scope.content = response.data.points_balance;
}).error(function (error) {
$scope.content = "Erro!";
});
$scope.isDisabled = true;
}
The Codeigniter controller
private function update_user_points_balance()
{
return $this->Lineup_model->update_user_points_balance();
}
The Model function
public function update_user_points_balance()
{
$condition = array('user_id' => $this->session->userdata('user_id'));
$config['points_balance'] = $this->remain_balance;
$this->table_name = USER;
return $this->update($condition , $config);
}
Here is the dataSavingHttp code
vfantasy.factory('dataSavingHttp', function($http, $location) {
var wrapper = function(requestConfig) {
var options = angular.extend({
url: "",
method: "POST",
data : '',
dataType: "json",
},requestConfig);
var httpPromise = $http(options);
httpPromise.success(function(result, status, headers, config){
var l = window.location;
wrapper.lastApiCallConfig = config;
wrapper.lastApiCallUri = l.protocol + '//' + l.host + '' + config.url + '?' +
(function(params){
var pairs = [];
angular.forEach(params, function(val, key){
pairs.push(encodeURIComponent(key)+'='+encodeURIComponent(val));
});
return pairs.join('&')
})(config.params);
wrapper.lastApiCallResult = result;
})
return httpPromise;
};
return wrapper;
});
Maybe there is a simpler solution, but I'm really new in these languages. Thanks in advance.

Wordpress / Jquery ajax, get works post fails with jquery error

Hi all the following function will work and do exactly as I want it to but I want this to be a .post not a .get can anyone see a problem with the following? its pretty much straight from another answer on stack overflow and should work fine.
jQuery(document).ready(function() {
//This function adds a development.
jQuery('#add_dev').bind('submit', function(e) {
e.preventDefault();
var data = {
action: 'AjaxAddDev',
security: AjaxHandler.ajaxnonce,
name: jQuery('#dev_name').val(),
desc: jQuery('#dev_desc').val()
};
//alert(data['name']+data['desc']);
jQuery.get(
AjaxHandler.ajaxurl,
data,
function(response) {
// ERROR HANDLING
if (!response.success) {
// No data came back, maybe a security error
if (!response.data) {
//$('#my-answer').html('AJAX ERROR: no response');
alert("Problem adding Development");
} else {
//$('#my-answer').html(response.data.error);
alert(response.data);
}
} else {
//$('#my-answer').html(response.data);
alert("Problem adding Development");
}
}
);
});
});
The error I get when I set it to .post is:
l.send(n.hasContent && n.data || null), r = function (e, i) {
Which is line 2963 of an un-minified version of jquery
/*! jQuery v1.10.2 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license */
Can anyone point me in the right Direction?
Updated Code:
jQuery(document).ready(function() {
//This function adds a development.
jQuery('#add_dev').bind('submit', function(e) {
e.preventDefault();
var data = {
action: 'AjaxAddDev',
security: AjaxHandler.ajaxnonce,
name: jQuery('#dev_name').val(),
desc: jQuery('#dev_desc').val()
};
//alert(data['name']+data['desc']);
jQuery.ajax({
url: AjaxHandler.ajaxurl,
type: "POST",
data: data,
success:function(data) {
// This outputs the result of the ajax request
alert(data);
},
error: function(errorThrown){
alert(errorThrown['error']);
}
});
});
});
I am using firefox latest version,
I got the following returned as an errotThrowen['error']
function () {
if (l) {
var t = l.length;
(function i(t) {
x.each(t, function (t, n) {
var r = x.type(n);
"function" === r ? e.unique && p.has(n) || l.push(n) : n && n.length && "string" !== r && i(n)
})
})(arguments), n ? o = l.length : r && (s = t, c(r))
}
return this
}
if you want to ajax on change
$("#yourid").change(function () {
var p = {
postfieldname: value,
postfieldname: value,
postfieldname: value,
postfieldname: value,
postfieldname: value,
postfieldname: value,
postfieldname: value,
}
$.ajax({
url: "library/test.php",
type: "POST",
data: p,
success: function (e) {
var t = jQuery.parseJSON(e);
$("#id").val(t['a']);
}
})
})
and on test.php
$array = array("a" => "test", "b" => "array");
$encode = json_encode($aray);
echo $encode;
OK this was kind of an odd one,
To get it working I simply had to add the following as the post URL.
url: AjaxHandler.ajaxurl+"&security="+AjaxHandler.ajaxnonce,
If I left the security out of the url it would fail, I don't know why but this had me going around in circles for hours.

Unable to select a result from the select2 search results

I am using the select2 for on of my search boxes. I'm getting the results from my URL but I'm not able to select an option from it. I want to use the 'product.productName' as the text to be shown after selection. Is there anything that I have missed out or any mistake that I have made. I have included select2.css and select2.min.js,jquery.js
function dataFormatResult(product) {
var markup = "<table class='product-result'><tr>";
markup += "<td class='product-info'><div class='product-title'>" + product.productName + "</div>";
if (product.manufacturer !== undefined) {
markup += "<div class='product-synopsis'>" + product.manufacturer + "</div>";
}
else if (product.productOptions !== undefined) {
markup += "<div class='product-synopsis'>" + product.productOptions + "</div>";
}
markup += "</td></tr></table>";
return markup;
}
function dataFormatSelection(product) {
return product.productName;
}
$(document).ready(function() {
$("#e7").select2({
placeholder: "Search for a product",
minimumInputLength: 2,
ajax: {
url: myURL,
dataType: 'json',
data: function(term,page) {
return {
productname: term
};
},
results: function(data,page) {
return {results: data.result_object};
}
},
formatResult: dataFormatResult,
formatSelection: dataFormatSelection,
dropdownCssClass: "bigdrop",
escapeMarkup: function(m) {
return m;
}
});
});
This is my resut_object
"result_object":[{"productName":"samsung galaxy s3","manufacturer":"Samsung","productOptions":"Color;Memory","productOptiondesc":"Silver;32GB"},{"productName":"samsung salaxy s3","manufacturer":"Samsung","productOptions":"Color;Memory","productOptiondesc":"Graphite;32GB"},{"productName":"samsung galaxy s3","manufacturer":"Samsung","productOptions":"Color;Memory","productOptiondesc":"Silver;16GB"}]
You are missing id attribute for result data. if it has not, it makes option "unselectable".
Example:
$('#e7').select2({
id: function(e) { return e.productName; },
});
Since I was using AJAX, what worked for me was returning something as the ID on processResults:
$(field).select2({
ajax: {
// [..] ajax params here
processResults: function(data) {
return {
results: $.map(data, function(item) {
return {
// proccessResults NEEDS the attribute id here
id: item.code,
// [...] other attributes here
foo: item.bar,
}
})
}
},
},
});
The id param can be a string related to the object property name, and must be in the root of the object. Text inside data object.
var fruits = [{code: 222, fruit: 'grape', color:'purple', price: 2.2},
{code: 234,fruit: 'banana', color:'yellow', price: 1.9} ];
$(yourfield).select2(
{
id: 'code',
data: { results: fruits, text: 'fruit' }
}
);
I have faced the same issue,other solution for this issue is:-
In your response object(In above response Product details object) must have an "id" as key and value for that.
Example:- Your above given response object must be like this
{"id":"1","productName":"samsung galaxy s3","manufacturer":"Samsung","productOptions":"Color;Memory","productOptiondesc":"Silver;32GB"}
SO you don't need this
id: function(object){return object.key;}

Zend Ajax can't delete

I have a table named state with columns state_id, state_name. Currently I can add new states and edit them, but I can't delete states. What might be wrong with my code?
{title:"Actions",template:'<a class="left" onclick="javascript:openEditStatePopup(this);">Edit</a>' +
'<a class="right" onclick="javascript:deleteState(this);">Delete</a>'
,width:120,sortable:false}
This snippet is the view code, and when I click the link, it executes the following JavaScript:
function deleteState(element)
{
var countryDetail = {};
var GriddataItem = $("#state_grid").data("kendoGrid").dataItem($(element).closest("tr"));
countryDetail.state_id =GriddataItem.state_id;
countryDetail.state_name = GriddataItem.state_name;
// alert(countryDetail.state_id);
$.ajax({
url:"<?= $this->baseUrl('admin/state/delete')?>",
data: {state_id : countryDetail.state_id},
dataType: "json",
type: "POST",
success: function(){
alert('success');
},
failure:function(){
alert('not working');
}
});
}
When I echo alert(countryDetail.state_id) before the $.ajax call, I can get the correct state id.
My delete controller is:
public function deleteAction()
{
$state = $this->_request->_getPost('state_id');
$stateMapper = new Application_Model_Mapper_StateMapper();
$stateMapper->delete($state);
}
and the model mapper for deleting is:
public function delete(Application_Model_State $state)
{
$data = $state->toArray();
$adapter = $this->getDbTable()->getAdapter()->delete(array('state_id=?'=>$data['state_id']));
}
Hi you need to write deleteAction as following
public function deleteAction()
{
$state = $this->_getParam('state_id');
$stateMapper = new Application_Model_Mapper_StateMapper();
$stateId = $stateMapper->delete($state);
$this->_helper->json(array('success'=>1));
}
in your controller action deleteAction() you are getting POST param 'state_id'
$state = $this->_request->_getPost('state_id');
$stateMapper = new Application_Model_Mapper_StateMapper();
$stateMapper->delete($state);
and you are passing that $state in the $stateMapper->delete($state); function
in your model class function public function delete(Application_Model_State $state) definition you are passing State model object not and state id, so you should change this to
public function delete($state_id)
{
$adapter = $this->getDbTable()->getAdapter()->delete(array('state_id=?'=>$state_id));
}
Then it should work...
Another thing I have not seen
failure:function(){
alert('not working');
}
Rather it is
error:function(){
alert('not working');
}

Categories