Laravel/Ajax CRUD: show option value on edit button click - php

I have an edit modal with three drop down select options
Currently having trouble showing the appropriate option on edit button click, my input fields have no issue.
heres my working add function for reference, all three option tags are working in this way.
$(document).on('click', '.add_category', function(e){
e.preventDefault();
var category_data = {
'category_name': $('.category_name').val(),
'category_description': $('.category_description').val(),
'category_description': $('.category_description').val(),
'config_view_type': $('.config_view_type').val(),
'config_edit_type': $('.config_edit_type').val(),
'bbrmode_view_type': $('.bbrmode_view_type').val(),
}
//token taken from laravel documentation
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: "/clinical/bbr-category-configuration",
data: category_data,
dataType: "json",
success: function (response){
console.log(response);
if(response.status == 400) {
$('#category_formCheck').html("");
$('#category_formCheck').addClass('alert alert-danger');
$.each(response.errors, function (key, err_values) {
$('#category_formCheck').append('<li>'+err_values+'</li>');
});
}
else
{
$('#category_notif').html("");
$('#category_notif').addClass('alert alert-success');
$('#category_notif').text(response.message);
$('#createCategory').modal('hide');
fetchcategory();
}
}
});
});
also, in my edit category button, I went ahead and used console.log to show that the option values can be read form the table:
I tried to add the three in my edit display
$(document).on('click','.edit_category',function (e) {
e.preventDefault();
var cat_id = $(this).val();
console.log(cat_id);
$('#editCategoryModal').modal('show');
$.ajax({
type: "GET",
url: "/clinical/bbr-category-configuration-edit/"+cat_id,
success: function (response) {
console.log(response);
if(response.status == 404) {
$('#success_message').html("");
$('#success_message').addClass('alert alert-danger');
$('#success_message').text(response.message);
} else {
$('#edit_category_name').val(response.category_edit.category_name);
$('#edit_category_description').val(response.category_edit.category_description);
$('#edit_cat_id').val(response.category_edit.category_id);
//new code
$('#edit_config_view_type').val(response.category_edit.config_view_typ);
$('#edit_config_edit_type').val(response.category_edit.config_edit_type);
$('#edit_bbrmode_view_type').val(response.category_edit.bbrmode_view_type);
}
}
});
});
modal fields:
<input type="text" id="edit_category_name" class="form-control form-group w-100" placeholder="Category Name">
<textarea id="edit_category_description" class="form-control w-100" placeholder="Category Description" cols="50" rows="10"></textarea>
<div class="container">
<div class="row mb-4">
<div class="col-md-4">
<small class="font-weight-bold">Config Access View Type:</small>
</div>
<div class="col-md-4">
<div class="form-group">
<select id="edit_config_view_type" class="edit_config_view_type form-control w-100" name="config_view">
{{-- <option id="edit_category_name" class="form-control form-group w-100" value="asdasd"></option> --}}
<option>Public</option>
<option>Restricted</option>
</select>
</div>
</div>
<div class="col-md-4 text-center">
<button id="edit_config_view_type_r" type="submit" class="btn btn-outline-secondary" data-toggle="modal" data-target="#new_category"><i class="fas fa-plus-circle "></i> Add Recipient</button>
</div>
</div>
</div>
tried adding <option id="edit_config_view_type" ></option> but to no avail.
Notes:
have the option value show up in the edit button like the name/description textfields.
the option needs to be the same as the column values from the table.
category_name and category_description are already read from the table, I just need to have that effect on a dropdown
also added a shortcut on the three columns when added: P & R and they get displayed as Public and restricted
This question is a bit on the advice side, any help would be appreciated, thank you

Related

How to grab data and auto fill a form on change event using Ajax

