How to remove dublicate values using codeigniter and ajax? - ajax

I return passports from my database when I select user using codeigniter and I'm getting these data using ajax.
This is my php code in the controller:
public function contactsPassports(){
// POST data
$this->load->model('contacts/contacts_international_pass_m');
$data = $this->input->post();
$passports = array();
$where = array('contact_id'=>$data['selected_id']);
$passports = $this->contacts_international_pass_m->where($where)->order_by('id','DESC')->get_all();
if(!empty($passports)) {
foreach($passports as $item)
{
$item->pass = $this->contacts_international_pass_m->get($item->nat_passport_num);
}
}
$this->data->passports = $passports;
echo json_encode($this->data);
}
And this is my ajax code:
$.ajax({
url:'/companies/ajax/contactsPassports',
method: 'post',
data: {"selected_id": contactID},
dataType: 'json',
async: true,
success: function(data){
var html = '';
$.each(data.passports, function(key, value) {
console.log(data);
html += '<div class="nationality_name" style="float:left">'+ value.nat_passport_num + '</div>' + '<div class="nationality_name_delimiter" style="float:left">'+', '+'</div>';
});
$('#passport').html(html);
}
});
But I want to remove the dublicate passports for every user. For example now I am getting this:
User 1
12345678, 1234, 1234, 123456, 123456
And I want to getting this:
User 1
12345678, 1234, 123456

You can use distinct query builder to select only distinct values:
$passports = $this->contacts_international_pass_m->distinct()->select('nat_passport_num')->where($where)->order_by('id','DESC')->get_all();

Related

Bootstrap Select 'refresh" continues to add new options instead of removing the old ones

Any help here would be appreciated as I can't see what I'm doing wrong.
I have an empty select picker:
<select class='selectpicker' name='new_teamid' id='new_teamid' style='width:200px;margin-left:-5px;margin-top:0px;' required></select>
This is being populated via AJAX call when another select box option has changed
var query_parameter = document.getElementById("new_deptid").value;
var dataString = 'dept=' + query_parameter;
// AJAX code to execute query and get back to same page with table content without reloading the page.
$.ajax({
type: "POST",
url: "helpers/populateteams.php",
data: dataString,
cache: false,
success: function(html) {
document.getElementById("new_teamid").innerHTML=html;
$('#new_teamid').selectpicker('refresh');
}
});
As you can see, its calling another php page which returns an HTMl string for the options. This works, if i inspect the element, the HTML options are updated correctly. im using = not +=. Problem is, the selectpicker is not removing the previous items. It just keeps adding the new items.
Any idea what I may be doing wrong here?
If you are curious, this is the populateteams.php
$theHTML = "";
$theHTML .= '<option value="" selected>Please Select</option>';
$sql = "SELECT * FROM tool_teams WHERE (dept_id=?) ORDER BY teamname asc";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $dept_id);
if ($stmt->execute() === TRUE) {
$result = $stmt->get_result();
if(!empty($result) && $result->num_rows)
{
while ($row = mysqli_fetch_array($result))
{
$theHTML .= '<option value="'.$row['team_id'].'">'.$row['teamname'].'</option>';
}
}
}
echo $theHTML;
resolved this myself. This is dumb, but this is how you need to do it:
$.ajax({
type: "POST",
url: "helpers/populateteams.php",
data: dataString,
cache: false,
success: function(html) {
document.getElementById("new_teamid").innerHTML=html;
$('#new_teamid').selectpicker('destroy');
$('#new_teamid').selectpicker('render');
},
complete: function(html) {
}
});
You need to destroy and render instead of refresh. This is stupid. But it works

How to search database data using 2 conditions

I am trying to get data from database for specific id for selected month from datatable.
I passed the id and month using ajax but stuck at using 2 where condition.
Ajax
$('.viewmonthwisesale').on('click',function () {
var getid = document.getElementById('getid').value;
var dataId = $(this).attr("data-id");
$.ajax({
type: 'GET',
url: '/viewmonthlydataforcustomer',
data: {
'id': getid,
'month':dataId
},
success: function(data) {
console.log(data);
//location.reload();
}
});
})
Controller
{
$id = $req->id;
$monthname = $req->month;
$month_number = Carbon::parse($monthname)->format('m-Y');
$getdaa = Dairyincome::select(
DB::raw('DATE_FORMAT(milksaledate, "%m %Y") as "month_name", SUM(cmilkquantity) as "cmilkquantity", SUM(cmilkamount) as "cmilkamount",SUM(bmilkquantity) as "bmilkquantity", SUM(bmilkamount) as "bmilkamount", SUM(totalamount) as "totalamount"')
)
->where('customerid',$id)
->whereYear('milksaledate', date('Y'))
->groupBy('month_name')
->get();
return response()->json([$getdaa]);
}
Refer image where i able to get data for Year 2022 but i need it with Specific month as per monthname .
Hope i clearly mention my problem and thanks in advance for support.

How to show array result in ajax success using codeigniter?

