I am new to laravel framework. I want to complete a important task in my app.
In that app they have modules like invoices,quotes,payment,customers. for particular customers they have multiple invoices with status of sent and partially paid.
Here is the receipt page, on type of customer name it will get autosuggestion from customer table. Onclick of cutomer name it will get invoice details from (invoice table) based on customer id,and need to show on table below that customer name textbox, onclick of table invoice it will open modal which means if the particular customer has unpaid invoice they need to record payment else proceed with normal receipt creation.
I try the code like this, But I am not getting proper output please anyone help me to get out of this issue.
<input type="text" name="customername" required="required" id="cust" placeholder="Customer Name" class="form-control col-md-7 col-xs-12 typeahead"/>
$( function() {
$( "#cust" ).autocomplete({
//source: "http://www.duminex.com/client/search",
source: "{{route('search.client')}}",
select: function( event, ui ) {
get_invoices(ui.item.id);
$('#id').val(ui.item.id);
$('#clientAddress').val(ui.item.address);
}
});
} );
function get_invoices(client_id)
{
$.ajax({
method: 'GET',
url: "{{route('client.details')}}"
}).done(function(data){
alert(data);
});
}
routes
Route::get('/client/search',[
'uses'=>'ClientsController#search',
'as'=>'search.client'
]);
Route::get('/client/search2', 'ClientsController#search2')->name('client.details');
Controller
public function search(Request $request)
{
$s= Input::get('term');
$clients = Client::select("id" ,"user_id", "companyname", "companyaddress" , "billingAddress")->where('companyname','like','%'.$s.'%')->where('user_id',Auth::user()->id)->get();
if(count($clients) == 0){
$searchResult[] = "No Item found";
}
else{
foreach ($clients as $key => $value) {
$searchResult[] = ['id' => $value->id, 'value' => $value->companyname , 'email' => $value->companyaddress , 'address' => $value->billingAddress];
}
}
return $searchResult;
}
public function search2(Request $request)
{
$clients = Invoice::select("invoiceNo")->where('status',['sent,Partially paid'])->where('client_id',$request->client_id)->get();
if(count($clients) == 0){
$searchResult[] = "No Item found";
}
else{
foreach ($clients as $key => $value) {
$searchResult[] = ['invoiceNo' => $value->invoiceNo];
}
}
return $searchResult;
}
Thanks in advance. Please anyone to help me get out of this issue.
You are not passing any data to the ajax so thats why you are not getting any result.
Try below code :
function get_invoices(client_id) {
$.ajax({
method: 'GET',
data : {
client_id: client_id
},
url: "{{route('client.details')}}"
}).done(function(data){
alert(data);
});
}
Related
I'm working on a Laravel PHP site, and am getting an error when trying to add a user to a cell in a table
The error says:
An error has occurred adding your contact. If the problem persists, please contact us.
and is displayed in a red 'ribbon' that pops up just below the browser address bar for a few seconds when trying to select a new user from the drop down.
I have seen a couple of similar questions on SO, but can't see how any of the answers apply to what's going on here...
In the HTML, the table column whose cell value I am trying to update is done via a form that pops up in a dialog box when pressing the 'Edit' icon in the cell:
<div class="provTaxContacts__row">
<form [formGroup]="newContactForm" class="provTaxContacts__col provTaxContacts__new-contact">
<label>Add new contact</label>
<div class="provTaxContacts__new-contact-fields">
<input class="provTaxContacts__new-contact-field provTaxContacts__name" [class.error]="newContactFormErrors.contactFirstName" placeholder="First name" type="text" autocomplete="given-name" formControlName="contactFirstName" />
<input class="provTaxContacts__new-contact-field provTaxContacts__name" [class.error]="newContactFormErrors.contactLastName" placeholder="Last name" type="text" autocomplete="family-name" formControlName="contactLastName" />
<input class="provTaxContacts__new-contact-field provTaxContacts__email" [class.error]="newContactFormErrors.contactEmail" placeholder="Email address" type="email" autocomplete="email" formControlName="contactEmail" />
<button class="btn btn-primary provTaxContacts__new-contact-button" type="button" (click)="onNewContactAdd(taxpayer.accountId)">Add contact</button>
<div *ngIf="addContactLoading" class="spinner-loading"></div>
</div>
</form>
</div>
The onNewContactAdd() function that's called when pressing the 'Add Contact' button is defined in a Typescript file called tax-reminder.ts, and as well as handling what happens to the browser on the front-end, it also calls the function addUserToAccount() from user.service.ts. It is what's displaying the error in the browser, and is defined with:
onNewContactAdd(accountId: number) {
const firstName = this.newContactForm.get('contactFirstName').value;
const lastName = this.newContactForm.get('contactLastName').value;
const email = this.newContactForm.get('contactEmail').value;
// Reset error states
this.resetContactFormErrors();
// Check for form errors
if (!firstName || Validate.isEmpty(firstName) || !Validate.lettersAndSpaces(firstName)) {
this.newContactFormErrors.contactFirstName = true;
} else {
this.newContactFormErrors.contactFirstName = false;
}
if (!lastName || Validate.isEmpty(lastName) || !Validate.lettersAndSpaces(lastName)) {
this.newContactFormErrors.contactLastName = true;
} else {
this.newContactFormErrors.contactLastName = false;
}
if (Validate.isEmpty(email) || !Validate.emailRegex.test(email)) {
this.newContactFormErrors.contactEmail = true;
} else {
this.newContactFormErrors.contactEmail = false;
}
// If there are any errors at this stage, Don't add
if (this.newContactFormErrors.contactFirstName || this.newContactFormErrors.contactLastName || this.newContactFormErrors.contactEmail) {
return
}
// Reset errors, just in case there were previous erros that we now know have been resolved
this.resetContactFormErrors();
this.addContactLoading = true;
// If all is valid, send a request to create the new contact
this.userService.addUserToAccount([{firstName, lastName, email, role: 'FULL'}], 'FULL', accountId)
.subscribe(
(response: any) => {
this.addContactLoading = false;
// Reset the add contact form so that the user can add more
this.newContactForm.patchValue({
contactFirstName: '',
contactLastName: '',
contactEmail: '',
});
// If the new contact's email address is already in the on-page list do nothing
if (_.find(this.contacts[accountId], {email})) {
return;
} else {
// If the request is succcessful, add the new contact to the list of contacts
this.contacts[accountId].push({
accountId,
email,
firstName,
groupTag: 'FULL',
lastName,
provTaxManager: 0,
provTaxPaymentsContact: 0,
userId: response.userId,
//transactionContactId,
});
}
},
error => {
console.log("Error: " + error);
const message = new Message();
message.type = MessageType.ERROR;
message.message = 'An error has occurred adding your contact. If the problem persists please contact us.';
this.messagingService.emitMessage(message);
}
)
}
In the browser console, I can see the following output in the Network-> Preview tab:
array:9 [
"userId" => 9561
"title" => null
"firstName" => "Shane"
"lastName" => "Williams"
"workPhone" => null
"mobilePhone" => null
"email" => "shane#williams.com"
"userTypeId" => 3
"login" => array:3 [
"loginId" => 9449
"loginName" => "shane#williams.com"
"userId" => 9561
]
]
Which shows that the details I entered into the form have been collected, and a new user ID has been assigned.
That output is coming from a dd() I have in the addAccountUser() PHP function:
public function addAccountUser( AddAccountUsersRequest $request )
{
$users = $request->input('users');
$type = $request->input('type');
$accountId = $request->input('accountId');
$userType = $type == 'taxfirm-agent' ? UserType::where('userTypeTag', 'AGENT')->first() : UserType::where('userTypeTag', 'DIRECT')->first();
$messages = array();
$hasWarningMessages = false;
try
{
DB::beginTransaction();
foreach ($users as $userRaw)
{
$details = array(
'firstName' => $userRaw['firstName'],
'lastName' => $userRaw['lastName'],
'email' => $userRaw['email'],
'password' => uniqid(),
'userTypeId' => $userType->userTypeId,
'accountId' => (!empty($accountId)) ? $accountId : null
);
$propertyValues = array();
// Adding tax agent
if ($type == 'taxfirm-agent') {
$group = $userRaw['role'];
$rv = $this->addTaxfirmAgent($details, $group);
}
else if($type == 'taxfirm-direct') {
$rv = $this->addTaxfirmDirectContact($details);
}
else {
$group = $userRaw['role'];
$rv = $this->addTaxpayerDirectContact($details, $group);
}
DB::commit();
dd($rv['user']->toArray());
if ($rv['status'] !== 'SUCCESS') {
if (!isset($messages[$rv['status']])) {
$messages[$rv['status']] = array(
'message' => StatusMessage::getMessage($rv['status']),
'data' => [],
//dd($messages);
);
}
$messages[$rv['status']]['data'][] = [$userRaw['email'], ucfirst($userRaw['firstName']), ucfirst($userRaw['lastName'])];
//dd($messages); // success is true at this point, users are null
if (!$hasWarningMessages)
{
$hasWarningMessages = true;
}
}
}
}
catch(\Exception $e)
{
DB::rollback();
return response()->json(array(
'success' => false,
'exceptionCode' => $e->getCode(),
'exceptionMessage' => $e->getMessage().' - '.$e->getFile().' - '.$e->getLine(),
'userId' => $userId // Try returning the userId too...
), 400);
}
$outputMsg = array();
foreach ($messages as $value) {
$outputMsg[] = $value;
}
//dd($users);
return response()->json(array(
'success' => true,
'hasWarningMessages' => $hasWarningMessages,
'result' => $outputMsg,
//'users' => $rv['user']->user, /*ERF(18/09/2018 # 1630) Change to userId */
'userId' => $rv['user']->userId,
));
}
I don't fully understand how the JavaScript, PHP & HTTP are all interacting here, or why the PHP debug appears to be showing the new contact created successfully, and yet I still get the error in the browser.
Can anyone point me in the right direction here? Why is the contact seemingly created, and yet I get the error, as well as the contact not being displayed in the drop down box as I am expecting?
Edit
So, I think that the issue I'm having here is not to do with the PHP itself- as that function seems to be returning the correct information (the console output given when I added the line dd($rv['user']->toArray()) at the end of the function showed all of the details for the user I had just added correctly), but rather to do with the Angular that should be updating the front end, to display the new user in the drop down.
That function is defined as follows:
this.userService.addUserToAccount([{firstName, lastName, email, role: 'FULL'}], 'FULL', accountId)
.subscribe(
(response: any) => {
this.addContactLoading = false;
// Reset the add contact form so that the user can add more
this.newContactForm.patchValue({
contactFirstName: '',
contactLastName: '',
contactEmail: '',
});
// If the new contact's email address is already in the on-page list do nothing
if (_.find(this.contacts[accountId], {email})) {
return;
} else {
// If the request is succcessful, add the new contact to the list of contacts
this.contacts[accountId].push({
accountId,
email,
firstName,
groupTag: 'FULL',
lastName,
provTaxManager: 0,
provTaxPaymentsContact: 0,
userId: response.userId,
//transactionContactId,
});
}
},
error => {
console.log("Error: " + error);
const message = new Message();
message.type = MessageType.ERROR;
message.message = 'An error has occurred adding your contact. If the problem persists please contact us.';
this.messagingService.emitMessage(message);
}
)
I think I need to add a call to reload this page element at the end of the else statement in this function... How would I do that?
Edit
So, it seems that although the contact appears to be created, the HTTP response I'm getting is actually the error- as I can see the An error has occurred adding your contact. If the problem persists please contact us. message in the browser... Why is it that the HTTP response is failing? How can I resolve this?
I added a console.log() to display the error in the console, and it's showing the following output:
unparsable response
Error: SyntaxError: Unexpected token < in JSON at position 0
I don't understand where this error is coming from... any ideas?
I have a view in which I have a detailview and a gridview. In my grid view there are check-boxes against all the columns. The detail view contains the model id. Now the case is simple, I want to select any column from the grid view and then on click of the a link button I want to send the ajax call, which includes the value of selected column and the model id, to my controller. Below is my view
<?= GridView::widget([
'dataProvider' => $dataProvider,
/*'filterModel' => $searchModel,*/
'columns' => [
['class' => 'yii\grid\CheckboxColumn', 'checkboxOptions' => function($d) {
return ['value' => $d['meter_id']];
}],
'Meter_Serial_Number',
'Issued_To',
'Store',
],
]); ?>
Set PDF
Now the javascript and the ajax call
<?php
$url = Url::toRoute(['/ogpheader/viewsetpdf','id'=>$model->id]);
$script = <<< JS
$(document).ready(function () {
$('#myid').on('click',function() {
var strValue = "";
$('input[name="selection[]"]:checked').each(function() {
if(strValue!="")
{
strValue = strValue + " , " + this.value;
}
else
strValue = this.value;
});
// alert(strValue);
$.ajax({
url: '$url',
type: 'POST',
data: {
data: strValue,// also tired with {strValue:strValue id:id} but it did not worked for me as well
},
success: function(data) {
alert(data);
},
});
})
});
JS;
$this->registerJs($script, static::POS_END);
?>
Action Controller
public function actionViewsetpdf($id)
{
$model = $this->findModel($id);
print_r($_POST);
$data = "";
if(Yii::$app->request->isAjax)
{
$data = json_decode($_POST['data']);
print_r($data);
}
else{
echo 'no data';
}
exit();
}
The response i always got is Array ( ) no data. I have also looked into Passing two parameters in yii2 ajax request using jquery to a controller and Yii2 extra parameter ajax in controller but both seems to be helpful in my case.
Note:
As per my understanding the id is a get and strValue is post. So I am confused in both of them. May be I am wrong.
Update 1
Image quality is not that good
The response in Xhr is
array(1) {
["data"]=>
array(1) {
["data"]=>
string(26) "99 , 100 , 101 , 102 , 103"
}
}
Any help would be highly appreciated.
Prevent the default click event
$('#myid').on('click',function(e) {
e.preventDefault();
i have two tables user and department where department has two fields id and name i want to create a view so that when someone selects a department name from the dropdownlist the user's name of all in that department show in another dropdownlist using AJAX and How to call that in controller
<script>
jQuery(document).ready(function ($) {
//jQuery('#searchTable').dataTable();
$('#department_id').change(function () {
jQuery('#user').empty();
var data2 = {};
data2['department_id'] = jQuery(this).val();
var json = JSON.stringify(data2);
jQuery.ajax({
type: "POST",
url: "/AjaxRequests/name",
data: json,
dataType: "json",
success: function (response) {
var app = "<option value>All</option>";
jQuery('#user').append(app);
jQuery.each(response, function (i, text) {
jQuery('#user').append(jQuery('<option></option>').val(i).html(text));
});
}
});
});
</script>
this is the script i am using
and in view the department dropdown is like this
<?php echo $this->Form->input('department_id', array('onChange' => 'showFields(this.value)', 'class' => 'form-control-custom', 'id' => 'department_id', 'type' => 'select', 'label' => true, 'label' => 'department:', 'options' => $departments, 'empty' => 'Select A Department', 'required' => 'false'))
?>
Anyone please help me with this ajax and also the controller
According to your code, can u try to replace 'id' => 'department' with 'id' => 'department_id' . Cause it's seen here you are using department_id as selector but your department_id id as not declared in dropdownlist. Here you declared department as ID. So selector is not found. So Just replace 'id' => 'department' with ''id' => 'department_id'', Hope it can be helpful to you.
I need help with saving a drag n drop menu order. I use http://farhadi.ir/projects/html5sortable to drag and update the list. Each menu item has two hidden fields: id and order. The order is updated dynamically when dropped. I don't know how to turn the fields id and order into a correct array so I can update via AJAX into Laravel.
HTML - Menu :
<div>
<input name="menu[1][id]" type="hidden" value="1">
<input name="menu[1][order]" class="new-order" type="hidden" value="3">
</div>
<div>
<input name="menu[2][id]" type="hidden" value="2">
<input name="menu[2][order]" class="new-order" type="hidden" value="4">
</div>
<div>
<input name="menu[3][id]" type="hidden" value="3">
<input name="menu[3][order]" class="new-order" type="hidden" value="5">
</div>
jQuery - Drag/drop, update order value then send via ajax :
// Sortable options
$('.nav-pages__items').sortable({
handle: '.nav-pages__drag',
items: ':not(.home)'
}).bind('sortupdate', function() {
// When dropped clear list order
$(this).find('input[name=menu]').attr('value', '');
// Then update list order
$('.nav-pages__items li:not(.home)').each(function(i, element) {
element = i+1;
$(this).find('input.new-order').attr('value'),
$(this).find('input.new-order').attr('value', + element);
});
// !! Somehow create array to send/save !!
// Ajax to send
$.post('/menu-update', {
_token: token,
id: id,
order: order
}, function(data) {
if (data.status == 'success') {
console.log('success: ', data);
} else if (data.error == 'error') {
console.log('error: ', data);
};
});
});
PHP/Laravel - Not got this far (without errors):
public function update()
{
$menu = Input::all();
$save = Page::where('id', $menu['id'])->update([
'order' => $menu['order']
]);
if ($save) {
$response = [
'status' => 'success',
'msg' => 'Message here',
'id' => $menu['id'],
'order' => $menu['order'],
];
};
return Response::json($response);
}
To summarise:
Get the id and order for each field group
Loop though them in js and crate correct array
Send array to Laravel and update order based on id
Also, if there's a much simpler way to do this, I'm all ears.
I don't believe you need those hidden inputs -- what about something like:
jQuery:
// Sortable options
$('.nav-pages__items').sortable({
handle: '.nav-pages__drag',
items: ':not(.home)'
}).bind('sortupdate', function() {
// Collect the new orderings
var newOrders = [];
$('.nav-pages__items li:not(.home)').each(function(i, element) {
var id = $(element).data('id'); // Set a data-id attribute on each li
var order = i;
newOrders[order] = id;
});
// Ajax to send
$.post('/menu-update', {
_token: token,
newOrders: newOrders
}, function(data) {
if (data.status == 'success') {
console.log('success: ', data);
} else if (data.error == 'error') {
console.log('error: ', data);
};
});
});
PHP/Laravel:
public function update()
{
$responses = [];
foreach (Input::get('newOrders') AS $order => $id) {
$save = Page::where('id', $id)->update([
'order' => $order
]);
if ($save) {
$response[$id] = [
'status' => 'success',
'msg' => 'Message here',
'id' => $id,
'order' => $order,
];
}
}
return Response::json($responses);
}
After reviewing many tutorials and various approaches to Cascading DropDownLists, I decided to create a ViewModel for my View and then populate my DropDownLists based on this post:
MVC3 AJAX Cascading DropDownLists
The goal here is the most basic and covered in many tutorials, but I still can't get it quite right... to populate a City dropdown based on the value of a State dropdown.
EDIT:
Since posting this request for help, I discovered Firebug (yes, that's how new I am to doing any sort of programming), and I was able to determine that I am successfully calling my controller, and pulling the necessary data. I believe the problem is the second half of my JavaScript that returns the data to my View.
Here is my View:
<label>STATE HERE:</label>
#Html.DropDownListFor(x => x.States, Model.States, new { #class = "chzn-select", id = "stateID" })
<br /><br />
<label>CITY HERE:</label>
#Html.DropDownListFor(x => x.Cities, Enumerable.Empty<SelectListItem>(), new { id = "cityID" })
Here is the JavaScript within my View, and somehow I'm not handling my results correctly once I get them:
$(function () {
$("#stateID").change(function () {
var stateId = $(this).val();
// and send it as AJAX request to the newly created action
$.ajax({
url: '#Url.Action("GetCities")',
type: 'GET',
data: { Id: stateId },
cache: 'false',
success: function (result) {
var citySelect = $('#cityID');
$(citySelect).empty();
// when the AJAX succeeds refresh the ddl container with
$.each(result, function (result) {
$(citySelect)
.append($('<option/>', { value: this.simpleCityID })
.text(this.cityFull));
});
},
error: function (result) {
alert('An Error has occurred');
}
});
});
});
Here is my controller called by the JavaScript:
public JsonResult GetCities(int Id)
{
return Json(GetCitySelectList(Id), JsonRequestBehavior.AllowGet);
}
private SelectList GetCitySelectList(int Id)
{
var cities = simpleDB.simpleCity.Where(x => x.simpleStateId == Id).ToList();
SelectList result = new SelectList(cities, "simpleCityId", "cityFull");
return result;
}
Here are my results from Firbug, which tell me I'm building and getting the data without issue, just not populating my DropDownList correctly:
[{"Selected":false,"Text":"Carmel","Value":"IN001"},{"Selected":false,"Text":"Fishers","Value":"IN002"}]
If anyone has any suggestions as to why the JavaScript fails to populate the dropdrown, please comment, thanks!
I have done this several times with something like this:
Create a partial to popolate dropdown list. Name it DropDownList and put in Shared folder of Views
#model SelectList
#Html.DropDownList("wahtever", Model)
Your create view should be something like this (skipped irrelevant parts)
<script type="text/javascript">
$(function() {
$("#StateId").change(function() {
loadLevelTwo(this);
});
loadLevelTwo($("#StateId"));
});
function loadLevelTwo(selectList) {
var selectedId = $(selectList).val();
$.ajax({
url: "#Url.Action("GetCities")",
type: "GET",
data: {stateId: selectedId},
success: function (data) {
$("#CityId").html($(data).html());
},
error: function (result) {
alert("error occured");
}
});
}
</script>
#Html.DropDownList("StateId")
<select id="CityId" name="CityId"></select>
Carefully note the Empty Select item for CityId and the call of loadLevelTwo at document.ready
And your controller should be like:
public ActionResult Create()
{
ViewBag.StateId = new SelectList(GetAllCities(), "Id", "Name");
return View();
}
public ActionResult GetCities(int stateId) {
SelectList model = new SelectList(GetCitiesOfState(stateId), "Id", "Name");
return PartialView("DropDownList", model);
}
Thank you for your assistance,
It turns out that in my JavaScript below, I was attempting to directly reference the simpleCityID and cityFull fields associated with my data model:
$.each(result, function (result) {
$(citySelect)
.append($('<option/>', { value: this.simpleCityID })
.text(this.cityFull));
Instead, I needed to keep it generic and inline with JavaScript standards of referencing Value and Text:
$.each(modelData, function (index, itemData) {
select.append($('<option/>', {
value: itemData.Value,
text: itemData.Text