Laravel dependent select boxes with Ajax - json

I created 3 dependent select boxes in Laravel with Ajax (a reproduction of the code from the original project in wich I use MySQL instead of array): https://github.com/grigore16/laravel_select_boxes. It has only one view and one controller.
It generally works fine, but if I refresh multiple times, I get 500 Internal Server Error (in Chrome's console) and from jQuery I see the error is: xhr.send( options.hasContent && options.data || null ). In a slower computer the error is more often.
Please tell me if the code is ok or not!
This is the view:
<table class='table table-bordered'>
<tr>
<td>Country</td>
<td>City</td>
<td>Street</td>
</tr>
<tr>
<td>
<select id="country" name="country">
<option selected>Germany</option>
</select>
</td>
<td>
<select id="city" name="city">
<option selected>Hamburg</option>
</select>
</td>
<td>
<select id="street" name="street">
<option selected>h1</option>
</select>
</td>
</tr>
</table>
<div>
<script>
var present_country = 'Germany';
var present_city = 'Hamburg';
var present_street = 'h1';
$(document).ready(function(){
$.ajax({
url: 'http://localhost/laravel_select_boxes/public/ajax',
method: "GET",
data: {countries:'test'},
success: function (data) {
$(data.countries).each(function(index, country) {
if(country !== present_country){
$("#country").append(new Option(country));
}
});
var country = $('#country').val();
$.ajax({
url: 'http://localhost/laravel_select_boxes/public/ajax',
method: "GET",
data: {country:country},
success: function (data) {
$(data.cities).each(function(index, city) {
if(city !== present_city){
$("#city").append(new Option(city));
}
});
var city = $('#city').val();
$.ajax({
url: 'http://localhost/laravel_select_boxes/public/ajax',
method: "GET",
data: {city:city},
success: function (data) {
$(data.streets).each(function(index, street) {
if(street !== present_street){
$("#street").append(new Option(street));
}
});
}
});
}
});
}
});
$("#country").change(function() {
$('#city').empty();
$('#street').empty();
var country = $('#country').val();
$.ajax({
url: 'http://localhost/laravel_select_boxes/public/ajax',
method: "GET",
data: {country:country},
success: function (data) {
$(data.cities).each(function(index, city) {
$("#city").append(new Option(city));
});
var city = $('#city').val();
$.ajax({
url: 'http://localhost/laravel_select_boxes/public/ajax',
method: "GET",
data: {city:city},
success: function (data) {
$(data.streets).each(function(index, street) {
$("#street").append(new Option(street));
});
}
});
}
});
});
$("#city").change(function() {
$('#street').empty();
var city = $('#city').val();
$.ajax({
url: 'http://localhost/laravel_select_boxes/public/ajax',
method: "GET",
data: {city:city},
success: function (data) {
$(data.streets).each(function(index, street) {
$("#street").append(new Option(street));
});
}
});
});
});
</script>
and this is the controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class AjaxController extends Controller
{
public function index(Request $request)
{
if($request['countries']){
$countries = ['Germany', 'France'];
return response()->json(['countries'=>$countries]);
}
if($request['country']){
if($request['country'] === 'Germany'){
$cities = ['Hamburg', 'Berlin'];
}
if($request['country'] === 'France'){
$cities = ['Paris', 'Lion'];
}
return response()->json(['cities'=>$cities]);
}
if($request['city']){
if($request['city'] === 'Hamburg'){
$streets = ['h1', 'h2', 'h3'];
}
if($request['city'] === 'Berlin'){
$streets = ['b1', 'b2', 'b3'];
}
if($request['city'] === 'Paris'){
$streets = ['p1', 'p2', 'p3'];
}
if($request['city'] === 'Lion'){
$streets = ['l1', 'l2', 'l3'];
}
return response()->json(['streets'=>$streets]);
}
}
}
Thank you very much!

Related

Laravel- Auto fill input after selecting value from dropdown

how to do the auto fill after select the dropdown list. I'm not really good in js or ajax.
When user select doc_no then both rev_no and title field must be filled up. Thanks!
View
<div class="form-group">
{!! Form::label('text', 'Doc No', ['class' => 'col-lg-3 control-label']) !!}
<div class="col-lg-10">
<select name="docNo" id="docNo" class="form-control" style="width:250px">
#foreach ($soplists as $soplist)
<option value="{{ $soplist->id }}">{{ $soplist->doc_no }}</option>
#endforeach
</select>
</div>
</div>
<input type="hidden" name="carType" value="Internal Audit" class="form-control">
<div class="form-group">
{!! Form::label('text', "Rev No", ['class' => 'col-lg-5 control-label']) !!}
<div class="col-lg-5">
<input type="text" class="form-control" id="rev" />
</div>
</div>
<div class="form-group">
{!! Form::label('text', "Title", ['class' => 'col-lg-5 control-label']) !!}
<div class="col-lg-10">
<input type="text" class="form-control" id="title" />
</div>
<script>
$('#docNo').change(function() {
var id = $(this).val();
var url = '{{ route("getDetails", ":id") }}';
url = url.replace(':id', id);
$.ajax({
url: url,
type: 'get',
dataType: 'json',
success: function(response) {
if (response != null) {
$('#rev').val(response.rev_no);
$('#title').val(response.title);
}
}
});
});
</script>
Controller
---php
public function getDetails($id = 0)
{
$data = sopList::where('doc_no', $id)->first();
echo json_encode($data);
exit;
}
Route
'Route::get('get/details/{id}', 'internalAuditController#getDetails')->name('getDetails');'
Database sop_list table image link
https://ibb.co/SwkJhLc
Dropdown and input image
https://ibb.co/0VN3Z2y
Network tab
https://ibb.co/56w5BLD
Add a route in web.php file:
Route::get('get/details/{id}', 'YourController#getDetails')->name('getDetails');
Controller Function:
public function getDetails($id = 0)
{
$data = sopList::where('doc_no',$id)->first();
return response()->json($data);
}
And in view the script:
$('#docNo').change(function(){
var id = $(this).val();
var url = '{{ route("getDetails", ":id") }}';
url = url.replace(':id', id);
$.ajax({
url: url,
type: 'get',
dataType: 'json',
success: function(response){
if(response != null){
$('#rev').val(response.rev_no);
$('#title').val(response.title);
}
}
});
});
Make sure to add the id rev and title to the rev and title input fields respectively.
you have to make a rout that returns what you need
for example
/**
* #return \Illuminate\Http\JsonResponse
*/
public function getCategories()
{
$category = Category::where('_id', request()->get('_id'))
->select(['name', '_id'])->first();
return response()->json($category);
}
then call it on change of your select box with ajax and show it every where you want
like this example:
$("#docNo").change(function () {
$.ajax({
url: "{{ route('getCategories') }}",
type: 'POST',
data: {
_token: "{{ csrf_token() }}",
_id: $(this).val()
},
success: function (data) {
var newOption = '';
$.each(data, function (k, category) {
newOption += '<option value="' + category.id + '">' + category.name + '</option>';
});
$('#parent').append(newOption);
},
error: function (error) {
console.log(error);
}
});
});
you can add onChange method on your docNo and then call do ajax call to get the rev_no and title and update the content via document.getElementById()

Why input value is NULL when using Ajax?(ASP.NET CORE)

I do not have access to input values when using Ajax in View(MVC) but I have access to input values when not use Ajax. actually values is empty when use Ajax
When I use Ajax:
<form id="Form1" asp-action="Register" asp-controller="UserPanel" method="post">
<div class="row">
<div class="col-lg-5 col-md-5 col-sm-12 col-12 .sm-right" id="margin-top">
<span>Name:</span>
<input type="text" asp-for="Name" class="form-control">
</div>
<div>
<span>Number:</span>
<input type="text" asp-for="Number" class="form-control">
</div>
</div>
<input type="reset" value="send" id="ajax-button" class="btn btn-success btn-sm waves-effect waves-light submit-btn" />
</form>
Script:
<script>
$(document).ready(function () {
var url = '#Url.Action("Register", "UserPanel")';
var data = $('#Form1').serialize();
$('#ajax-button').click(function () {
debugger
$.ajax({
type: "POST",
data: data,
url: url,
contentType: 'application/json; charset=utf-8',
success: function (result) {
alert('Done');
},
error: function () {
alert("error");
}
});
})
})
</script>
I added tag helpers
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
#addTagHelper *, SmsWebClient
#using Microsoft.AspNetCore.Razor.TagHelpers;
Value is null before enter to ajax ,image:
Please Move the
var data = $('#Form1').serialize();
to below
$('#ajax-button').click(function () {
In fact, your code should be:
<script>
$(document).ready(function () {
var url = '#Url.Action("Register", "UserPanel")';
$('#ajax-button').click(function () {
var data = $('#Form1').serialize();
debugger
$.ajax({
type: "POST",
data: data,
url: url,
success: function (result) {
alert('Done');
},
error: function () {
alert("error");
}
});
})
})
</script>
In your code data set when docuement loaded and for this reason the value
is null
You must write like this
<form id="Form1" asp-action="Register" asp-controller="UserPanel" method="post">
<div class="row">
<div class="col-lg-5 col-md-5 col-sm-12 col-12 .sm-right" id="margin-top">
<span>Name:</span>
<input type="text" asp-for="Name" class="form-control">
</div>
<div>
<span>Number:</span>
<input type="text" asp-for="Number" class="form-control">
</div>
</div>
<div class="form-group">
<button id="ajax-button">Submit</button>
</div>
</form>
And This ViewModel
public class RegisterVm
{
public string Name { get; set; }
public string Number { get; set; }
}
And finally this is the Ajax code
#section Scripts{
<script>
$(document).ready(function () {
var url = $('#Form1').attr("action");
var model = $('#Form1').serialize();
var token = $('input[name=__RequestVerificationToken]').val();
model.__RequestVerificationToken = token;
$('#ajax-button').click(function () {
$.ajax({
type: $('#Form1').attr("method"),
data: model,
url: url,
success: function (result) {
alert('Done');
},
error: function () {
alert("error");
}
});
})
})
</script>
}
Your data are set when docuement loaded, it will not pass the value which you enter.
For a working demo, try code below:
<script>
$(document).ready(function () {
$('#ajax-button').click(function () {
var url = '#Url.Action("Register", "Home")';
var data = new FormData();
data.append('Name', $('#Name').val());
data.append('Number', $('#Number').val());
$.ajax({
type: "POST",
data: data,
url: url,
processData: false,
contentType: false,
success: function (result) {
alert('Done');
},
error: function () {
alert("error");
}
});
})
})
</script>

pass a list of objects via ajax to a MVC controller always sends null

I am probably missing something very simple. I have been working on this for a day and an half now and can not get it to work. I am looping through a table and creating a list of objects to send back to my controller. For some reason I am always receiving a null value in my controller. Here is the java script.
var items = [];
$('#grid tr').each(function () {
var item = {};
item.numReceived = $(this).find("input[id*='NumReceived']").val();
/*skip the header row*/
if (item.numReceived !== null) {
item.transactionID = $(this).find("input[id*='item_TransactionID']").val();
items.push(item);
}
});
$.ajax({
url: './ReceivePOLines',
type: "Post",
cache: false,
data: JSON.stringify(items),
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function () {
window.location.replace("../Home/Index");
},
error: function (request) {
alert("error");
}
});
here is the method signature in the controller
[HttpPost]
public void ReceivePOLines(List<RecievedTransactions> inTransactions)
And here is the class ReceivedTransactions
public class RecievedTransactions{
public int numReceived { get; set; }
public int transactionID { get; set; }
}
Here are the results from Fiddler showing what was passed
[{},{"numReceived":"10000","transactionID":"10661768"},{"numReceived":"10000","transactionID":"10661769"},{"numReceived":"2000","transactionID":"10661770"},{"numReceived":"2500","transactionID":"10661771"},{"numReceived":"2500","transactionID":"10661772"},{"numReceived":"2000","transactionID":"10661773"},{"numReceived":"10000","transactionID":"10661774"}]
Any and all help appreciated.
cheers
bob
This is a new answer. Originally, I was getting null, like you. But, now it works the way you want (array of complex objects). Please get this to work for you. If you can't get it to work, although it should, I can create an ASP.NET Fiddle.
public class RecievedTransactions
{
public int numReceived { get; set; }
public int transactionID { get; set; }
}
public class HomeController : Controller
{
[HttpPost]
public void ReceivePOLines(List<RecievedTransactions> inTransactions) // MyArray MyArray
{
return;
}
//you use your own action name
public ActionResult Tut133()
{
return View();
}
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Tut132</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(function () {
var items = [];
$('#grid tr').each(function () {
var item = {};
item.numReceived = $(this).find("input[id*='NumReceived']").val();
/*skip the header row*/
if (item.numReceived !== null) {
item.transactionID = $(this).find("input[id*='item_TransactionID']").val();
items.push(item);
}
});
$.ajax({
//!!changing your url
//url: './ReceivePOLines',
url: "/Home/ReceivePOLines",
type: "Post",
cache: false,
//data: JSON.stringify({ MyArray: items }),
data: JSON.stringify(items),
//expecting back from server-need to remove since we are not getting back data from server
//dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function () {
//alerting success instead of opening window
alert("success");
//window.location.replace("../Home/Index");
},
error: function (request) {
alert("error");
}
});
})
</script>
</head>
<body>
<table id="grid">
<tr>
<td><input type="text" id="NumReceived1" value="10000" /></td>
<td><input type="text" id="item_TransactionID1" value="10661768" /></td>
</tr>
<tr>
<td><input type="text" id="NumReceived2" value="10000" /></td>
<td><input type="text" id="item_TransactionID2" value="10661769" /></td>
</tr>
</table>
<input type="button" id="theButton" value="Go" />
</body>
</html>

bootbox.confirm dose not display the message and page crashed

I'm new to bootstrap.I'm trying to show confirm message with bootbox format after click on delete btn .I know that bootbox.confirm need callback function so I utilize result and checked if its true then show it.I expect to see this: Are you sure to delete this customer? but after click noting happen and browser just freeze and I have to refresh it again.
this is all my code:
<h2>Customers</h2>
#Html.ActionLink("ADD New Customer", "CreatNewCustomer", "Customer", new { #class = "form-control" })
#if (!Model.Any())
{
<p> there is no customer</p>
}
else
{
<table id="Customers" class="table table-bordered table-hover">
<thead>
<tr>
<th>Customers</th>
<th>Discount Rate</th>
<th>Delete </th>
</tr>
</thead>
<tbody>
#foreach (var Customer in Model)
{
<tr>
#*<td>#Customer.Name</td>*#
<td>#Html.ActionLink(Customer.Name.ToString(),"Edit","Customer",new {id=Customer.CustomerID },null)</td>
<td>#Customer.MembershipType.MembershipName</td>
<td>
<button data-customer-id="#Customer.CustomerID" class="btn-link js-delete"> Delete</button>
</td>
</tr>
}
</tbody>
</table>
}
#section scripts
{
<script>
$(document).ready(function () {
$("#Customers .js-delete").on("click", function () {
bootbox.confirm("Are you sure to delete this customer?", function (result) {
if (result) {
var butten = $(this)
$.ajax({
url: "/api/customer/" + butten.attr("data-customer-id"),
method: "Delete",
success: function () {
console.log("success"),
butten.parents("tr").remove();
}
})
}
})
})
})
</script>
}
Main part is here:
<script>
$(document).ready(function () {
$("#Customers .js-delete").on("click", function () {
var butten = $(this);
bootbox.confirm("Are you sure to delete this customer?", function (result) {
if (result) {
$.ajax({
url: "/api/customer/" + butten.attr("data-customer-id"),
method: "Delete",
success: function () {
console.log("success"),
butten.parents("tr").remove();
}
})
}
})
})
})
</script>
I can't get what's wrong with that.
When I use bootbox.confirm my code not works but when I use confirm alon like this:
<script>
$(document).ready(function () {
$("#Customers .js-delete").on("click", function () {
var butten = $(this);
confirm("Are you sure to delete this customer?", function (result) {
if (result) {
$.ajax({
url: "/api/customer/" + butten.attr("data-customer-id"),
method: "Delete",
success: function () {
console.log("success"),
butten.parents("tr").remove();
}
})
}
})
})
})
</script>
my code works. I have installed bootbox version 4.3.0 and set in my bundle config like this :
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/bootbox.js",
"~/Scripts/respond.js"));
And I use vs 2017
Hope someone help me.
If you're trying to get a reference to the button that triggered the click event, you (still) are selecting the wrong item when doing this:
$(document).ready(function () {
var butten = $(this);
Where you have that line in your latest edit, you're selecting the document. What you need is:
$("#Customers .js-delete").on("click", function () {
// THIS is where you select the button...
var butten = $(this);
// ... the rest of your code
}
If you're struggling with this, I suggest spending some time on the jQuery Learning Center: https://learn.jquery.com/

AngularJS same html site for insert and update

This one is going to be a long one :)
So here is the idea, I wanna use same html page for two controllers , problem is , that page in insert state wont load , because of ng-repeat="employee in employee" because its non existent in insert controller.
What my repeater does it just fills textboxes , it doesnt repeat anything , its just a single form and it fills information of that one single employee , am i doing this wrong ?
employeeUpdate works like a charm , problem is in employeeInsert , is there a posibility that it can fill textboxes without ng-repeat part , because it does not work without it , but it does fill comboBox/select options without it.
.state('employeeUpdate', {
url: '/employeeUpdate?employeeCode=:param1',
templateUrl: 'pages/employeeUpdate.html',
controller: 'employeeUpdateCtrl',
resolve: {
employeeGatherAll: ['$http', function ($http) {
return $http.jsonp("webserviceSite&procedureName=wsEmployeeGatherAll 'param','param'&callback=JSON_CALLBACK")
.success(function (response) {
return (response)
}).error(function (response) {
console.log("failed");
});
}],
employeeSelectByCode: ['$http','$location', function ($http, $location) {
var employeeCode = $location.search().employeeCode
return $http.jsonp("webServiceSite&procedureName=wsEmployeeSelectByCode 'paramet','parame','" + employeeCode + "'&callback=JSON_CALLBACK")
.success(function (response) {
return (response)
}).error(function (response) {
console.log("failed");
});
}]
}
})
.state('employeeInsert', {
url: '/employeeInsert',
templateUrl: 'pages/employeeUpdate.html',
controller: 'employeeInsertCtrl',
resolve: {
employeeGatherAll: ['$http', function ($http) {
return $http.jsonp("webServiceSiteUrl&procedureName=wsEmployeeGatherAll 'parametar','parametar'&callback=JSON_CALLBACK")
.success(function (response) {
return (response)
}).error(function (response) {
console.log("failed");
});
}],
}
})
So i have selectView as well , where i list all employees, and on click i go to employeeUpdate where i send code trough url as well , my html employeeUpdate page looks something like this :
<div ng-repeat="employee in employee">
<div class="col-md-4">
<label>Employee code</label>
<input type="text" class="form-control" id="txtEmployeeCode" ng-model='employee.employeeCode' />
</div>
<div class="col-md-4">
<label>Status</label>
<select id="Select3" class="form-control" ng-model="employee.statusCode" ng-options="item.code as item.name for item in employeeGather.status">
<option value="">Select status</option>
</select>
</div>
</div>
And these are the controllers
angular
.module('app')
.controller('employeeUpdateCtrl', ['$scope', 'employeeGatherAll', 'employeeSelectByCode', function ($scope, employeeGatherAll, employeeSelectByCode) {
$scope.employee = employeeSelectByCode.data.employee;
$scope.employeeGather = employeeGatherAll.data
}])
.controller('employeeInsertCtrl', ['$scope', 'employeeGatherAll', function ($scope, employeeGatherAll) {
$scope.employeeGather = employeeGatherAll.data
}])
employee.SelectByCode.data.employee[0] was the soulution , without ng-repeat