How to search database data using 2 conditions - laravel

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.

Related

How to remove dublicate values using codeigniter and 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();

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>'));
}
})

Passing two different list from controller to view through Ajax Success in MVC

Is there any way to pass two different list from controller to view using ajax success.
My Ajax Code is
$.ajax({
url: "#Url.Action("GetDoctorWiseReport","DCDReport")",
data: { fromDate: fromDate, toDate: toDate },
type: "post",
datatype: "json",
success: function (data) {
// do something
}
My Controller Code is
public JsonResult GetDoctorwiseReport(DateTime fromDate,DateTime toDate)
{
IEnumerable<DoctorVM> Doctors = homeObj.GetDistinctDoctorsFromTransactionMaster(fromDate, toDate);
IEnumerable<WorkOrderDetailsVM> woDetails = homeObj.GetDoctorwiseReport(fromDate, toDate);
return Json(woDetails.ToList());
}
I want to pass both Doctors and WoDetails through Json.
As Stephen Muecke said
return Json(new { x = woDetails, y = Doctors });
This works fine.

AJAX failing to upload blob image

I have a problem with uploading a blob using ajax. I have tried many options and they are not working.
I must say that the same variables (albeit with different names) work when using php in the standard sense but not when using ajax.
Please help
The ajax code is:
$(function() {
$("#upload").click(function() {
// validate and process form here
var username = $("input#username").val();
var title = $("input#title").val();
var image = $("#image").get(0).files.item(0);
var information = tinymce.get('blogcontent').getContent();
var dt = new Date();
// variable for blog date and time
var dateandtime = dt.toLocaleString();
var dataString = 'username=' + username + '&title=' + title + '&image=' + image + '&information=' + information + '&dateandtime=' + dateandtime;
$.ajax({
type: "POST",
url: "functions/insertblogpost.php",
data: dataString,
success: function() {
$('#writeblog').html("<div id='message'></div>");
$('#message').html("<h2>User account created!</h2>")
.append("<p>Please go back to login.</p>")
.hide()
.fadeIn(1000, function() {
$('#message').append("<a href='../../Mobileapptemplate.php'>Back</a>");
});
}
});
return false;
});
});
And the php script is:
$connection = mysqli_connect($dbserver, $dbusername, $dbpassword, $database);
$username = $_POST[ 'username' ];
$blogTitle = $_POST["title"];
$blogContent = $_POST["information"];
$blogpicturename = $_FILES["image"]["name"];
$blogpicdata = mysqli_real_escape_string( $connection, file_get_contents($_FILES["image"]["tmp_name"]));
$blogpictype = $_FILES['image']['type'];
$dateAndTime = $_POST["dateandtime"];
$result = "INSERT INTO ct5006ho_users.$username ( postnumber, user, title,
picturename, picture, blogpost, dateandtime ) VALUES ( '', '$username', '$blogTitle','$blogpicturename',
'$blogpicdata','$blogContent', '$dateAndTime');";
//if (
mysqli_query($connection, $result);
The connection IS established fine and all other data uploads to the phpmyadmin created database. I have omitted those details from the code.
Here is the answer:
$(function() {
$("#upload").click(function() {
// validate and process form here
tinyMCE.triggerSave();
var form = $('form')[0]; //
var formData = new FormData(form);
$.ajax({
type: "POST",
url: "functions/insertblogpost.php",
data: formData, // Data sent to server, a se
contentType: false,
cache: false, // To unable request pages to be cached
processData:false,
success: function() { ....................
If anybody has a similar issue please use this experience to help you.
Note - tinyMCE.triggerSave(); - sends the tinyMCE data. and this was my original issue with the - data: formData,
Ah well, shoot me down for asking!

jqgrid - copy row(s) with data from database

I'm trying to copy a row, but I'm using the data from a database, and I'm returning it with JSON. I'd like to know if it's possible to make a copy of a row, and if can I delimited the number of times that I can copy the rows. For example, I need to copy a row with id = 6, but I need to make 5 copies of this row. How can I do that?
You could make main work on server side not on client
In jqgrid decraration something like this:
grid.jqGrid({
...
loadComplete: function(data) {
var ids = grid.jqGrid('getDataIDs');
for (var i=0;i<ids.length;i++) {
var id=ids[i];
var rowData = thisGrid.jqGrid('getRowData', id);
grid.jqGrid('setCell', id, 'buttons', '<input type="button" class="copy" value="Copy">');
}
$('button.copy').click(function (e) {
var id = $(e.target).parents('tr')[0].id;
$.ajax({
url: 'some_url',
dataType : "json",
data: {'id': id},
timeout: 10000,
type: 'POST',
success: function (data) {
grid.trigger('reloadGrid');
},
});
});
}
....
});
In php part something like this
$array = array(
'success'=>false
);
if(isset($_POST['id])) {
if($db -> num_rows($q = $db->query("SELECT FROM ... WHERE `id` = ".intval($_POST['id'])) == 1) {
$row = $db -> fetch_assoc($q);
$db->query("INSERT INTO .....);
$array['success'] = true;
}
}
echo json_encode($array);
If you want to copy more than one time you could add some dialog on client side to input number of copies
use getRowData To Grab a Single row from jqgrid and then create an array by var s = new Array() and push the single row no of times you want ..
create a new column inside jqgrid .. using formatter Formatter In jQgrid place a link inside that column write handler for click over that link .. on that handler use getrowdata and grab the fields and then make a ajax call to send to the server...

Resources