Codeigniter Ajax sorting search result - javascript

Controller:
public function index()
{
.
.
.
$search_result = $this->m_results->search_people(array('country'=>$country,'state'=>$state,'city'=>$city,'sort'=>$this->sort,'id'=>$data['id']),$keyword,$s_id);
$this->load->view('include/header',$data);
if($search_result != FALSE)
{
$data['results']['freelancers'] = $search_result;
// print_r($data['results']['freelancers']); exit();
$data['sort_value'] = $this->sort;
$this->load->view('search',$data);
}else{
$data['string'] = $this->input->post('keyword');
$this->load->view('search_empty',$data);
}
$this->load->view('include/footer',$data);
}
Ajax function:
$("body").on("change", "#sort", function () {
$.ajax({
method: "get"
, url: base_url + "search"
// , cache: false
, data: {
skills: $("#inputtags").val()
, sort: $("#sort").val()
, city: $("#locationTextField").val()
}
, success: function (data) {
// console.log(data);
alert(data);
$("body").html(data);
}
})
});
View:
<div class="form-group sidemargin">
<select name="sort" id="sort" class="form-control select color2 bold">
<option value="rating" <?php echo set_select('sort','rating',( $sort_value == "rating" ? TRUE : FALSE )); ?>>Ratings</option>
<option value="review_count" <?php echo set_select('sort','review_count',( $sort_value == "review_count" ? TRUE : FALSE )); ?>>Reviews</option>
</select>
</div>
Above are the code I'm using for display the results after sorting by Ajax. But now the problem is after sorting the result, when I alert the success data its coming the entire html code but not the result from database.
I can't understand why its showing the html code instead of the sorted data from db. When I try to print_r() those result in controller, its showing correct value. When it come to Ajax success the values are different.
So folks help me to solve this. Answers will are appreciated. Thanks in advance.

Related

display state on select box in ajax success and show other states in dropdown list

Hello i am displaying state name and state id after ajax success function but i am not display because i don,t know how can i show ? After that i am also show that list of state below the state name. need help to solve this query
public function edit_address(Request $request)
{
$state = DB::table('states')->pluck('state_name','state_id');
$each_edit_address=DB::table('address')
->join('states','states.state_id','=','address.state_id')
->select('address.*','states.state_name')
->where('address_id',$request->address_id)
->get();
foreach ($each_edit_address as $edit_address)
{
return response()->json(['address_id' => $edit_address->address_id,'address' =>$edit_address->address,'pincode'=>$edit_address->pincode,'locality'=>$edit_address->locality,'city'=>$edit_address->city,'landmark'=>$edit_address->landmark,'option_mobile_number'=>$edit_address->option_mobile_number,'user_name'=>$edit_address->user_name,'user_mobile'=>$edit_address->user_mobile]);
}
}
//javascript
$(document).on('click', '.show_address', function(e){
e.preventDefault();
$('.edit_address_label').show();
$('#edit_address').show();
$("#address_show:checked").closest('.col-sm-8').find('.current_user_address').hide();
$("#address_show:not(:checked)").closest('.col-sm-8').find('.edit_address_label').hide();
$("#address_show:checked").closest('.display_address').find('.deliver_show_address').removeClass('deliver_address');
$("#address_show:checked").closest('.display_address').find('.deliver_show_address').addClass('delivery_hide_address');
$('#save_address').hide();
var address_id=$(this).attr('data-val');
$.ajax({
type : 'get',
url : '/edit-address',
data:{ 'address_id':address_id
},
success:function(result)
{
$('#edit_address').attr("data-val",result.address_id);
$('.show_address').parents().find('#name').val(result.user_name);
$('.show_address').parents().find('#mobile_number').val(result.user_mobile);
$('.show_address').parents().find('#address').val(result.address);
$('.show_address').parents().find('#pincode').val(result.pincode);
$('.show_address').parents().find('#locality').val(result.locality);
$('.show_address').parents().find('#city').val(result.city);
$('.show_address').parents().find('#landmark').val(result.landmark);
$('.show_address').parents().find('#option_number').val(result.option_mobile_number);
}
});
});
<div class="col-sm-6">
<div class="form-group">
<label>State<span>*</span>
</label>
<select name="new_state" class="form-control" id="state">
<option value="">Select State</option>
#foreach($state as $id => $state_name )
<option value="{{ $id }}">{{ $state_name }}</option>
#endforeach
</select>
</div>
</div>
It's because you are doing it wrong, I don't really know what you have in mind with the data, but you are starting a foreach loop inside your controller function, but you only return the first row of the $edit_address and the rest are skipped. So you have to first, return the data as a whole to JavaScript and then loop through it in your Ajax complete() function like below:
controller:
public function edit_address(Request $request)
{
$state = DB::table('states')->pluck('state_name','state_id');
$each_edit_address=DB::table('address')
->join('states','states.state_id','=','address.state_id')
->select('address.*','states.state_name')
->where('address_id',$request->address_id)
->get();
return response()->json(['addresses' => $each_edit_address, 'states' => $state]);
}
and then, in your JS code, based on the data that you returned from your controller, you can loop through the addresses like below:
var address_id=$(this).attr('data-val');
$.ajax({
type : 'get',
url : '/edit-address',
data:{ 'address_id':address_id
},
success:function(result)
{
$(result.addresses).each(function(address){
console.log(address.user_name);
// Write your own code here to deal with each address.
});
}
});
Note: You can also get access to the states data in your ajax complete() function like below:
var address_id=$(this).attr('data-val');
$.ajax({
type : 'get',
url : '/edit-address',
data:{ 'address_id':address_id},
success:function(result)
{
console.log(result.states);
}
});

