Get value in textbox using ajax response - javascript

I want Broker Commsion on Selection of Admin with the help of Ajax Only.
<select id="user_id" onchange="funCom(this);" >
<option value="" >Select Broker </option>
<?php $aData=$oGeneral->get_records('tbl_user');
$aUsertDetails = $oGeneral->aAdmin;
$iUserDetails = $oGeneral->iAdmin;
for($i=0;$i<$iUserDetails;$i++){?>
<option value="<?=$aUsertDetails[$i]['fld_id']?>">
<?php echo $aUsertDetails[$i]['fld_name']; ?></option>
<?php }?>
</select>
<input type="text" id="comm" name="fld_commision" value="" onkeyup="sum()" required>
Funtion calling
function funCom(id){
id = id.value;
Token= "search-comm";
SendData= "Token="+Token+"&id="+id;
$.ajax({ url: 'Ajaxhandler.php',
dataType: 'text',
type: 'post',
async: false,
data: SendData,
success: function(data)
{
//var commision=stripHTML(data);
//$('#comm').val(commision); again not working
//$('#comm').text(data); Tried this but fail
$('#comm').val(data); //output is <body></body></html>7000
// i want only 7000 i have tried
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
} });
}
It is Ajaxhandler.php.
Here I am geting the commsion value which needs to put into textbox. The value is showing in <div> but I want in text box.
<?php
require('../configuration/configuration.php');
$oGeneral = new GeneralClass();
$oUser = new UserClass();
$token= $_REQUEST['Token'];
switch($token) {
case 'search-comm': $id=$_REQUEST['id'];
$oUser->project_commision($id);
$aUsertDetails = $oUser->aResults;
$iUsertDetails = $oUser->iResults;
$total=0;
for($i=0;$i<$iUsertDetails;$i++){
$total+= $aUsertDetails[$i]['fld_commsionprice'];
}
echo $total;
break;
}
?>

Change your datatype to json and try this.
Funtion calling
function funCom(id){
id = id.value;
Token= "search-comm";
SendData= "Token="+Token+"&id="+id;
$.ajax({ url: 'Ajaxhandler.php',
dataType: 'json',
type: 'post',
async: false,
data: SendData,
success: function(data)
{
//var commision=stripHTML(data);
//$('#comm').val(commision); again not working
//$('#comm').text(data); Tried this but fail
$('#comm').val(data.total); //output is <body></body></html>7000
// i want only 7000 i have tried
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
} });
}
is Ajaxhandler.php
$token= $_REQUEST['Token'];
switch($token)
{
case 'search-comm': $id=$_REQUEST['id'];
$oUser->project_commision($id);
$aUsertDetails = $oUser->aResults;
$iUsertDetails = $oUser->iResults;
$total=0;
for($i=0;$i<$iUsertDetails;$i++){
$total+= $aUsertDetails[$i]['fld_commsionprice'];
}
echo json_encode(array('total'=>$total));
break;
}
?>

