jQuery UI Autocomplete and CodeIgniter - php

I am trying to implement a simple autocomplete script using jQuery UI and CodeIgniter 2 but my model keeps telling me there is an undefined variable so I dont know if my setup is right.
My view
$(function() {
$("#txtUserSuburb").autocomplete({
source: function(request, response){
$.ajax({
url: "autocomplete/suggestions",
data: {
term: $("#txtUserSuburb").val()
},
dataType: "json",
type: "POST",
success: function(data){
response(data);
}
});
},
minLength: 2
});
});
My controller
function suggestions(){
$this->load->model('autocomplete_model');
$term = $this->input->post('term', TRUE);
$rows = $this->autocomplete_model->getAutocomplete($term);
echo json_encode($rows);
}
My Model
function getAutocomplete() {
$this->db->like('postcode', $term, 'after');
$query = $this->db->get('tbl_postcode');
$keywords = array();
foreach($query->result() as $row){
array_push($keywords, $row->postcode);
}
return $keywords;
}
There arent any errors except it doesn't seem to be passing the $term variable to the model.

Yeah, I think you need getAutocomplete() to have a param "$term":
function getAutocomplete($term) {

change post value in Ajax
$(function() {
$("#txtUserSuburb").autocomplete({
source: function(request, response){
$.ajax({
url: "autocomplete/suggestions",
data: {
term: request.term //change post value
},
dataType: "json",
type: "POST",
success: function(data){
response(data);
}
});
},
minLength: 2
});
});
set page header as JSON in a controller
function suggestions(){
$this->load->model('autocomplete_model');
$term = $this->input->post('term', TRUE);
$rows = $this->autocomplete_model->getAutocomplete($term);
$this->output
->set_content_type('application/json')
->set_output(json_encode($rows));
}

Related

Function doesn't echo variable

I'm currently learning basic php and jQuery.
I've created script which is getting url on mouse hover, and sends it to php.
The problem is, if I want to pass this data to php variable, it seems like it doesn't work because it echos only "'This is our JS Variable :'"
Script:
<script type="text/javascript">
var hrefValue;
jQuery(document).ready(function($) {
$('#bio-box').find('a').mouseover(function() {
hrefValue = ($(this).attr('href'))
console.log(hrefValue)
});
$.ajax({
url: 'jakubtrz-portfolio/wp-admin/admin-ajax.php',
data: {
'action': 'php_tutorial',
'php_test': hrefValue
},
success: function(data){
console.log("happy")
}
});
});
</script>
functions.php:
function our_tutorial(){
if(isset($_REQUEST)){
$testing = $_REQUEST['php_test'];
echo 'This is our JS Variable :'.$testing;
global $wpdb;
$wpdb->insert(
$wpdb->prefix.'lms_enroll',
[
'ID' => $testing
]
);
}
die();
}
add_action('wp_ajax_php_tutorial', 'our_tutorial');
Solution:
$.ajax({
url: 'jakubtrz-portfolio/wp-admin/admin-ajax.php',
type: 'post', // define type
data: {
'action': 'php_tutorial',
'php_test': hrefValue
},
success: function(data){
console.log("happy")
}
});
functions.php:
// post to et value
$test = $_POST['php_test'];
The problem was - when page loaded, value of a variable was empty. So solution is to call ajax in the moment of mouseover.
var hrefValue;
jQuery(document).ready(function($) {
$('#bio-box').find('a').mouseover(function() {
hrefValue = ($(this).attr('href'))
//console.log(hrefValue)
$.ajax({
url: frontendajax.ajaxurl,
type: 'POST',
data: {
'action': 'image',
'php_test': hrefValue
},
success: function(data){
$('#featured-image').html(data);
//console.log(data);
}
});
});
});

Json unable to pass array to php

As the title says, I failed to pass the data array via json ajax to php. I am using codeigniter, what did I do wrong? here is the jQuery code:
function load_page_data1(){
var data = [];
data['val'] = "solid_t1";
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: data,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
}
Here is the php code:
function getdata(){
$parameter = '';
if(isset($_POST))
{
if(isset($_POST['val']))
{
$parameter = $_POST['val'];
} else
{
echo "failed!";
}
}
$this->load->model('Chart');
$this->load->helper('url');
$data1 = $this->Chart->getdata_solid($parameter);
echo json_encode($data1);
}
Final:
Guys, it turn out that the values did passed from jQuery to php, the problem is that I stupidly call the same php function twice within the javascript function, then the second time calling without posting the 'val', so that the php function error and stop.
Thank you all for your answers, at least I learn the different ways to passing data by using jQuery.
Don't make a array if it's not a array just make a object
var data = {};
data.val = "solid_t1";
// equivalent to
data ={val:"solid_t1"};
// equivalent to
data['val'] ="solid_t1";
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: data,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
Update 1: if you need to send array you need to make a proper array object like below
Example :
var data=[];
item ={val:'value'};
data.push(item);
var new_data = JSON.stringify(data);
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: new_data,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
For Debugging :
May be problem with your server side code .so for the testing purpose comment all the line in function just do this echo json_encode($_POST); and in your ajax success function just add console.log(output); and let me know the result.
create one json object
jsonObj = [];
create array list as per your need
item = {}
item ["val"] = "solid_t1";
push the array list in to the json.
jsonObj.push(item);
Please have a try like this. It is working in my case.
Your full code will be like
function load_page_data1(){
jsonObj = [];
item = {}
item ["val"] = "solid_t1";
jsonObj.push(item);
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: jsonObj,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
}
The another way to use this is given below.
function load_page_data1(){
var jsonObj = {};
jsonObj["val"] = "solid_t1";
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: jsonObj,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
}
Instead of var data = []; use var data = {}; to initialize your data. It should solve your problem.
Your data wasn't being passed as json, now it will.
Code will be:
function load_page_data1(){
var data = {};
data['val'] = "solid_t1";
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/welcome/getdata',
data: data,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
}
One more suggestion please use CI input library for post request in controller.
e.g.
$parameter = $this->input->post('val');

Json on input instead of autocomplet

$('#lev_nr').on('input', {
source: function(request, response) {
$.ajax({
url : 'pallavvikelse/jsonData',
dataType: "json",
data: {
name_startsWith: request.term,
type: 'lev_table',
row_num : 1
},
success: function(data) {
response($.map(data, function(item) {
var code = item.split("|");
return {
label: code[0],
value: code[0],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 1,
select: function(event, ui) {
var names = ui.item.data.split("|");
$('#lev_namn').val(names[1]);
var txt = $('#avta').val(names[2]);
if (txt.val() == "ja"){
$('#t').hide();
}
} }).trigger('input');
Can someone see why this does not work?
I am trying to change autocomplete function to on.input but I can't get it to work.
The code works perfectly when i change the first line to $('#leverantors_nr').autocomplete({
and when I remove .trigger('input')
$('#lev_nr').on('input', function() {
$.ajax({
url: 'pallavvikelse/jsonData',
data: {
name_startsWith: this.value,
type: 'country_table',
row_num: 1
},
dataType: 'json',
success: function(data) {
alert(data);
var names = data.split('|');
alert(names[0]);
}
});
});
I have managed to make it work this far, but when i try to alert(names[0]) i get nothing when alert(data) i get resault.. The data i get loocks like this: 5000950|TEST|BLABLA
Wen i try to split and alert again it dosent work
$('#leverantors_nr').on('input', function() {
$.ajax({
url: 'pallavvikelse/jsonData',
data: {
name_startsWith: this.value,
type: 'country_table',
row_num: 1
},
dataType: 'json',
success: function(data) {
alert(data.lev_namn);
}
});
});
Problem solved:
i changed the database so it outputs array like this:
$arr['lev_nr'] = $row->lev_nr;
$arr['lev_namn'] = $row->lev_namn;
I think you are not properly parsing JSON data.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

Jquery simple Ajax Post PHP not working

I have a simple code but is not working. I want to create a more complex function but I just need the basic structure.
HTML
<span class="cleanreport">Delete Record</span>
Javascript:
$( ".cleanreport" ).click(function() {
var token = "test";
$.ajax({
data: {"data": token},
type: "post",
url: "clean.php",
success: function (data) {
console.log(data);
$('.test').html(data);
}
});
});
PHP clean.php
$data = $_POST['data'];
echo $data;
What I am doing wrong?
This should work for you:
var token = "test";
$.ajax({
type: 'POST',
url: "clean.php",
data: {id: token},
dataType: "json",
success: function(response) {
// some debug could be here
},
error: function(a,b,c) {
// some debug could be here
}
});
If not, please debug success and error parameters using console.log().
Based on jquery documentation setting type is an alias for method so this could not be a problem in you case for sure.
$( ".cleanreport" ).click(function() {
var token = "test";
$.post('clean.php",
{
data: token
},
function (data,status) {
//console.log(data);
$('.test').html(data);
});
});

jQuery.autocomplete doesn't show value returned from jQuery.ajax

I have the following code.
The ajax query works, and the data returned from the server is a valid json.
I succeeded to make the autocomplete dropdown work with a remote data source, through a request like this : http://jqueryui.com/demos/autocomplete/#remote.
My problem is that the data returned from the jquery.ajax doesn't show in the autocomplete. Anyone can help? thks.
jQuery( "#input_2_5" ).autocomplete({
source: function(request, response){
jQuery.ajax({
url: "url/wp-admin/admin-ajax.php",
type:'POST',
dataType: 'json',
data:{
action: 'word_autocomplete'
},
success: function(data) {
return data;
}
});
}
});
jQuery( "#input_2_5" ).autocomplete({
source: function(request, response){
jQuery.ajax({
url: "url/wp-admin/admin-ajax.php",
type:'POST',
dataType: 'json',
data:{
action: 'word_autocomplete'
},
success: function (data) {
if (data.d != null) {
response($.map(data.d, function (item) {
return {
value: item.name
}
}));
}
}
});
}
});
This formulation worked for me: Mine was a jsonp request, but this should do it:
jQuery( "#input_2_5" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "url/wp-admin/admin-ajax.php",
type: 'POST',
data: 'searchterm=' + request.term,
success: function( data ) {
response( $.map( data, function ( item ) {
return item;
}));
}
});
Obviously your server side should be looking for 'searchterm' in the query string...

Categories