jQuery AJAX Autocomplete not working when trying to make it dynamic

I have my autocomplete working fine if there is hard coded data being fed into it. My PHP is returning a JSON result. I'm not sure where I am going wrong.
HTML
<div class="form-group bgcolor">
<label for="send_to">Direct to: </label><input type="text" name="send_to" id="send_to" class="form-control send_to typeahead" placeholder="Leave blank normally">
</div>
Jquery
$('.typeahead').typeahead({
source: {
groupName: {
ajax({
url: 'scripts/order_messaging.php',
method: 'POST',
data: JSON.stringify({action: 'autocomplete_to_user', query:query}),
contentType: 'application/json',
dataType: 'json',
success:function(data)
{
result($.map(data, function(item){
return item;
}));
}
})
},
},
debug: true
});
PHP
//autocomplete user name for user_to
if ( $_POST['action'] == 'autocomplete_to_user' ) {
$stmt = $pdo->prepare('select * from login where username like :query');
$stmt->bindValue('query', '%'.$_POST['query'].'%');
$stmt->execute();
$result = array();
while($user_name = $stmt->fetch(PDO::FETCH_OBJ)) {
array_push($result, $user_name->username);
}
echo json_encode($result);
}
I think it's this line in my jQuery: data: {action: 'autocomplete_to_user', query:query}, Maybe I have a syntax problem.
As per jQuery Ajax Documentation, dataType: 'json' evaluates the response as JSON and returns a JavaScript object.
You need to stringify your data by using JSON.stringify({action: 'autocomplete_to_user', query:query}) before you send it to PHP. Also, you need to add header Content-Type: 'application/json' that tells you PHP code that request data is JSON. You can do this by adding contentType: 'application/json' in your Ajax settings.
Your final jQuery code would look like this:
$('.typeahead').typeahead({
source: function(query, result)
{
$.ajax({
url: 'scripts/order_messaging.php',
method: 'POST',
data: JSON.stringify({action: 'autocomplete_to_user', query:query}),
contentType: 'application/json',
dataType: 'json',
success:function(data)
{
result($.map(data, function(item){
return item;
}));
}
})
}
});
Refer to jQuery Ajax Documentation for mode details.
Hope this helps!
EDIT:
You need to update your PHP code to read JSON. Please refer to this link.
Your PHP Code should look like this:
<?php
// Read the input stream
$body = file_get_contents("php://input");
// Decode the JSON object
$object = json_decode($body, true);
//autocomplete user name for user_to
if ( $object ['action'] == 'autocomplete_to_user' ) {
$stmt = $pdo->prepare('select * from login where username like :query');
$stmt->bindValue('query', '%'.$object['query'].'%');
$stmt->execute();
$result = array();
while($user_name = $stmt->fetch(PDO::FETCH_OBJ)) {
array_push($result, $user_name->username);
}
echo json_encode($result);
}
?>
In my humble opinion, the documentation has some errors. For instance, in the demos, specifically the example Country v2 states
A POST request will be sent with data myKey: myValue
when in actuality the request being sent in the example is GET, because it depends on the type key of the ajax object of the first source (country in this case), which is not set, thus defaulting to GET.
So, that being said, you really should stick to the proposed HTML structure (at least start with it, then take away stuff you don't want gradually as long as it'll let you).
HTML
<form id="form-country_v2" name="form-country_v2">
<div class="typeahead__container">
<div class="typeahead__field">
<div class="typeahead__query">
<input class="typeahead" name="country_v2[query]" placeholder="Search" autocomplete="off">
</div>
<div class="typeahead__button">
<button type="submit">
<i class="typeahead__search-icon"></i>
</button>
</div>
</div>
</div>
</form>
JS
$(document).ready(() => {
$('.typeahead').typeahead({
template: "{{display}} <small style='color:#999;'>{{group}}</small>",
source: {
users: { //might as well be 'willy wonka', it doesn't matter
ajax: {
type: "POST",
url: "scripts/order_messaging.php",
//this is not actually needed for the request to work (reach the server),
//this is used to access said request's returned data, it all
//depends on how you structure the response in the server,
//check out the php part
path: "data.users",
data: {
action: 'autocomplete_to_user',
query: 'username'
}
}
}
},
callback: {
//this is just to help you show the response in the html
onResult: function(node, query, result, resultCount) {
if (query === "") return;
var text = "";
if (result.length > 0 && result.length < resultCount) {
text = "Showing <strong>" + result.length + "</strong> of <strong>" + resultCount + '</strong> elements matching "' + query + '"';
} else if (result.length > 0) {
text = 'Showing <strong>' + result.length + '</strong> elements matching "' + query + '"';
} else {
text = 'No results matching "' + query + '"';
}
$('#result-container').html(text);
},
onInit: function(node) { //and this is just informational
console.log('Typeahead Initiated on ', node, node.selector);
}
}
});
});
order_messaging.php
if ($_POST['action'] == 'autocomplete_to_user') {
$stmt = $pdo->prepare('select * from login where username like :query');
$stmt->bindValue('query', '%' . $_POST['query'] . '%');
$stmt->execute();
$result = array();
while ($user_name = $stmt->fetch(PDO::FETCH_OBJ)) {
array_push($result, $user_name->username);
}
echo json_encode(array(
"status" => true,
"error" => null,
//here you use whatever structure you want to return the data in,
//as long as the payload is an array ($result).
//remember in the JS you are expecting 'data.users'?
//this is where it's coming from
"data" => array(
"users" => $result,
)
));
} else
echo json_encode(array(
"status" => true,
"error" => null,
"data" => array(
"users" => [],
)
));
HIH
Well, after much trial and error I got an autocomplete working using jQuery .autocomplete.
I don't know what I was doing wrong with the typeahead but the documentation was hard to understand (probably because of my limited experience with jQuery).
To all those in the future that need some help with this; here is a tutorial I found that was helpful: jquery ui autocomplete tutorial
Thank you to everyone
I've tested the library and you need to change two things in order to make it work.
1) You need to restructure the source parameter. You were giving it an AJAX callback which is not supported. According to the documentation, it accepts an array or an object with settings, so AJAX needs to be defined like this:
$('.typeahead').typeahead({
source: {
// source has an "ajax" property where you just need to place
// the object with AJAX params (the one you'd normally place inside
// an $.ajax() call)
ajax: {
url: 'scripts/order_messaging.php',
method: 'POST',
data: {
action: 'autocomplete_to_user',
query: query,
},
dataType: 'json',
path: '',
},
},
});
The path property of the ajax object is key here. It tells the typeahead function where to look for the data that was returned by the AJAX action. Since you're encoding a one-dimensional array of values, you need to set it to an empty string, meaning your data is in the root of the response.
If you were to return, for example, an array like echo json_encode(['users' => $result]); then you'd have to set the path to 'users' (because that is the index in the response that holds your data).
2) You have to follow a strict HTML structure in order to make it work:
<div class="typeahead__container">
<div class="typeahead__field">
<div class="typeahead__query">
<input class="js-typeahead" name="q" autocomplete="off">
</div>
</div>
</div>
If you leave out any of these elements, it doesn't trigger the functionality. This HTML structure is one of the first things they mention in the documentation.

