Ajax how change value id to text database? - ajax

I have a problem that is the value displayed in the database is the id value not the value of the text that appears in the input label. then my question is how to change the id value to a text value?
route web.php
`Route::get('/selectProvinces', [App\Http\Controllers\Admin\ManagementController::class, 'provinces'])->name('province.index'); `
ajax script
<script>
$(document).ready(function () {
$("#selectProvinces").select2({
placeholder: 'Pilih Provinsi',
ajax: {
url: "{{route('province.index')}}",
processResults: function ({
data
}) {
return {
results: $.map(data, function (item) {
return {
id: item.id,
text: item.name
}
})
}
}
}
});
</script>
blade.php boostrap
<div class="row">
<label for="formGroupExampleInput2">Provinsi</label>
<div class="col">
<select id="selectProvinces" class="form-control selectpicker" name="provinces">
</select>
</div>
</div>
controller
public function management_create(Request $request) {
Member::create([
'provinces' => $request->provinces,
]);
Alert::success('Success', 'Member berhasil dibuat');
return redirect()->route('management');
}
i hope the value changes text value like "East Java" not the number

Related

laravel 8 select 2 search dropdown store on database (name) instead of (id)

hello i'm trying to use select2 on a laravel 8 website i'm creating.
it is working correctly but when i submit the form it saves on the database the id instead of the name. (i need to store the name "origem" instead of the id of "origem".
the code is this:
create.blade
<div class="container mt-5">
<div class="row">
<div class="form-group mb-3">
<select class="origem form-control p-3" name="origem"></select>
</div>
</div>
</div>
<script type="text/javascript">
$('.origem').select2({
placeholder: 'Select movie',
ajax: {
url: 'ajax-autocomplete-search',
dataType: 'json',
delay: 250,
processResults: function(data) {
return {
results: $.map(data, function(item) {
return {
text: item.origem,
id: item.id
}
})
};
},
cache: true
}
});
</script>
selectsearch controller
public function selectSearch(Request $request)
{
$origem = [];
if($request->has('q')){
$search = $request->q;
$origem = Origem::select("id", "origem")
->where('origem', 'LIKE', "%$search%")
->get();
}
return response()->json($origem);
}
form controller
$data->origem = $request->input('origem');
$data->save();

Laravel How to append Ajax json in Select option

what is issue with my code, it returns empty drop down. i want drop down of nationality table, in teachers profile.
View:
<select class="form-control" name="nation_id" id="nation_id">
<input type="hidden" name="teacher_nation_id" id="teacher_nation_id"
value="{{ #$teacher->nation_id}}">
</select>
ajax code which returns empty dropdown: Ajax:
<script>
$(document).ready(function($){
$.get('nations-list', function(data) {
let teacher_nation_id = $('#teacher_nation_id').val();
let nations = $('#nation_id');
nations.empty();
$.each(data, function(key, value) {
nations.append("<option value='"+ key +"'>" + value + "</option>");
});
nations.val(teacher_nation_id);
});
});
</script>
My Controller:
public function ajaxrequest(Request $request)
{
$nations = Nation::all()->pluck('nation', 'id');
return response()->json($nations);
}
Here is my route:
Route:
Route::get('nations-list','TeachersController#ajaxrequest');
Try this,
<input type="hidden" name="teacher_nation_id" id="teacher_nation_id"
value="{{ #$teacher->nation_id}}">
<select class="form-control" name="nation_id" id="nation_id">
</select>
<select class="form-control" name="area" id="area">
</select>
Ajax code:
<script type="text/javascript">
$(document).ready(function($){
$('#nation_id').click(function($){
var tid = $('#teacher_nation_id').val();
if(tid){
$.ajax({
type:"get",
url:"{{url('/getNation)}}/"+tid,
success:function(res)
{
$('#nation_id').empty();
$("#nation_id").append('<option>--Select Nation--</option>');
if(res)
{
$.each(res,function(key,value){
$('#nation_id').append($("<option/>", {
value: key,
text: value
}));
});
}
}
});
}
});
$('#nation_id).change(function(){
var nid = $(this).val();
if(nid){
$.ajax({
type:"get",
url:"{{url('/getArea')}}/"+nid,
success:function(res)
{
$("#area").empty();
$("#area").append('<option>--Select Area--</option>');
if(res)
{
$.each(res,function(key,value){
$('#area').append($("<option/>", {
value: key,
text: value
}));
});
}
}
});
}
});
});
</script>
Controller:
public function getNation($id)
{
$nations= DB::table("nations")
->where("teacher_nation_id",$id)
->pluck("nation","id")
->toArray();
return response()->json($nations);
}
public function getArea($id)
{
$areas= DB::table("areas")
->where("nation_id",$id)
->pluck("area","id")
->toArray();
return response()->json($areas);
}
Route:
Route::get('/getNation/{id}','NationsController#getNation);
Route::get('/getArea/{id}','AriasController#getArea);
//Here I assumes that You have different controller named AreasController you can gave name of your controller
Hope it will useful for you..
Good Luck...

Pass multiple Id's against multiple values in database

I'm working on a task that uses autocomplete textbox items containing names, stores in textbox or in listbox with their associated Id's(hidden) and inserted into the required table (only their related id's). I'm working on mvc 5 application. So far I've achieved to add value in listbox with names but not Id's. And trying to add the listbox values get stored in database. Below is my code.
Note:- I'm using partial view to display listbox when the button clicks. The current scenario is that it the listbox overwrites the first value when inserting second value.
StudentBatch.cs
public List<string> selectedids { get; set; }
public List<string> SelectedNames { get; set; }
Create.cshtml
<div class="form-group">
<div class="col-md-12">
#Html.EditorFor(model => model.StudentName, new { id = "StudentName" })
<input type="button" value="Add Text" id="addtypevalue" />
<div id="typevaluelist"></div>
</div>
</div>
<div id="new" style="display:none;">
<div class="typevalue">
<input type="text" name="typevalue" />
<button type="button" class="delete">Delete</button>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Add Students" class="btn btn-default" />
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#StudentName").autocomplete({
//autocomplete: {
// delay: 0,
// minLength: 1,
source: function (request, response)
{
$.ajax({
url: "/Student/CreateStudent",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function(data) {
try {
response($.map(data,
function (item)
{
return { label: item.FirstName, value: item.FirstName };
}));
} catch (err) {
}
}
});
},
messages:
{
noResults: "jhh", results: "jhjh"
}
});
});
</script>
<script>
$('#addtypevalue').click(function () {
$(document).ready(function () {
var selValue = $('#StudentName').val();
$.ajax({
type: "GET",
url: '#Url.Action("GetListBox", "Student")',
dataType: "html",
data: { CourseId: selValue },
success: function (data) {
$("#partialDiv").html(data);
},
failure: function (data) {
alert('oops something went wrong');
}
});
});
});
</script>
GetListBox.cshtml
#model WebApplication1.Models.StudentBatch
#if (ViewBag.Value != null)
{
#Html.ListBoxFor(m => m.SelectedNames, new SelectList(Model.SelectedNames))
}
StudentController.cs
public PartialViewResult GetListBox(string CourseID)
{
Context.Student studCont = new Context.Student();
Models.StudentBatch student = new Models.StudentBatch();
student.SelectedNames = new List<string>();
student.SelectedNames.Add(CourseID);
ViewBag.Value = student;
return PartialView(student);
}

Vue Object is Empty

I'm using Vuejs to display data from an API to a template. I'm trying to figure out why I am not returning data for the team so I can display in for the template. Right now when I use the VueJS Chrome Extention it shows that the team is an empty object.
<div v-if="team">
<div class="row">
<div class="col-12 col-sm-12">
<div class="fw-700 pb3 mb5" style="border-bottom: 1px solid #333;">Name:</div>
<div class="mb10" style="font-size: 20px;">{{ team.name }}</div>
</div>
</div>
<script>
module.exports = {
http: {
headers: {
'X-CSRF-TOKEN': window.Laravel.csrfToken
}
},
props: [ 'id', 'editable' ],
data: function(){
return {
modalName: 'additionalInfo',
team:{
}
}
};
},
methods: {
fetchInfo: function(){
this.$http.get('/api/teams/info', { params: { id: this.id } }).then((response) => {
this.team = response.data;
});
},
},
}
}
</script>
It is empty because your method fetchInfo isn't being called, so you need to do something like this:
created () {
this.fetchInfo()
}
This will call the function fetchInfo which in turn will fetch and fill this.team