What I need
I need when someone change my calendar, a php script should run in background and fetch some data and show it in the form fields accordingly. To do that, I have the following HTML code and Ajax script
$("#normalShiftDate").change(function() {
var FD = new FormData($('#dailyEditor')[0]);
$.ajax({
type: "POST",
url: "supervisorEditAjax.php",
processData: false,
contentType: false,
data: FD,
success: function(result) {
$('#normalShiftOperator').val(result["normalShiftOa"]);
$("#normalShiftOperatorDuration").val(result["normalShiftOperatorDuration"]);
$("#normalShiftPinCount").val(result["normalShiftPinCount"]);
},
error: function() {
alert('Some error occurred!');
}
});
});
<div class="form-group">
<div class="row">
<div class="col-sm text-center" id="normalShiftOaDiv" class="">
<label for="currentOa">Current OA?</label><br>
<input type="radio" name="currentOa" id="normalShiftOa" value="normalShiftOa">
</div>
<div class="col-sm" id="normalShiftOperatorNameDiv">
<label for="normalShiftOperator">Normal Shift</label>
<select class="form-control" id="normalShiftOperator" name="normalShiftOperator">
<option></option>
<option>A</option>
<option>B</option>
</select>
</div>
<div class="col-sm" id="normalShiftOperatorDurationDiv">
<label for="normalShiftOperatorDuration">Duration</label>
<select class="form-control" id="normalShiftOperatorDuration" name="normalShiftOperatorDuration">
<option></option>
<option>1</option>
<option>2</option>
</select>
</div>
<div class="col-sm">
<label for="normalShiftPinCount">Pin Count</label>
<input type="number" class="form-control" id="normalShiftPinCount" name="normalShiftPinCount" value="23">
</div>
<div class="col-sm">
<label for="normalShiftDate">Date</label>
<input type="date" class="form-control" id="normalShiftDate" name="normalShiftDate">
</div>
<div class="col-sm">
<button type="submit" class="btn btn-primary" style="margin-top: 30px;" id="normalShiftUpdate" name="normalShiftUpdate">Update</button>
</div>
</div>
</div>
I want to show the php variables $normalShiftOa, $normalShiftOperatorDuration and $normalShiftPinCount in the form fields with id normalShiftOperator, normalShiftOperatorDuration, normalShiftPinCount respectively when someone change calendar. Please see the contents of supervisorEditAjax.php. How can I show these three variables into the three id fields?
I only know how to show to one single field. But if there are multiple values to be shown in multiple fields, how can we do that?
Can someone please help?
Edit 1
Contents of supervisorEditAjax.php
<?php
$normalShiftOa = "A";
$normalShiftOperatorDuration = "2";
$normalShiftPinCount = "100";
$arr = array('normalShiftOa' => $normalShiftOa, 'normalShiftOperatorDuration' => $normalShiftOperatorDuration, 'normalShiftPinCount' => $normalShiftPinCount);
echo json_encode($arr);?>
I tried to use some Json method. But it is not working
After many trial and error, I am able to show it in the respective form fields. The issue was at the Ajax part. Basically I need to parse the Json object in order to get the specific values. Replace the AJAX code as below and it works fine
< script >
$("#normalShiftDate").change(function() {
var FD = new FormData($('#dailyEditor')[0]);
$.ajax({
type: "POST",
url: "supervisorEditAjax.php",
processData: false,
contentType: false,
data: FD,
success: function(result) {
var returnedData = JSON.parse(result); //This is the change done to the code
$('#normalShiftOperator').val(returnedData["normalShiftOa"]);
$("#normalShiftOperatorDuration").val(returnedData["normalShiftOperatorDuration"]);
$("#normalShiftPinCount").val(returnedData["normalShiftPinCount"]);
},
error: function() {
alert('Some error occurred!');
}
});
});
</script>
Please read more about JSON.parse here

Getting a null value in my input file type field