AJAX filled Select2 not clickable

I'm using Select2 for a project. The second select box gets filled depending on the selected item in the first box, as shown in the link below. However, I can't click the first item in the second select box for some reason. The only way for me to select the first item if I want to, is to first select a different user, and then back to the first. How can I solve this?
Video:
My code:
This is the first select box, getting filled by regular PHP (Laravel). Everything works fine here.
<div class="form-group">
<label for="select"> Partner: </label>
<select id="select" name="select" class="searchselect searchselectstyle">
#foreach($partners as $i => $partner)
<option {{$i == 0 ? 'selected' : ''}} value="{{$partner->id}}">{{$partner->name}}</option>
#endforeach
</select>
</div>
Here Is the second select box, with the error.
<div class="form-group" >
<label for="select2"> Hoofdgebruiker: </label>
<select id="select2" style="min-width: 200px;" name="select2" class="searchselect searchselectstyle">
</select>
</div>
<script type="text/javascript">
$(document).ready(function(){
var url = '/json/getusers';
var $post = {};
$post.id = $("select").val();
$.ajax({
type: "POST",
dataType: "json",
url: url,
data: $post,
cache: false
}).done(function(data){
$('#select2')
.find('option')
.remove()
.end();
$.each(data, function(i, value) {
console.log(data);
$('#select2').append($('<option>').text(value.text).attr('value', value.id));
});
}
);
});
-
public function getusers(){
if(!isset($_POST['term'])){
$users = User::where('partner_id', $_POST['id'])->get();
}else{
$wildcard = '%'.$_POST['term'].'%';
$users = User::where('partner_id', $_POST['id'])->where('email', 'LIKE', $wildcard)->get();
}
$array = array();
foreach($users as $i => $user){
$array[$i] = array("id" => $user->id, "text" => $user->email);
}
return response()->json($array);
}
Check the case sensitivity of the key "id" in json data. Probably you return "ID" insteat of "id".
{"results":[{"id":"3","text":"Exampe 3"},{"id":"4","text":"Example 4"},{"id":"16","text":"Example 16"}]}
not like that
{"results":[{"ID":"3","text":"Exampe 3"},{"ID":"4","text":"Example 4"},{"ID":"16","text":"Example 16"}]}
I found a solution, which is the following:
<script type="text/javascript">
$(document).ready(function() {
$(".searchselect").select2();
search();
$("#select").change(function(){
search();
});
});
function search(){
var $post = {};
$post.id = $("#select").val();
$("#select2").select2({
ajax: {
dataType: "json",
type: "POST",
data: function (params) {
var query = {
term: params.term,
id: $post.id
};
return query;
},
url: '/json/getusers',
cache: false,
processResults: function (data) {
return {
results: data
};
}
}
});
}
</script>
Now I'm using the regular AJAX functionality built in Select2, it is all working as expected now!