try this code, I test in my computer and that works!
function funCom(id){
id = id.value;
Token= "search-comm";
SendData= "Token="+Token+"&id="+id;
$.ajax({ url: 'Ajaxhandler.php',
type: 'POST',
data: {Token:Token,id:id},
}).done(function( data ) {
$("#comm").val(data.total);
});
<?php
$token= $_REQUEST['Token'];
header('Content-type: application/json');
switch($token)
{
case 'search-comm':
$id=$_REQUEST['id'];
$oUser->project_commision($id);
$aUsertDetails = $oUser->aResults;
$iUsertDetails = $oUser->iResults;
$total=0;
for($i=0;$i<$iUsertDetails;$i++){
$total+= $aUsertDetails[$i]['fld_commsionprice'];
}
echo json_encode(array('total'=>$total));
die;
}
echo json_encode(array('total'=>""));
die;
?>

Related

highlight the keywords in autocomplete search

i want to highlight the keywords according to its autocomplete search, like if i type a then the results it gives:
java
javascript
so in this java
javascript
and then if i type av then java
javascript should get highlight or bold according to the search.
Below is my code:
javascipt
$(this).ready( function() {
$("#id").autocomplete({
minLength: 1,
source:
function(req, add){
//alert("xdhf");
$.ajax({
url: "<?php echo base_url(); ?>/trainer_dashboard/autocomplete_batchsearch",
data: req,
dataType: 'json',
type: "post",
cache: false,
success: function (data){
//alert(data);
if(data.response =="true"){
add(data.message);
console.log(data);
}
},
error: function (xhr, ajaxOptions, thrownError)
{
alert(thrownError);
}
});
},
});
});
controller
public function autocomplete_batchsearch()
{
//$user_id=get_cookie('trainer_login_user_id');
$keyword = $this->input->post('term');
$data['response'] = 'false'; //Set default response
$query = $this->trainer_dashboard_model ->batchsearch($keyword); //Search DB
//echo"";print_r($query);
if( ! empty($query) )
{
$data['response'] = 'true'; //Set response
$data['message'] = array(); //Create array
foreach( $query as $row )
{
$data['message'][] = array(
'id'=>$row->id,
'value' => $row->id,
''
); //Add a row to array
}
}
if('IS_AJAX')
{
echo json_encode($data); //echo json string if ajax request
}
else
{
$this->load->view('trainer_dashboard_view',$data); //Load html view of search results
}
}

Change event not triggered on ajax call

In the below code I have a dropdown (id-name) which populated from listplace.php'. Also made another ajax call which when the dropdown item is selected it lists the specific product fromdataprod.php`
Problem: when I click on the specific item from drop-down it does not trigger the Ajax event
I checked the dataprod.php it works correctly, but even after binding the change event with my dropdown box I m not getting the result. Please help..
<select id="name">
<option selected disabled>Please select</option>
</select>
<?php if (isset($_GET['place']) && $_GET['place'] != '') { ?>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$.ajax({
type: "POST",
data: {place: '<?= $_GET["place"] ?>'},
url: 'listplace.php',
dataType: 'json',
success: function (json) {
if (json.option.length) {
var $el = $("#name");
$el.empty(); // remove old options
for (var i = 0; i < json.option.length; i++) {
$el.append($('<option>',
{
value: json.option[i],
text: json.option[i]
}));
}
}else {
alert('No data found!');
}
}
});
</script>
<script>
$(document.body).on('change',"#name",function (e) {
//doStuff
var name1 = this.value;
$.ajax ({
data: {name1: '<?= $_GET["name1"] ?>'},
url: 'dataprod.php',
success: function (response) {
console.log(response);
$('.products-wrp').html('');
$('.products-wrp').hide();
$('.products-wrp').html(response);
$('.products-wrp').show();
},
});
</script>
<?php } ?>
dataprod.php
<?php
include("config.inc.php");
$name1 = $_POST['name1'];
$results = $mysqli_conn->query("SELECT product_name, product_desc, product_code,
product_image, product_price FROM products_list where product_name='$name1'");
$products_list = '<ul id ="products_list" class="products-wrp">';
while($row = $results->fetch_assoc()) {
$products_list .= <<<EOT
<li>
<form class="form-item">
<h4>{$row["product_name"]}</h4>
<div>
<img src="images/{$row["product_image"]}" height="62" width="62">
</div>
<div>Price : {$currency} {$row["product_price"]}<div>
</form>
</li>
EOT;
}
$products_list .= '</ul></div>';
echo $products_list;
?>
You need to pass the selected value in the ajax call.
change this line from
var name1 = this.value;
$.ajax ({
data: {name1: '<?= $_GET["name1"] ?>'},
to
var name1 = this.value;
$.ajax ({
data: {name1: name1},
type: 'POST',
HTML:
you can store the values in hidden field like:
<input type='hidden' name='name1' id='name1' value='<?= $_GET["name1"] ?>'>
Javascript:
$(document.body).on('change',"#name",function (e) {
//doStuff
var name1 = $('#name1').val();
$.ajax ({
data: {name1: '<?= $_GET["name1"] ?>'},
url: 'dataprod.php',
success: function (response) {
console.log(response);
$('.products-wrp').html('');
$('.products-wrp').hide();
$('.products-wrp').html(response);
$('.products-wrp').show();
},
});

jquery ajax call in codeigniter

i have two function one is for delete and another for update . My delete function is working correctly but when i have written update function that is not working . Also update not working.
Here is the view
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script>
$(document).ready(function()
{
$('table#delTable td button.delete').click(function()
{
if (confirm("Are you sure you want to delete this row?"))
{
var id = $(this).parent().parent().attr('id');
var parent = $(this).parent().parent();
$.ajax(
{
type: "POST",
url: "<?php echo base_url('Welcome/delete');?>",
data:'id='+id,
cache: false,
success: function()
{
parent.fadeOut('slow', function()
{$(this).remove();});
}
});
}
});
$('table#delTable tr:odd').css('background',' #FFFFFF');
});
function update(str){
var id=str;
var nm=$('#nm'+str).val();
var em=$('#em'+str).val();
var st=$('#st'+str).val();
var ph=$('#ph'+str).val();
var dp=$('#dp'+str).val();
var un=$('#un'+str).val();
var datas="id="+id+"&nm="+nm+"&em="+em+"&st="+st+"&ph="+ph+"&dp="+dp+"&un="+un;
$.ajax(
{
type: "POST",
url: "<?php echo base_url('Welcome/update');?>,
data:datas,
cache: false,
success: function(msg) {
alert(msg);
}
});
}
</script>
<button type="button" class="delete>Delete</button>
<button type="button" onclick="update(<?php echo $row['id']; ?>)">Save</button>
Controller
public function update(){
$id=$_POST['id'];
$userName=$_POST['nm'];
$tokens=explode("",$userName);
$fName=$tokens[0];
$lName=$tokens[1];
$userEmail=$_POST['em'];
$userUni=$_POST['un'];
$userState=$_POST['st'];
$userDept=$_POST['dp'];
$userPh=$_POST['ph'];
$array = array(
'first_name' => $fName,
'last_name' => $lName ,
'email' => $userEmail,
'phone_number' => $userPh,
'varsity_name' => $userUni,
'state' => $userState,
'dept_name'=> $userDept,
);
$this->load->model('Prime_Model');
$result=$this->Prime_Model->updateProfile($id,$array);
if($result){
return "Data has updated";
}
else{
return "Nothing";
}
}
You miss double quote after ?> below:
$.ajax({
type: "POST",
url: "<?php echo base_url('Welcome/update');?>", // here
data: datas,
cache: false,
success: function(msg) {
alert(msg);
}
});

jQuery autocomplete ajax request not displaying returned data

When I see on the debug developer tool ajax request responded with data but the data is not rendered in the text box. The data contains some special characters as you can see in the picture.
What is exactly wrong with the response function ? What (like utf-8 encoding maybe) should I add to the ajax call to display the special character ?
html:
<select name="selCat">
<option>....</option>
</select>
<input class="col-3" type="text" id="txtPOI" name="txtPOI" />
jquery:
$("#txtPOI").autocomplete({
source: function(request, response) {
$.ajax({
url: '<?php echo site_url("crowd/get_POIs") ?>',
data: {cat: selectedCode, q: request.term},
dataType: "json",
type: "post",
success: function(data) {
response(data);
},
fail : function ( jqXHR, textStatus, errorThrown ) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
},minLength: 3
});
}
});
Controller :
function get_POIs(){
$cat = $this->input->post('cat');
$q = $this->input->post('q');
//echo $cat;
if (isset($cat) && isset($q)){
$cat = strtolower($cat);
$q = strtolower($q);
$data=$this->crowd->get_POIs($cat,$q);
//echo "aa";
$a_json = array();
if(count($data) > 0){
foreach ($data as $row){
$a_json_row["title"] = $row->title;
$a_json_row["contentid"] = $row->contentid;
$a_json_row["latitude"] = $row->latitude;
$a_json_row["longitude"] = $row->longitude;
array_push($a_json, $a_json_row);
}
echo json_encode($a_json);
}
}
}
Model :
function get_POIs($cat, $q){
$this->db->DISTINCT();
$this->db->select('title, a.contentid, latitude, longitude, address');
$this->db->from('attraction a');
$this->db->join('geographicdata g', 'a.contentid = g.contentid', 'left');
$this->db->where('cat3 = "'.$cat.'"');
$this->db->where('title like "%'.$q.'%"');
$this->db->order_by('title','ASC');
$query = $this->db->get()->result();
//die(var_dump($query));
//echo $this->db->get_compiled_select();
return $query;
}
I managed to solve this problem by modifying the code inside the success event. Here how I did it.
change from
success: function(data) {
response(data);
}
to
success: function(data) {
response( $.map( data, function( item )
{
return{
label: item.title,
value: item.title,
contentid: item.contentid,
latitude: item.latitude,
longitude: item.longitude
}
}));
}

Get JSON from Javascript to PHP

I have a javascript function that sends JSON to my server:
$("#sendRoute").live('click', function(){
trackCoords_str = JSON.stringify(trackCoords);
final_time_m_str = JSON.stringify(final_time_m);
final_time_s_rounded_str = JSON.stringify(final_time_s_rounded);
aver_speed_km_h_rounded_str = JSON.stringify(aver_speed_km_h_rounded);
total_km_rounded_str = JSON.stringify(total_km_rounded);
$.ajax({
url: "http://test.whirlware.biz/server/",
type: "POST",
data: {
route : trackCoords_str,
timeInMinutes: final_time_m_str,
timeInSeconds: final_time_s_rounded_str,
averageSpeed: aver_speed_km_h_rounded_str,
distance: total_km_rounded_str,
},
dataType: "json"
});
});
And mix of PHP and JS code that receive and display my JSON data
<?php
$route = $_POST['route'];
$timeInMinutes=$_POST['timeInMinutes'];
$timeInSeconds=$_POST['timeInSeconds'];
$averageSpeed=$_POST['averageSpeed'];
$distance=$_POST['distance'];
$trackCoords = json_decode($route, false);
$total_km_rounded = json_decode($timeInMinutes, false);
$final_time_m = json_decode($timeInSeconds, false);
$final_time_s_rounded = json_decode($averageSpeed, false);
$aver_speed_km_h_rounded = json_decode($distance, false);
echo $trackCoords['coordsarray'];
echo $total_km_rounded;
echo $final_time_m;
echo $final_time_s_rounded;
echo $aver_speed_km_h_rounded;
?>
<script type="text/javascript">
var total_km_rounded = '<?php echo $total_km_rounded ?>';
document.write('Растояние: ' + total_km_rounded);
var final_time_m = '<?php echo $final_time_m ?>';
document.write('Растояние: ' + final_time_m);
var final_time_s_rounded = '<?php echo $final_time_s_rounded ?>';
document.write('Растояние: ' + final_time_s_rounded);
var aver_speed_km_h_rounded = '<?php echo $aver_speed_km_h_rounded ?>';
document.write('Растояние: ' + aver_speed_km_h_rounded);
</script>
But when I send JSON data my server don`t display it. Where did I make a mistake? Maybe I can receive JSON another way?
Try this, success: function(response) {alert('Success!');}, after the data, not inside the data
data: {
route : trackCoords_str,
timeInMinutes: final_time_m_str,
timeInSeconds: final_time_s_rounded_str,
averageSpeed: aver_speed_km_h_rounded_str,
distance: total_km_rounded_str
},
success: function(response) {alert('Success!');},
You should JSON.stringify an array like this(general convention):
//rough code
data['trackCoords_str'] = trackCoords;
data['final_time_m_str'] =final_time_m;
data['final_time_s_rounded_str'] = final_time_s_rounded;
data['aver_speed_km_h_rounded_str'] = aver_speed_km_h_rounded;
data['total_km_rounded_str'] = total_km_rounded;
$.ajax({
url: "http://test.whirlware.biz/server/",
type: "POST",
data: JSON.stringify(data),
dataType: "json",
success: function(){ alert('success!'); },
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
alert(thrownError);
});
});

Categories

Resources