passing ajax posting values in php laravel controller only one selected dropdown options array values are inserted so required two arrays of two selected drop list values to be inserted
get array of values
'$.ajax({
dataType: 'json',
url: "/getCity/"+id,
type: "GET",
success: function (data) {
console.log(data);
$('select[name="GLNO[]"]').empty();
$.each(data, function(key,data){
$('select[name="GLNO[]"]').append('<option value="'+ data.GLNO +'">'+ data.GLNO +'</option>');
});
$('select[name="NAME[]"]').empty();
$.each(data, function(key,data){
$('select[name="NAME[]"]').append('<option value="'+ data.NAME +'">'+ data.NAME +'</option>');
});
``
post array of values
$('#ProductForm').submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type: 'POST',
url: "{{ url('store-product') }}",
data: formData,
cache: false,
contentType: false,
processData: false,
success: (data) => {
$("#product-modal").modal('hide');
var oTable = $('#products').dataTable();
oTable.fnDraw(false);
$("#btn-save").html('Submit');
$("#btn-save").attr("disabled", false);
},
error: function(data) {
console.log(data);
}
});
});
form of multiple selected dropdown
<div class="form-group">
<label for="name" class="col-sm-2 control-label">GLNO</label>
<div class="col-sm-12">
<select name="GLNO[]" multiple id="glno" class="form-control" >
<option value=""></option>
</select>
</div>
</div>
<div class="form-group">
<label for="name" class="col-sm-2 control-label">GLNO</label>
<div class="col-sm-12">
<select name="NAME[]" multiple id="name" class="form-control" >
<option value=""></option>
</select>
</div>
</div>
controller of store
public function store(Request $request)
{
$productId = $request->id;
$request->validate([
'fmcode',
'fmcodes',
'area',
'naoffm','glno','frmdate',
'todate'
]);
$input = $request->all();
$products=$request->GLNO;
foreach ((array)$products as $product1) {
$product = Product::updateOrCreate(
[
'id'=> $productId ,
'fmcode' => $request->FMCODE,
'fmcodes' => $request->FMCODES,
'area' => $request->AREA,
'naoffm' => $request->NAOFFM,
'frmdate' => $request->frmdate,
'todate' => $request->todate,
'glno'=>$product1
]
);
}
return Response()->json($product);
}'
inserting two array multiple selected dropdown list values its showing error of inserting values so how we can pass values in for each loop for two request of values
Related
In my Laravel-5.8, I passed data from controller to view using JSON.
public function findScore(Request $request)
{
$userCompany = Auth::user()->company_id;
$child = DB::table('appraisal_goal_types')->where('company_id', $userCompany)->where('id',$request->id)->first();
if(empty($child))
{
abort(404);
}
$maxscore2 = 1;
$maxscore = DB::table('appraisal_goal_types')->select('max_score')->find($child->parent_id);
return response()->json([
'maxscore' => $maxscore,
'maxscore2' => $maxscore2
]);
}
Route
Route::get('get/findScore','Appraisal\AppraisalGoalsController#findScore')
->name('get.scores.all');
View
<form action="{{route('appraisal.appraisal_goals.store')}}" method="post" class="form-horizontal" enctype="multipart/form-data">
{{csrf_field()}}
<div class="card-body">
<div class="form-body">
<div class="row">
<div class="col-12 col-sm-6">
<div class="form-group">
<label class="control-label"> Goal Type:<span style="color:red;">*</span></label>
<select id="goal_type" class="form-control" name="goal_type_id">
<option value="">Select Goal Type</option>
#foreach ($categories as $category)
#unless($category->name === 'Job Fundamentals')
<option hidden value="{{ $category->id }}" {{ $category->id == old('category_id') ? 'selected' : '' }}>{{ $category->name }}</option>
#if ($category->children)
#foreach ($category->children as $child)
#unless($child->name === 'Job Fundamentals')
<option value="{{ $child->id }}" {{ $child->id == old('category_id') ? 'selected' : '' }}> {{ $child->name }}</option>
#endunless
#endforeach
#endif
#endunless
#endforeach
</select>
</div>
</div>
<input type="text" id="max_score" value="max_score" class="form-control" >
</form>
<script type="text/javascript">
$(document).ready(function() {
$(document).on('change', '#goal_type', function() {
var air_id = $(this).val();
var a = $(this).parent();
console.log("Its Change !");
var op = "";
$.ajax({
type: 'get',
url: '{{ route('get.scores.all') }}',
data: { 'id': air_id },
dataType: 'json', //return data will be json
success: function(data) {
console.log(data.maxscore);
console.log(data.maxscore2);
$('#max_score').val(data.maxscore);
},
error:function(){
}
});
});
});
</script>
When I click on the dropdown on change, I got these:
Console:
textbox:
I need the direct value to be displayed on the text and not the JSON object as shown in the diagram. For example, only the 75 in the textbox.
How do I get this resolved?
Thank you.
You're seeing this result because maxscore is an object. You can either reference maxscore.max_score from JavaScript when adding to the element, or you can alternatively look at your eloquent code. You can likely replace the ->find() with calls to ->where() and ->first() as you did with $child
You can access the inner elements using something like this, or at least have an idea , and then you can print the elemet you need from the array...
var selectedValue = max_score.options[max_score.selectedIndex].innerHTML;
var arreglo = selectedValue.split(' ');
var arreglo1 = arreglo[0];
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()
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>
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!
I want to post a record in SQL using Ajax without using a form but I have trouble:
method not allowed
<input type="text" name="name" value=" 2" />
<input type="text" value="detail" />
<input type="hidden" name="_Token" value="{{ csrf_token() }}">
<input type="button" onclick="add()" value="Submit Comment" />
Here is my controller:
class Cdesigination extends Controller
{
public function index()
{
$insertData = array(
"name" => Input::get("name"),
"detail" => Input::get("detail"),
"token_key" => Input::get("_token")
);
return view('company');
}
public function product()
{
$record = array(
"p_name" => Input::get("name"),
"p_price" => Input::get("price"),
"p_detail" => Input::get("detail")
);
return view('product');
}
}
The route is:
Route::post('add', ['as' => 'addrecord', 'uses' => 'Cdesigination#index']);
Ajax Function:
function add()
{
var name = $('#name').val();
var detail = $('#detail').val();
var token = $('#_token').val();
$.ajax({
type: 'POST',
url: '{{url("/posts")}}',
data: "name=" + name + "&detail=" + detail + "&_token=" + token,
success: function(data){ }
});
}
Where is my mistake? Please guide me and explain how to post record in Laravel without using a form.
your url is: {url("/posts")} and you haven't this route defined