How do I use Ajax in a Wordpress plugin?

I have a Wordpress site with 2 dropdown boxes. When I select an option in the first dropdown box I want the 2nd one to be refreshed with data from a PHP function. For that I need ajax. But I'm struggling with binding ajax into Wordpress.
The HTML looks like this:
<form method="get" action="http://siradjov.anex.at/playground/">
<div class="form-inner">
<div class="listing-search-main">
<input type="text" class="listing-search-text text" name="s" title="Coach House, Golf Course, Water View, etc" value="unique">
<input type="submit" class="listing-search-submit btn btn-large btn-primary" name="search-submit" value="Search">
</div><!-- .listing-search-main -->
<div class="listing-search-details">
<div class="listing-search-field listing-search-field-select listing-search-field-status">
<select class="listing-search-status select" name="status">
<option value="">Status</option>
<option value="sale">Sales</option>
<option value="rent">Rentals</option>
<option value="foreclosure">Foreclosure</option>
</select>
<div class="listing-search-advanced " style="display: block;">
<div class="listing-search-field listing-search-field-select listing-search-field-min">
<select class="listing-search-min select" name="min">
<option value="">Price (min)</option>
<option value="100000">100.000</option>
<option value="200000">200.000</option>
<option value="300000">300.000</option>
<option value="400000">400.000</option>
</select>
Now when for example the user selects "Sales" I want the second select tag to be reloaded with the matching prices from a PHP array.
The PHP function looks like this:
<?php
$selectedStatus = $_POST['status'];
if($selectedStatus == "sale")
{
// Set price (min) to select
$fields['min']['type'] = 'select';
// Set price (min) select options
$fields['min']['data'] = array(
'100000' => '120,000',
'120000' => '200.000',
'130000' => '300.000',
);
// Set price (max) to select
$fields['max']['type'] = 'select';
// Set price (max) select options
$fields['max']['data'] = array(
'100000' => '120,000',
'120000' => '200.000',
'130000' => '300.000',
);
}
else if($selectedStatus == "rent")
{
// Set price (min) to select
$fields['min']['type'] = 'select';
// Set price (min) select options
$fields['min']['data'] = array(
'200' => '200',
);
// Set price (max) to select
$fields['max']['type'] = 'select';
// Set price (max) select options
$fields['max']['data'] = array(
'200' => '200',
);
}
echo $fields;
I've save my jQuery Ajax call in a separate .js file. The code is the following:
jQuery(document).ready(function() {
jQuery(".listing-search-status.select[name='status']").change(function() {
if (this.value == "sale")
{
jQuery.ajax({
type: "POST",
url: "http://siradjov.anex.at/playground/wp-content/plugins/wpcasa-extended-search-status-price-chain-select/wpcasa_custom_prices.php",
data: { status : "sale" },
success: function(data)
{
alert('Sale' + data['min']['data'][0]);
}
});
}
else
{
if (this.value == "rent")
{
jQuery.ajax({
type: "POST",
url: "http://siradjov.anex.at/playground/wp-content/plugins/wpcasa-extended-search-status-price-chain-select/wpcasa_custom_prices.php",
data: { status : "rent" },
success: function(data)
{
alert('Rent' + data['min']['data'][0]);
}
});
}
}
});
});
But the alert Boxes don't show up. Neither do I get any error messages on Google Chrome's Console. Can anyone help me?
Use the native methods that Wordpress provides to you to leverage ajax requests.
In your plugin file, we need to add a couple actions so that we can send ajax requests through and have them parsed by the admin-ajax.php file.
add_action('wp_ajax_nopriv_ajax_request', 'ajax_controller');
add_action('wp_ajax_ajax_request', 'ajax_controller');
Now we build out an ajax controller in our plugin file. The purpose of this is to act as a controller that will switch it's output based on the FN parameter supplied by the ajax request (more on this later)
function ajax_controller(){
$ret = ''; //our return variable
switch($_REQUEST['fn']):
case 'status' :
$ret = update_status($_REQUEST['status']);
break;
endswitch;
echo $ret;
die(); //this makes sure you don't get a "1" or "0" appended to the end of your request.
}
Please note that the update_status() function was created to encapsulate your above php code.
Now we have the actions bound, and a controller that we can use endlessly to retrieve data. We just need to make a couple modifications to the ajax call. First, we can use ternary assignment for the 'rent/sale' switch, as opposed to 2 ajax calls, which will clean things up. Second, we need to change the url address to the /wp-admin/admin-ajax.php file.
var $status = (this.value == "sale") ? this.value : 'rent';
jQuery.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
data: {
action: 'ajax_request',
fn : 'status', //this is the $_REQUEST['fn'] from above
status : $status },
success: function(data){
alert('Sale' + data['min']['data'][0]);
}
});
The action parameter is required, the fn is a result of my coding principles. The action attribute must directly match what comes after add_action('wp_ajax_nopriv_ and add_action('wp_ajax_.
This should resolve it.

Select list not getting populated (jQuery Ajax)

Update: Got this working by disabling CodeIgniter Profiler which was interfering with the Ajax success response. I think it adds a div to the JSON response.
I am trying to populate a dependent select box with data from mysql database. The problem is that the dependent select box is not getting populated in spite of getting data in the correct format in response to Ajax request.
Please help me as I am totally clueless about what's happening here. Below is my JavaScript code.
<script type="text/javascript">
$(document).ready(function(){
$('#country').change(function(){
$("#cities > option").remove();
var form_data = {
country: $('#country').val(),
csrf_token_name: $.cookie("csrf_cookie_name")
};
$.ajax({
type: "POST",
url: "http://localhost/outlets/get_cities",
data: form_data,
dataType : "JSON",
success: function(cities)
{
$.each(cities,function(id,name)
{
var opt = $('<option />');
opt.val(id);
opt.text(name);
$('#cities').append(opt);
});
}
});
});
});
</script>
And here is the HTML. I am using Codeigniter.
<form id="form">
<?php $cities['#'] = 'Please Select'; ?>
<label for="country">Country: </label><?php echo form_dropdown('country_id', $countries, '#', 'id="country"'); ?><br />
<label for="city">City: </label><?php echo form_dropdown('city_id', $cities, '#', 'id="cities"'); ?><br />
</form>
Here is the controller:
function get_cities(){
$country = $this->input->post('country');
$this->load->model('city');
header('Content-Type: application/x-json; charset=utf-8');
echo (json_encode($this->city->get_cities($country)));
}
& the Model:
function get_cities($country = NULL){
$this->db->select('id, name');
if($country != NULL){
$this->db->where('countries_id', $country);
}
$query = $this->db->get('cities');
$cities = array();
if($query->result()){
foreach ($query->result() as $city) {
$cities[$city->id] = $city->name;
}
return $cities;
}else{
return FALSE;
}
}
Change your ajax success callback to:
success: function (cities) {
for (var id in cities) {
var opt = $('<option />');
opt.val(id);
opt.text(cities[id]);
$('#cities').append(opt);
}
}
Because your ajax result is not a array but an json object.
Alright everyone, I managed to get this working by disabling CodeIgniter Profiler. Codeigniter profiler, that otherwise is a handy tool, breaks javascript on any page with Ajax. If you can't do without profiler, use the solution provided on Making CodeIgniter’s Profiler AJAX compatible

Categories