I downloaded a web application and i found out that it is created using Smarty Template Engine. I want to add an avatar field when creating new company so i added enctype="multipart/form-data" and <input type="file" name="avatar"> to the existing <form> and i also added avatar to my companies table in my database. Here is the HTML code:
<form class="form-horizontal" id="ib_modal_form" enctype="multipart/form-data">
<div class="form-group"><label class="col-lg-4 control-label" for="company_name">{$_L['Company Name']}<small class="red">*</small></label>
<div class="col-lg-8"><input type="text" id="company_name" name="company_name" class="form-control" value="{$val['company_name']}"></div>
</div>
<div class="form-group"><label class="col-lg-4 control-label" for="avatar">{$_L['Avatar']}</label>
<div class="col-lg-8"><input type="file" name="avatar"></div>
</div>
<div class="form-group"><label class="col-lg-4 control-label" for="email">{$_L['Email']}</label>
<div class="col-lg-8"><input type="text" id="email" name="email" class="form-control" value="{$val['email']}"> </div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" class="btn btn-danger">{$_L['Cancel']}</button>
<button class="btn btn-primary modal_submit" type="submit" id="modal_submit"><i class="fa fa-check"></i> {$_L['Save']}</button>
</div>
I found out that the form goes to this javascript code when clicking the Save Button:
$modal.on('click', '.modal_submit', function(e){
e.preventDefault();
$.post( _url + "contacts/add_company_post/", $("#ib_modal_form").serialize())
.done(function( data ) {
if ($.isNumeric(data)) {
location.reload();
}
else {
$modal.modal('loading');
toastr.error(data);
}
});
});
Here is the code in the Controller:
case 'add_company_post':
$data = ib_posted_data();
$company = Model::factory('Models_Company')->create();
$company->company_name = $data['company_name'];
$company->url = $data['url'];
$company->email = $data['email'];
$company->phone = $data['phone'];
$company->logo_url = $data['logo_url'];
$company->avatar = $_FILES['avatar']['name'];
$company->save();
break;
The problem is that it does not recognize $_FILES['avatar']['name']; in the Controller Whenever i add a new company, i get a NULL value in my database. I cant seem to solve this problem. Any help would be appreciated. Thanks.
Change
From
$("#ib_modal_form").serialize()
To
new FormData($("#ib_modal_form")[0])
You should use FormData for uploading files using ajax. $(form).serialize() will give you just key and value.
Can you change your ajax call below way
$modal.on('click', '.modal_submit', function(e){
e.preventDefault();
var formData = new FormData($("#ib_modal_form")[0]);
$.ajax({
url: _url + "contacts/add_company_post/",
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function (data) {
if ($.isNumeric(data)) {
location.reload();
}
else {
$modal.modal('loading');
toastr.error(data);
}
},
});
});

How to properly collect the input values inserted by the user using jQuery to send them to the server using ajax post?

