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

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();

Related

Ajax how change value id to text database?

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

How to get input data from MVC ViewModel into ajax post

I am fetching data from a SQL database table into an ASP.NET MVC Razor view but I have troubles getting changed input data into an Ajax post such as:
#model MyViewModel
<div class="row">
<div class="col-1">
#Html.LabelFor(model => model.Id, "Id:", new {})
</div>
<div class="col-4">
#Html.Label(Model.Id.ToString(), new { title = "" })
</div>
</div>
<div class="row">
<div class="col-1">
#Html.LabelFor(model => model.Test, "Test:", new { })
</div>
<div class="col-9">
#Html.TextBoxFor(model => model.Test, new { data_bind = "value: Test", #type = "text" })
</div>
</div>
#section scripts {
<script type="text/javascript">
$("#save-click").click(function () {
var nr = #Model.Id;
var postData = #Html.Raw(Json.Encode(#Model));
//alert(postData.Test);
$.ajax({
type: "POST",
url: actions.test.createOrUpdate + "?id=" + nr,
dataType: "json",
traditional: true,
data: postData,
success: function (response) {
if (response.Code == 0) {
else {
window.location.reload(false);
}
} else {
alert('err');
}
}
});
});
});
</script>
}
When I load the view everything is displayed correctly. The controller action is triggered correctly and the Id (which can not be altered) is passed properly too. However when input fields are changed not the changed values get passed to the controller but the original values that were fetched into the view.
The serialization seems to work, since the alert (postData.Test) returns a value - but always the unchanged one.
Any help would be appreciated.
var postData = #Html.Raw(Json.Encode(#Model));
This line is the culprit. When Razor renders the script, it will assign the original/unchanged model to your postData variable.
If you use "Inspect Element" or dev tools to check the value of postData, you'll see that the values won't change because they're statically assigned.
You need to check for the new values every time you click the button by using
var postData = $("form").serialize();
And be sure to wrap your input fields inside a form tag. See code below:
<form>
<div class="row">
<div class="col-1">
#Html.LabelFor(model => model.Id, "Id:", new {})
</div>
<div class="col-4">
#Html.Label(Model.Id.ToString(), new { title = "" })
</div>
</div>
<div class="row">
<div class="col-1">
#Html.LabelFor(model => model.Test, "Test:", new { })
</div>
<div class="col-9">
#Html.TextBoxFor(model => model.Test, new { data_bind = "value: Test", #type = "text" })
</div>
</div>
</form>
#section scripts {
<script type="text/javascript">
$("#save-click").click(function () {
var nr = #Model.Id;
// use form.serialize or use the id/class of your form
var postData = $("form").serialize();
$.ajax({
type: "POST",
url: actions.test.createOrUpdate + "?id=" + nr,
dataType: "json",
traditional: true,
data: postData,
success: function (response) {
if (response.Code == 0) {
else {
window.location.reload(false);
}
} else {
alert('err');
}
}
});
});
});
</script>
}

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);
}

Vuejs Cannot Submit Form Ajax

I want to submit data via modal Semantic UI and Vuejs. But my form cannot submit data via Ajax. i'm tired to find the problem, maybe someone can help me.
My View like this.
<form v-on:submit.prevent="addProductCategory" class="ui form">
<div class="content">
<div class="description">
<div class="field" v-bind:class="{'has-error': input.errorsAddProductCategory.name}">
<label for="name">Name</label>
<input v-model="input.addProductCategory.name" type="text" id="name" name="name">
<div class="help-block" v-if="input.errorsAddProductCategory.name"
v-text="input.errorsAddProductCategory.name[0]"></div>
</div>
</div>
</div>
<div class="actions">
<div class="ui black deny button">
No
</div>
<button type="submit" class="ui positive right button">Add</button>
</div>
</form>
<script type="text/javascript">
const CSRF_TOKEN = '{{ csrf_token() }}';
const URLS = {
productCategory: {
addProductCategory: '{{ route('product-category.store') }}',
}
};
</script>
Function to Add Data.
function addProductCategory() {
var data = app.input.addProductCategory;
data._token = CSRF_TOKEN;
$.ajax({
url: URLS.productCategory.addProductCategory,
method: 'POST',
data: data,
success: function (data) {
app.input.addProductCategory = {
name: ""
};
app.input.errorsAddProductCategory = [];
$('#modal-create').modal('hide');
}
error: function (data) {
if (data.status === 401) { // unauthorized
window.location.reload();
} else if (data.status === 422) {
app.input.errorsAddProductCategory = data.responseJSON;
} else {
alert('There is an error.');
console.log(data);
}
}
});
}
And Vuejs
var app = new Vue({
el: "#app",
data: function () {
return {
input: {
addProductCategory: {
name: ""
},
errorsAddProductCategory: [],
editProductCategory: {
name: ""
},
errorsEditProductCategory: []
}
};
},
methods: {
addProductCategory: addProductCategory,
}
});

ajax alert is not working using codeigniter

I am newer to ajax. I want to add two fields using ajax and codeigniter.. When i click the submit button the two fields are added but the alert message is not showing also the page is not refreshing. Can any one solve my issue.. Thanks in advance..
This is my Form
<form action="" id="suggestionsform" method="post">
<div class="form-group">
<label for="suggname">Name</label>
<input type="text" class="form-control" name="suggname" id="suggname" placeholder="Enter Your Name" required="required">
</div>
<div class="form-group">
<label for="suggmessage">Suggestion</label>
<textarea class="form-control" rows="4" name="suggmessage" id="suggmessage"
placeholder="Enter Your Suggestions"></textarea>
</div>
<button type="submit" class="btn btn-default" id="suggestions">Submit</button>
</form>
This is my ajax codeing
<script>
// Ajax post
$(document).ready(function() {
$("#suggestions").click(function(event) {
event.preventDefault();
var name = $("#suggname").val();
var suggestion = $("#suggmessage").val();
$.ajax({
type: "POST",
url: "<?php echo site_url('Helen/addSuggestion')?>",
dataType: 'json',
data: {name: name, suggestion: suggestion},
success: function(data) {
if (data=='true')
{
alert("Thank you for your Suggestion");
}
}
});
});
});
</script>
Controller Coding
public function addSuggestion()
{
$data=array(
'name' => $this->input->post('name'),
'messages' => $this->input->post('suggestion'),
'date' => now()
);
$data=$this->Helen_model->setSuggestion($data);
echo json_encode($data);
}
Model Coding
public function setSuggestion($data){
$this->db->insert('messages', $data);
return $this->db->insert_id();
}
You can achieve like this..
Model
Return true status if insert successful.
public function setSuggestion($data){
$res = $this->db->insert('messages', $data);
if($res){
$result = array('status'=>true,'message'=>'successful');
}
else
{
$result = array('status'=>false,'message'=>'failed');
}
return $result;
}
JS
Check status in success function
<script>
// Ajax post
$(document).ready(function() {
$("#suggestions").click(function(event) {
event.preventDefault();
var name = $("#suggname").val();
var suggestion = $("#suggmessage").val();
$.ajax({
type: "POST",
url: "<?php echo site_url('Helen/addSuggestion')?>",
dataType: 'json',
data: {name: name, suggestion: suggestion},
success: function(response) {
data = eval(response);//or data = JSON.parse(response)
if (data.status ===true)
{
alert("Thank you for your Suggestion");
}
}
});
});
});
</script>
Try to use echo '{"status": "success"}; on your controller response.
That i see on your script you are shown database response.

Resources