Meteor: Error: {{#each}} currently only accepts arrays, cursors or falsey values

I keep getting this error message when I click on the send button. Im trying to create a Instant Messenger app where online users can chat one on one. I am a beginner and I would really appreciate any help. Here is my error message, again it appears in the console once I click the Send button.
Exception from Tracker recompute function: meteor.js:862 Error:
{{#each}} currently only accepts arrays, cursors or falsey values.
at badSequenceError (observe-sequence.js:148)
at observe-sequence.js:113
at Object.Tracker.nonreactive (tracker.js:597)
at observe-sequence.js:90
at Tracker.Computation._compute (tracker.js:331)
at Tracker.Computation._recompute (tracker.js:350)
at Object.Tracker._runFlush (tracker.js:489)
at onGlobalMessage (meteor.js:347)
Here is my HTML
<template name="chat_page">
<h2>Type in the box below to send a message!</h2>
<div class="row">
<div class="col-md-12">
<div class="well well-lg">
{{#each messages}}
{{> chat_message}}
{{/each}}
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<form class="js-send-chat">
<input class="input" type="text" name="chat" placeholder="type a message here...">
<input type="submit" value="Send">
</form>
</div>
</div>
</template>
<!-- simple template that displays a message -->
<template name="chat_message">
<div class = "container">
<div class = "row">
<img src="/{{profile.avatar}}" class="avatar_img">
{{username}} said: {{text}}
</div>
</div>
<br>
</template>
Client Side
Template.chat_page.helpers({
messages: function () {
var chat = Chats.findOne({ _id: Session.get("chatId") });
return chat.messages;
},
other_user: function () {
return "";
}
});
Template.chat_page.events({
'submit .js-send-chat': function (event) {
console.log(event);
event.preventDefault();
var chat = Chats.findOne({ _id: Session.get("chatId") });
if (chat) {
var msgs = chat.messages;
if (! msgs) {
msgs = [];
}
msgs.push({ text: event.target.chat.value });
event.target.chat.value = "";
chat.messages = msgs;
Chats.update({ _id: chat._id }, { $set : { messages: chat } });
Meteor.call("sendMessage", chat);
}
}
});
Parts of the server side
Meteor.publish("chats", function () {
return Chats.find();
});
Meteor.publish("userStatus", function () {
return Meteor.users.find({ "status.online": true });
});
Meteor.publish("userData", function () {
if (this.userId) {
return Meteor.users.find({ _id: this.userId },{ fields: { 'other': 1, 'things': 1 } });
} else {
this.ready();
}
return Meteor.users.find({ "status.online": true });
});
Meteor.publish("users", function () {
return Meteor.users.find({ "status.online": true });
});
Chats.allow({
insert: function () { return true; },
update: function () { return true; },
remove: function () { return true; }
});
Meteor.methods({
sendMessage: function (chat) {
Chats.insert({
chat: chat,
createdAt: new Date(),
username: Meteor.user().profile.username,
avatar: Meteor.user().profile.avatar,
});
}
});
Chances are your subscriptions aren't ready. This means that Chats.findOne() will return nothing, meaning that Chats.findOne().messages will be undefined.
Try the following:
{{ #if Template.subscriptionsReady }}
{{#each messages}}
{{/each}}
{{/else}}
Alternatively, use a find() on chats, then {{#each}} on the messages within that chat. For example:
Template['Chat'].helpers({
chats: function () {
return Chats.find(Session.get('chatId')); // _id is unique, so this should only ever have one result.
}
});
Then in template:
{{#each chats}}
{{#each messages}}
{{>chat_message}}
{{/each}}
{{/each}}
I think there might be a logical error in this line
Chats.update({ _id : chat._id }, { $set : { messages : chat } });
You are setting the value of the field messages to chat. But chat is an object. So in your helper when you are returning Chats.findOne().messages to the {{#each}} block, you are actually returning an object which is not a valid value to be sent to an {{#each}} block and hence the error.
I think what you mean to do is
Chats.update({ _id : chat._id }, { $set : { messages : msgs } });

Resources