I have a payment page that has a multi-step form. In the "step 1" the user inserts his information like nama, surname, etc, then billing information.
So, in the "step 1" I have fields like name, surname, etc. I want in each step collect all information with jQuery so that is possible to send an ajax request to the server to validate the information when the "go to step 2" button is clicked.
My doubt is about how to properly store this step1 data inserted by the user to be possible to send it to the server. For example in the step 1 Im getting the values like:
var name = $('#name').val();
Then how to send the data to the server using an ajax post request?
step 1 html
<div class="tab-pane fade show active clearfix" id="step1" role="tabpanel" aria-labelledby="home-tab">
<h6>User Info</h6>
<form method="post" action="">
{{csrf_field()}}
<div class="form-group font-size-sm">
<label for="name" class="text-gray">Name</label>
<input type="text" required class="form-control" value="{{ (\Auth::check()) ? Auth::user()->name : old('name')}}">
</div>
<!-- other form fields -->
<input type="submit" id="goToStep2" href="#step2"
class="btn btn-primary btn float-right next-step" value="Go to step 2"/>
</form>
</div>
For the ajax part when "Go to step 2" is clicked I created a route 'storeUserInfo', but do you know how to send the data to the PaymentController?
$("a[id='goToStep2']").on('click', function(){
$.ajax({
url: '{{ route('products.storeUerInfo',null) }}',
type: 'POST',
success:function(result){
),
error: function(error) {
console.log(error.status)
}
});
});
This is a complete solution for form with file element
HTML
<div class="tab-pane fade show active clearfix" id="step1" role="tabpanel" aria-labelledby="home-tab">
<h6>User Info</h6>
<form method="post" action="" id="page-form">
{{csrf_field()}}
<div class="form-group font-size-sm">
<label for="name" class="text-gray">Name</label>
<input type="text" required class="form-control" value="{{ (\Auth::check()) ? Auth::user()->name : old('name')}}">
</div>
<!-- other form fields -->
<input type="submit" id="goToStep2" href="#step2"
class="btn btn-primary btn float-right next-step" value="Go to step 2"/>
</form>
</div>
JS
$(function () {
'use strict'
var page_form_id = "page-form";
$('#a[id='goToStep2']').on('click', function () {
$('#' + page_form_id + ' .error').html("");
$('#' + page_form_id + ' .form-group').removeClass("has-error");
var custom_form = $("#" + page_form_id);
var custom_params = custom_form.serializeArray();
var custom_files = $("#file")[0].files;
var custom_formData = new FormData();
for (var i = 0; i < custom_files.length; i++) {
custom_formData.append("file", custom_files[i]);
}
$(custom_params).each(function (custom_index, custom_element) {
custom_formData.append(custom_element.name, custom_element.value);
});
$.ajax({
method: "POST",
url: '{{ route('products.storeUerInfo',null) }}',
contentType: false,
processData: false,
data: custom_formData,
success: function (data, textStatus, jqXHR) {
setTimeout(function () {
window.location.reload();
}, 3000);
},
error: function (data) {
var errors = data.responseJSON;
$.each(errors['message'], function (index, value) {
$('#' + add_form_id + ' .eMsg_' + index).html(value[0]);
$('#' + add_form_id + ' .eMsg_' + index).parent().parent().addClass("has-error");
});
}
});
});
});
If you use form to send something. Better Use submit form method on JQuery. And give return false on the end of the function.
To check is it working, you can use inspect element on your browser on the console tab. If you see something error status it's maybe your code has something wrong.
In other way you can go to the url manually, without hitting by ajax. So you must make sure it works, before you want to use ajax.
Instead of gathering all of the data into variables separately, use the form online to submit inside your ajax call. First, call preventDefault() on the Event, and then you can use this line in your ajax call:
data:$('#myForm').serialize(),
PS, you add the event object as a parameter in your click listener. Then you can call event.preventDefault();.
$("a[id='goToStep2']").on('click', function(){ var name = $('#name').val();
$.ajax({ url: '{{ route('products.storeUserInfo',null) }}/' + category_id, type: 'POST',
data:{ "name": name},success:function(result){ ), error: function(error) { console.log(error.status) } }); });

im not able to call my ajax request in new added div in angular js

