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()
Related
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
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];
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>
lam trying to save replycomments to the database
here is my html form,
<div id="replyform" class="card my-4 d-none">
<h5 class="card-header">Cevap Yaz:</h5>
<div class="card-body">
<form>
<div class="form-group">
<textarea id="replytext" name="replytext" typeof="text" class="form-control" rows="3"></textarea>
</div>
<button type="submit" id="sendreply" name="sendreply" class="btn btn-primary">Cevap Yaz</button>
</form>
</div>
</div>
and here is my homecontroller action code
public JsonResult ReplyComment(string replycomment, int articleid,int commentid)
{
var UserId = Session["UserId"];
if (replycomment == null)
{
return Json(true, JsonRequestBehavior.AllowGet);
}
db.ReplyComments.Add(new ReplyComment
{ UserId = Convert.ToInt32(UserId), ArticleId = articleid, CommentId=commentid, Paragraph = replycomment, Date = DateTime.Now });
db.SaveChanges();
return Json(false, JsonRequestBehavior.AllowGet);
}
and my ajax code is here
<script type="text/javascript">
$(document).ready(function () {
$("#sendreply").click(function () {
var r_comment = $("#replytext").val();
var r_commentid = $(".astar").val();
$.ajax({
cache: false,
url: '#Url.Action("ReplyComment","Home")',
contentType: "application/json; charset=utf-8",
data: { replycomment: r_comment, articleid:#Model.ArticleId, commentid: r_commentid },
type: 'POST',
dataType: 'json',
success: function (data) {
alert("İşlemOkey");
}
});
});
})
l cant call the Replycomment action with this code
I have tested this code and it will work for you. since am posting via ajax, i have removed the form tags from the body of the html.
For backend(php), I just test it by sending variables r_comment and r_commentid and it works fine. it should work with your backend code now. Give me a shout if it works for you...........
<html>
<head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#sendreply").click(function () {
var r_comment = $("#replytext").val();
var r_commentid = $(".astar").val();
var articleid = '20';
/* lets test with data
var r_comment ='my comment';
var r_commentid = '20';
*/
$('#loader').fadeIn(400).html('Data is being processed');
// assuming that you want query result by posting a variable
var datasend = "r_comment="+ r_comment + "&r_commentid=" + r_commentid + "&articleid=" + articleid;
$.ajax({
type:'POST',
url:'smoke1.php',
data:datasend,
crossDomain: true,
cache:false,
success:function(msg){
//display image loader or text to alert the use that content is being processed
$('#loader').hide();
// and display result
alert("İşlemOkey");
$('#result').fadeIn('slow').prepend(msg);
}
});
})
});
</script>
<div id="replyform" class="card my-4 d-none">
<h5 class="card-header">Cevap Yaz:</h5>
<div class="card-body">
<div class="form-group">
replytext: <textarea id="replytext" name="replytext" class="form-control" rows="3"></textarea>
</div>
<div class="form-group">
astar: <input type="text" class="astar">
</div>
<div id="loader"></div>
<div id="result"></div>
<br>
<button type="submit" id="sendreply" name="sendreply" class="btn btn-primary">Cevap Yaz</button>
</div>
</div>
</body></html>
my testing backend in php(Try it with yoour backend code)
smoke1.php
<?php
echo "ok";
echo $_POST['r_comment'];
echo $_POST['r_commentid'];
echo $_POST['articleid'];
?>
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