I am fetching values from data using where in() mysql query and I got the correct result, but I don't know how to display the result in ajax success.
How do I display company name and email id from result data set?
my ajax code
<script type="text/javascript">
$('#ok').on('click', function() {
var vals = $('#show').val();
$.ajax({
type: "POST",
url: "<?php echo base_url();?>email/get_company",
data: { vals:vals },
datatype: 'json',
success: function (data) {
alert(data);
$("#result").html(data);
var result = JSON.parse(data);
}
});
});
</script>
my controller code:
function get_company()
{
$vals = $this->input->post('vals');
$query = $this->db->query("SELECT * FROM customer` where company_id IN ($vals) ")->result();
echo json_encode($query);
}
my result:
[{"company_name":"xyz Ltd","company_email":"123#gmail.com"},{"company_name":"wer Jit","company_email":"2222#gmail.com"}]
assuming you get this json in your ajax success:
const json = '[ {
"company_name": "xyz Ltd",
"company_email": "123#gmail.com"
},
{
"company_name": "wer Jit",
"company_email": "2222#gmail.com"
}]
';
const obj = JSON.parse(json);
// you don't need this line, if you have set ajax datatype:'json'
you can get results for a single data set:
console.log(obj[0].company_name);
// this is how to get the first company name of the data set
// expected output: "xyz Ltd"
or you can loop through the whole data set
obj.forEach(element => $("#result").append(element.company_name + '<br>'));
see a working example
conclusion: your ajax function could look just simply like this:
$.ajax({
type: "POST",
url: "<?php echo base_url();?>email/get_company",
data: {
vals: vals
},
datatype: 'json',
success: function(data) {
obj.forEach(data => $("#result").append(data.company_name + '<br>'));
}
})

How can we encode the Multi JSON data response in ajax

I have a problem with json encoded information which loaded via ajax.I pass the multi JSON to the ajax for display the field value.
How can i fetch the field value from the json using query ajax.
ajax code :
....success:function(data){
var TotalBuyPrice = 0;
var TotalItem = 0;
$.each(data, function(c,cart){
//Condition follow 1
var InStockQty =cart.products_qty;
alert(InStockQty);
//And also follow 2
var name =cart["withoutdiscount"][0]["products_name"];
alert(name);
});
}...
The PHP code :
These are my steps following for json response.By using array collect the result
$response = array();
$response['withoutdiscount'] = $withoutdiscount;
$response['withdiscount'] = $withdiscount;
echo $_GET['jsoncallback'] . '(' . json_encode($response). ');';
jsoncallback:
({"withoutdiscount":[{"products_id":"1","products_name":"Lumia"}],
"withdiscount":[{"products_id":"2","discount_qty":"8"},
{"products_id":"3","discount_qty":"1"}
]
});
I Solve the problem like this:
Using PHP file get one response like this:
$response = array();
$response['withoutdiscount'] = $withoutdiscount;
$response['withdiscount'] = $withdiscount;
echo $_GET['jsoncallback'] . '(' . json_encode($response). ');';
jsoncallback: //JSON response
({"withoutdiscount":[{"products_id":"1","products_name":"Lumia"}],
"withdiscount":[{"products_id":"2","discount_qty":"8"},
{"products_id":"3","discount_qty":"1"}
]
});
using ajax function call the json response like this:
function querySuccess(tx,results) {
var jsonString = JSON.stringify(results);
$.ajax({
url:'getcart.php',
data: {data : jsonString},
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success:function(data){
var withdiscount=data.withdiscount;
var withoutdiscount=data.withoutdiscount;
if(withdiscount!='')
{
$.each(withdiscount, function(c,cart){
var discount_qty =cart.discount_qty;
alert(discount_qty);
);
}
if(withoutdiscount!='')
{
$.each(withoutdiscount, function(c,cart){
var products_name =cart.products_name;
alert(products_name);
});
}
}
});
}
This is working with me.
NOTE: There is only 2 JSON response is pass so i given directly.

Ajax form not submitting

I followed the Submit Ajax Form tutorial on tutsplus.com ,
but cannot figure out for the life of me why my data won't have addreply.php applied to it. When I look in my mysql table, the data does not get inserted. Any help would be greatly appreciated. I searched the web and have troubleshooted for many hours.
$(document).ready(function() {
$(".replyLink").one("click", function(){
$(this).parent().after("<div id='contact_form'></div>");
$("#contact_form").append("<form id='replyForm'></form>");
$("#replyForm").append("<input class='enterName' id='enterName' type='text'
name='name' placeholder='name' rows='1' cols='20' />");
$("#replyForm").append("<textarea class='enterReply' id='enterReply' name='comment'
placeholder='reply'></textarea>");
$("#replyForm").append("<input type='hidden' name='id' value=''>");
commentID= $(this).parent().attr('id');
$("#replyForm").append("<input class='replyButton' id='replyButton' type='submit' `value='reply'/>");`
$(".enterReply").slideDown();
$(".replyButton").slideDown();
});
$(".replyButton").click(function() {
var name = $("input#enterName").val();
var reply = $("textarea#enterReply").val();
var dataString = 'name='+ name.val() + '&comment=' + reply.val();
$.ajax({
type: "POST",
url: "addreply.php",
data: dataString,
success: function() {
}
});
return false;
});
**addreply.php**
<?php
session_start();
$replyID= $_POST['id'];
$name= $_POST['name'];
$comment= $_POST['comment'];
$type= $_POST['type'];
$song= $_POST['song'];
if($song == ''){
$song= 'not';
}
include 'connection.php';
if($_SESSION['signed_in'] == 'yes') {
$query1= "INSERT INTO ApprovedComments(name, comment, Authorized, type, reply_ID, song, date)
VALUES('$name', '$comment', 'YES', '$type', '$replyID', '$song', NOW());";
$insertComment= mysql_query($query1);
// echo "hi";
}
if( !isset($_SESSION['signed_in']) ) {
$query2= "INSERT INTO PreApprovedComments(name, comment, reply_ID, song, date)
VALUES('$name', '$comment', '$replyID', '$song', NOW());";
$insertComment= mysql_query($query2);
}
mysql_close();
?>
Try
$.ajax({
type: "POST",
url: "addreply.php",
data: $("#replyForm").serialize()+'name='+ encodeURIComponent(name) +
'&comment=' + encodeURIComponent(reply),
success: function() {
}
});
this will post all the fields in the #replyForm form and the name and comment fields.

Resources