i have a three dropdowns like country,state,city it's using ajax reuest.
then i add new dropdowns div using my buttion , myfirst dropdown div's data passed and displayed and it's work fine, but others div's dropdown data not passed and not display and ajax request can't send .
it's my ajax request
<script>
function getstatedetails(id)
{
//alert('this id value :'+id);
$.ajax({
type: "POST",
url: 'ajax_get_finish/'+id,
data: id='cat_id',
success: function(data){
// alert(data);
$('#old_state').html(data);
},
});
}
function getcitydetails(id)
{
$.ajax({
type: "POST",
url: 'ajax_get_size/'+id,
data: id='st_id',
success: function(data){
$('#old_city').html(data);
},
});
}
it's my angular js code
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('shanidkvApp', []);
app.controller('MainCtrl', function($scope) {
$scope.choices = [{id: 'choice1'}];
$scope.addNewChoice = function() {
var newItemNo = $scope.choices.length+1;
$scope.choices.push({'id':'choice'+newItemNo});
};
$scope.removeChoice = function() {
var lastItem = $scope.choices.length-1;
$scope.choices.splice(lastItem);
};
});
and its my html
<div class="content-wrapper" ng-app="shanidkvApp">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Add Challan Details
<i class="fa fa-list"></i> challan Details List
</h1>
</section>
<!-- Main content -->
<section class="content">
<div class="row"> <div class="col-md-12 display_alert"></div></div>
<div class="row">
<div class="col-md-6">
<div class="box box-primary" ng-app="angularjs-starter" ng-controller="MainCtrl">
<div class="box-body table-responsive">
<form action="insert" method="post" data-parsley-validate novalidate enctype="multipart/form-data">
<div data-ng-repeat="choice in choices">
<div class="form-group">
<label for="form-address">Model Name</label>
<select name="country_details" class="form-control countries" id="country_details" onChange="getstatedetails(this.value)">
<option value="" selected="selected" >Select Model</option>
<?php foreach($groups as $count): ?>
<option value="<?php echo $count->model_id; ?>"><?php echo $count->model_name; ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label for="form-address">Finish Name</label>
<select name="select_state" class="form-control countries" id="old_state" onChange="getcitydetails(this.value)">
<option selected="selected">Select Finish</option>
</select>
</div>
<div class="form-group">
<label for="form-address">Size</label>
<select name="selectcity" class="form-control countries" id="old_city" >
<option selected="selected">Select Size</option>
</select>
</div>
<div class="btn btn-primary" ng-show="$last" ng-click="removeChoice()">Remove</div>
</div>
<div class="btn btn-primary" ng-click="addNewChoice()">Add fields</div>
<div class="form-group text-right m-b-0">
<button class="btn btn-primary waves-effect waves-light" type="submit">Save</button>
</div>
</form>
</div>
</div>
</div>
</section>
<!-- /.content -->
data in ajax should be in object form
function getstatedetails(id)
{
//alert('this id value :'+id);
$.ajax({
type: "POST",
url: 'ajax_get_finish/'+id,
data: id='cat_id',
success: function(data){
// alert(data);
$('#old_state').html(data);
},
});
}
pls try
$.ajax({
...
data: { id: 'cat_id' }
})
Stop using JQuery and AngularJS together.
If you want your data, use AngularJS too.
For instance,
app.factory('requestFactory', function($q, $http) {
var ret = {
getStateDetails: getStateDetails,
getCityDetails: getCityDetails
};
return ret;
function getStateDetails(id) {
//Use of promises
var deffered = $q.defer();
$http.post('ajax_get_finish/' + id, {id: 'cat_id'})
.then(function(success) {
deferred.resolve(success.data);
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
}
function getCityDetails(id) {
//Use of promises
var deffered = $q.defer();
$http.post('ajax_get_size/' + id, {id: 'st_id'})
.then(function(success) {
deferred.resolve(success.data);
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
}
});
Then, load your data in your controller, and use the two-way binding to display it.

Auto refresh dropdown after send new value

i have a dropdown with this code:
and other block:
<script type="text/javascript">
/*Primo pulsante attributo*/
$(document).ready(function() {
$('#bloccoetapulsante').click(function() {
var dati = $("#campo").val();
$.ajax({
url: "database/bloccoattributi.php",
data: 'dati=' + dati,
method: "POST",
dataType: "HTML",
cache: false,
success: function(data) {
alert("Attributo inserito");
}
});
});
});
</script>
<div class="row">
<div class="col-lg-3">
<div class="input-group">
<input name="campo" id="campo" type="text" class="form-control" placeholder="Inserisci altro">
<span class="input-group-btn">
<button class="btn btn-default" type="button" id="bloccoetapulsante"><span class="glyphicon glyphicon-plus"></span></button>
</span>
</div>
<!-- /input-group -->
How can i update dropdown, without reload page, after add a new value with button (bloccoetapulsante)?
Thanks
success: function (data) {
$("#id").html("Attributo inserito"); // #id as a dropdown Id
}
or
$("#id").append("Attributo inserito");
Simply add $('.selectpicker').selectpicker('refresh'); after ajax call. it will refresh Bootstrap selectbox

Categories