It's more of a logical question than code...
So I have 2 tables in the DB: kpiInvoices and kpiTerms
The kpiInvoices table is where the user's entered data will be saved to and displayed in a DataTable.
When the user creates a new KPI invoice it will show the form above. I want the SLA Term to be <select> and fetches the data from the kpiTerms Table. When the user selects a term, the Cost input automatically fetches and show the cost of that selected term. Then submits the form and saves the data in kpiInvoices table.
Do I need to create relationships for the 2 tables?
Should I use Eloquent Relationships?
Should I use App\Models\KPITerms in the KPIInvoiceController and do a foreach loop in the blade?
So I made an ajax request to both SLATerm and SLACost and looped through the requested data. Then I made an if statement within the loop to change the SLACost based on the SLATerm selected.
function fetchSLA() {
$.ajax({
type: 'GET',
url: "/management/kpi/fetch/sla",
dataType: 'json',
success: function (response) {
$.each(response.SLATermData, function (key, value) {
$("select[name='SLATerm']").change(function() {
if ( $("select[name='SLATerm']").val() == value.SLATerm ) {
$("input[name='SLACost']").val(value.SLACost);
}
});
});
}
});
}
And here is the Laravel controller for the API:
/**
** KPI API
**/
public function fetchSLA()
{
$kpiTerms = KPITerms::get(['SLATerm' => 'SLATerm', 'SLACost' => 'SLACost']);
return response()->json([
'SLATermData' => $kpiTerms, // SLATermData is the name that will be used in Ajax.
]);
}
Related
How can I do clickable tab that display data?
I want to fetch the data from mysql row to the row in the table dynamically and when i open her i will see the details of all the the row in my database. Like in this picture.
https://ibb.co/m0Zmk7
If I didn't get your question wrong, you want to display some data from database when user will click on a row.
You need to call a function on every row just like this:
<tr onclick="somefunction(id)"></tr> OR <div onclick="somefunction(id)"></div>
Also you have to create a div where your data will be populated.
<div id="display_data"></div>
And then JS function would be just like:
<script>
function somefunction(id){
$('#display_data').remove(); //it will remove all the data before loading new record.
$.ajax({
url: "pathOfYourFile/function/",
type: "post",
data: {
id: id
},
success: function (data) {
if(data.status==1){
alert("success");
$('#display_data').show();
$('#display_data').append(data.message);
}else{
alert(record error);
}
},
error: function (data) {
console.log(data);
}
});
}
<script>
And in the end you have to write a function in php that will get your data from database. Just make sure that you will return data just like this:
$data['json_data'] = array('status' => 1,
'message' => $record
);
I Hope this will work in your case. Please do not hesitate to ask a question if there is any confusion.
Basically, I want to do that user will check the checkbox and click on deleteAll button for delete multiple records at once. For this, i fire ajax and get all selected id's and then selected id's send to controller's method.
I am using delete method for remove multiple records from database but it is not working.
And I do not want to delete multiple records using loop.
Is there any other way of CakePHP of delete multiple records at once?
I tried below code:
script.js :
$('#del_all').click(function(){
var selected=[];
$('.check:checked').each(function(){
selected.push($(this).attr('id'));
});
$.ajax({
type: "post",
url: "Users/deleteall", // URL to request
data: {"id":selected}, // Form variables
success: function(response){
alert(response);
}
});
});
Controller method :
public function deleteall(){
$data=$this->request->data['id'];
$user_ids=implode("','",$data);
$user_ids="'".$user_ids."'";
$this->User->delete($user_ids,$cascade=false);
}
try this with deleteall try to use this
public function deleteall()
{
$user=array(1,2,3); // replace with real values
$condition = array('User.id in' => $user);
$this->User->deleteAll($condition,false);
}
Use deleteAll() method
$this->User->deleteAll(array('id' => $user_ids), false);
Note that:
deleteAll() will return true even if no records are deleted, as the conditions for the delete query were successful and no matching records remain.
More information you can find in manual.
After hours of Googling, I can't seem to find an answer to this seemingly simple problem. I can't add data to a database and show that data without refreshing the page. My goal is to be able to create an object from a form to upload to a database, and then show all the items in database (without the page refreshing). I have tried to get AJAX working many times, but I can't seem to do that. The application works by adding stars to students, so basically I would want to be able to update a students star count without reloading the page. But right now I can't even console.log the submitted form data. My Controller code is like so:
public function addStar(){
$id = Input::get('id');
$user_id = Input::get('user_id');
if(Auth::user()->id == $user_id){
Student::addStar($id);
}
return Redirect::back();
}
And my form:
{{Form::open(array('action'=>'HomeController#addStar','id'=>'addStar','method'=>'post'))}}
{{ Form::hidden('id', $student->id, array('id'=>'id_value')) }}
{{ Form::hidden('user_id', $student->user_id, array('id'=>'user_id_value'))}}
{{ Form::submit('+')}}
{{ Form::close() }}
And my extremely poor attempts at AJAX:
$('#addStar').on('submit',function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
cache: false,
dataType: 'JSON',
url: '/addstar',
data: $('#addStar').serialize(),
success: function(data) {
console.log(data);
},
});
return false;
});
The code works fine if I settle for allowing page reloads, but I don't want that. So essentially, my question is, how do I add data to a database and show it without the page reloading? Thanks so much!
Your controller is doing a redirect after the logic, ajax won't be able to do anything with the response. A one take would be, after adding a start returning the new star rating.
public function addStar(){
$id = Input::get('id');
$user_id = Input::get('user_id');
if(Auth::user()->id == $user_id){
Student::addStar($id);
}
$star_count = //get new star count;
return Response::json(['star_count' => $star_count]);
}
Since controller now returns a json response, the success callback on $.ajax can grab it and do something (update the star count).
#codeforfood,
If you want to grab the response and show it immediately in the page without a reload then you may go with returning a JSON reponse and then handle that response at the client side Javascript for Success or Failure conditions.
Can try something like this if you want:
In the controller addStar() method response:
$data = ['star_count' => 'COUNT OF STARS'];
return json_encode($data);
In the View for that specific Star Div:
<script>
$('#stardiv).on('submit', function (e) {
$.ajax({
type: 'POST',
url: "{{URL::to('xxxxx')}}",
data: $(this).serialize(),
dataType: "JSON",
success: function (data) {
Handle the success condition here, you can access the response data through data['star_count']
},
error: function (data) {
Handle the error condition here, may be show an alert of failure
}
});
return false;
});
</script>
After all this is just one approach, you may try different one which ever suits your need.
I'm working on a Extjs 4 application and I'm at a point where I need to create view components dynamically.
I have a store that's loaded with new items when I select a value from a combobox. And I want to create a new view component for each item the new store has.
I'm using Extjs 4 with the MVC architecture.
This is the function that creates a new combobox that's fired when I choose an Item from another combo :
function createComboBox(label) {
var combo = new Ext.form.ComboBox({
displayField: 'combo',
typeAhead: true,
mode: 'local',
forceSelection: true,
triggerAction: 'all',
emptyText: 'Select item...',
selectOnFocus: true,
fieldLabel: label
});
return combo;
}
This is the code inside my "select combobox" handler event :
onSelectedValue: function (combo) {
var selected = combo.getValue();
var guiDataStore = this.getGuiDataStore();
guiDataStore.getProxy().url = 'gui_comp_items.php?id_metric=' + selected;
guiDataStore.load({
params: {
id_metric: selected
},
scope: this,
callback: function () {
var paramsRef = this.getParams();//this is the view where I'd like to create the combobox
var total = guiDataStore.getTotalCount();
if (total > 0) {
guiDataStore.each(function (model) {
if (model.get('type_guicomp') == 'combobox') {
paramsRef.down('fieldset[id=filterfieldset]').add(createComboBox(model.get('name_filter')));
paramsRef.down('fieldset[id=filterfieldset]').doLayout();
}
})
}
}
})
}
So my problem is, the first time I choose an item from the existing combobox and total = 0 , no combobox is created and everything is fine, then when I choose a value that returns total = 2, 2 new comboboxes are created, that's perfect. BUT, when right after that, I choose again a value with total = 0, the store is not updated and I STILL get 2 new comboboxes.
Is there a problem with my callback? Please any help would be much appreciated.
Once guiDataStore has 2 records in it, why would it be empty next time?
As in, do you empty the store between the various callback calls?
ok, so I have a database comprising of two tables, products and suppliers.
All suppliers fill in a form and their data is then stored in the suppliers table, and the products table contains a list of all of the products, so when the supplier fills in the form, he can choose as many products as he wishes as I use jQuery JSON and AJAX to get the list of all of the products and then populate a drop down list with all of them in it, which can then be cloned as many times as is needed.
The problem I am sitting with now is, how do I insert all of the different products the supplier chooses into the supplier table, or should I rather just relate all of the products he chooses to the one supplier for better normalization since all the products are already there?
I will be using jQuery $.ajax to POST the form data in JSON format to a waiting PHP file, which will then parse it and insert the data into the database.
So basically, I need to figure out how to relate the data in the database to achieve the best normalization possible, and I need to figure out a way of inserting a variable amount of products into the suppliers table or find a way to relate the many products he chooses to the one supplier.
I am very new to relational databases, so any advice on how to proceed would be a great help, so would any other advice you guys may have!
The jQuery code I use to populate clone and POST the products the supplier chooses:
$(document).ready(function() {
var count = 0;
//when clicked it will remove the closest div with a class of 'container'
$("span.remove").live('click', function(){
$(this).closest("div.container").fadeOut(400, function(){
$(this).remove();
$('#button').attr('disabled','');
});
});
//initialize the button
$('#button').attr('disabled','');
$('#button').click(function(){
var count = $("#systems_wrapper > .container").size();
var lastID = $("#systems_wrapper > .container:last").attr('id');
var exploded = lastID.split("_");
var increment = Number(exploded[1])+1;
//if the user has selected 5 products, disable the 'add' button
if(count >= 5){
$('#button').attr('disabled','disabled');
}else {
$('#button').attr('disabled','');
}
//clone the first drop down and give it a different ID, as well as it's child elements
var test = $('#systems_0.container').clone().attr('id', 'system_' + increment).appendTo('#systems_wrapper');
test.children(':nth-child(2)').append('<span class="remove"></span>');
test.children(':nth-child(2)').children(':first').attr('id', 'mail_' + increment).attr('class','dropDowns').attr('onchange','test();');
});
//get the products JSON object returned from test_post.php and run the necessary functions on the returned data
$.getJSON("test_post.php", function(data){
//clean out the select list
$('#box').html('');
//run the loop to populate the drop down list
$.each(data, function(i, products) {
$('#box').append(
$('<option></option>').html(products.products)
);
});
});
});
//this gets all of the products chosen and then gets each ones value and ID, and then posts it to the qwer.php file
function test(){
var sections = $('#systems_wrapper').find('.dropDowns');
var newArray = new Array();
sections.each(function(){
var id = $(this).attr('id');
var val = $(this).val();
var o = { 'id': id, 'value': val };
newArray.push(o);
});
alert(newArray);
$.ajax({
type: "POST",
url: "qwer.php",
dataType: 'json',
data: { json: JSON.stringify(newArray) }
});
}
Thanx in advance!
If i understand the problem correctly from a database level, should you be using an intermediate table called something like ProductSupplier containing a Product_ID and Supplier_ID column.
Then when a supplier selects a product, add both the supplier and product id to a new column in this table.
This will allow multiple suppliers to pick the same product and multiple products to be picked by the same supplier.
EDIT: I meant to say "add both the supplier and product id to a new ROW in this table"