Populate select box with json data from laravel db query - php

i have a html select box that needs to be populated using jquery ajax with select options that come from a php (Laravel) database query. I tried many approaches but no result, i only get 'undefined' as result.
The Laravel script:
public function loturi($articol) {
$loturi = DB::select("select mgla_lotto from MG_V_DispoLottiBarcode d
join MG_AnaArt art on art.MGAA_Id = d.MGAA_Id join MG_LottiAnag l on
l.MGLA_Id = d.MGLA_Id where MGAA_MBDC_Classe IN ('SEM','FIN') and mbmg_id = 55
and mgaa_matricola in (select child.MGAA_Matricola component
from DB_Legami join MG_AnaArt child on child.MGAA_Id = DBLG_Com_MGAA_Id
join MG_AnaArt p on p.MGAA_Id = DBLG_MGAA_Id
where p.MGAA_Matricola = '$articol') and mgla_datacreazione > '2014-01-01'
group by mgla_lotto having sum(dispo) > 0");
return compact('loturi');
}
The result is this:
{"loturi":[{"mgla_lotto":"1282\/15"},{"mgla_lotto":"1316\/15"},{"mgla_lotto":"1339\/15"},{"mgla_lotto":"1349\/15"},{"mgla_lotto":"1354\/15"},{"mgla_lotto":"1404\/15"},{"mgla_lotto":"1405\/15"},{"mgla_lotto":"1412\/15"}]}
The jquery script is this:
$(document).ready(function() {
$("#cod").change(function(){
var cod_articol = $("#cod").val();
$.ajax ({
url: "/internal/" + cod_articol ,
datatype: "json",
success: function(data) {
$.each(data, function(value){
$("#lot").append('<option id="' + value.index + '">' + value.name +
'</option>');
})
}
});
});
});

Hi here is your answer.
change
$.each(data, function(value){
to
$.each(data.loturi, function(value){
and use below syntax
$.each(data.loturi, function( index, value ){
$("#lot").append('<option value="' + index + '">' + value.mgla_lotto + '</option>');
}
Go to the link to see the example i have made for you.
https://jsfiddle.net/ovht7fkh/2/

Related

Slow SQL Query / Displaying (PHP / jQuery)

I have a request to get data in my mySQL database (36,848 entries).
Then I format and append them with jQuery on my web page.
These two operations take 2 minutes and 30 seconds.
During this time, no other operation is possible on the page.
Is there a way to optimize this to speed up the process?
Like this, it's unusable.
My PHP function
<?php
function get_my_customers() {
$req = $bdd->prepare("SELECT * FROM clients ORDER BY raison_sociale");
$req->execute();
$customers = $req->fetchAll(PDO::FETCH_ASSOC);
return $customers;
}
if(isset($_POST['ajax'])){
$result = get_my_customers();
echo json_encode($result);
}
?>
Data retrieval in jQuery (Ajax)
function get_my_customers(){
var customers;
$.ajax({
url: "model/application/*******/customers/get_my_customers.php",
async: false,
type: "POST",
dataType: 'json',
data: {ajax: 'true'},
success: function(data)
{
customers = data;
}
});
return customers;
}
var my_customers = get_my_customers();
$('#customers_list').append('<div class="list_card" card="customers_list"></div>');
$.each(my_customers, function(key, val){
if(val.enseigne == null){
var enseigne = '';
}else{
var enseigne = ',' + val.enseigne;
}
$('.list_card[card="customers_list"]').append(''+
'<div class="list_card_element">'+
'<div><b>'+ val.numero_client +'</b></div>'+
'<div>'+
'<b>'+ val.raison_sociale +'</b>' + enseigne +
'<br>'+
val.cp_livraison + ', ' + val.adresse_livraison +
'</div>'+
'</div>'
);
});
Do you know what I can do to speed up processing time?
I've tried limiting the SELECT query to only the fields I need but that doesn't improve processing time.
I wonder if it's not rather the jQuery layout that takes time rather than the SQL query.
Thank you !
Use devtools in your browser to determine which step is causing the slowdown. The Network tab will show you the Ajax request and the time interval of the data fetch. If that time interval is not the issue, it's likely with the Javascript. You can get deeper on the Javascript performance using the Performance tab.
try to use indexes see that
MySQL can use an index on the columns in the ORDER BY (under certain conditions). However, MySQL cannot use an index for mixed ASC,DESC order by (SELECT * FROM foo ORDER BY bar ASC, pants DESC). Sharing your query and CREATE TABLE statement would help us answer your question more specifically.
I just passed from 2 minutes and 30 secondes to 14 secondes with this optimization.
var construct_customers = "";
$.each(my_customers, function(key, val){
if(val.enseigne == null){
var enseigne = '';
}else{
var enseigne = ',' + val.enseigne;
}
construct_customers += '<div class="list_card_element">'+'<div><b>'+ val.numero_client +'</b></div>'+'<div>'+'<b>'+ val.raison_sociale +'</b>' + enseigne +'<br>'+val.cp_livraison + ', ' + val.adresse_livraison +'</div>'+'</div>';
//OLD CODE
// $('.list_card[card="customers_list"]').append(''+
// '<div class="list_card_element">'+
// '<div><b>'+ val.numero_client +'</b></div>'+
// '<div>'+
// '<b>'+ val.raison_sociale +'</b>' + enseigne +
// '<br>'+
// val.cp_livraison + ', ' + val.adresse_livraison +
// '</div>'+
// '</div>'
// );
});
$('.list_card[card="customers_list"]').append(construct_customers);
I'm impressed

How to populate a select from mysql using Ajax and json

I have an empty select in HTML that i want to populate through the database.
I have a button that opens a Modal and passes an id. With that ID i fetch the Data from the database and fill all the form fields for one company. However a company can have multiple employees, so i want to fill a select so that all employees that have the same ID as the company, will be shown.
For example:
Company ID is 43, i fill all the form fields (name, location etc.) using this id and fetching the data from the database.
In the table employee there are 3 employees that have the ID 43 as FK, let's name them hans, max and peter.
Now i want to populate a select that shows all 3 of them, so that an user can select one of them and depending on that selection an empty form will be populated, so that it can be edited.
I'm assuming this involves a loop, but i'm not sure how to do it. Not sure if it's relevant but all my mysqli calls use prepare, as i've read this is more secure.
The loop i've tried so far is this, but it's not working. I'm not sure if it's the loop that isn't working or if i'm trying to populate the select wrong.
This is inside a select and all the input fields get populated.
while ($row = $result->fetch_assoc()){
$prename= $row['prename'];
$surname= $row['surname'];
$users_arr[] = array("prename" => $prename, "surname" => $surname);
}
Then i return the data as follows
echo json_encode(array('users_arr'=>$users_arr));
and try to populate the select in the AJAX success
$.each(data.users_arr, function(key, val){
$("#contact_persons").append('<option id="' + data.prename + '">' + data.surname + '</option>');
});
Thanks
Edit: The complete Ajax call:
$.ajax({
url: url,
data: data,
dataType: 'json',
cache: false,
type: "POST",
error: function () {
$('#alertdone').removeClass('hidden');
},
//if ajax call is successful populate form fields and hide error message
success: function (data) {
//hide error message
$('#alertdone').addClass('hidden');
$.each(data.users_arr, function(key, val){
$("#contact_persons").append('<option id="' + data.prename + '">' + data.surname + '</option>');
});
}
});
});
In your AJAX success you can try
var d = $.parseJSON(data);
$.each(d.users_arr, function(index, element) {
$("#contact_persons").append('<option id="' + element.prename + '">' + element.surname + '</option>');
});
Edit
$.ajax({
url: url,
data: data,
cache: false,
type: "POST",
error: function () {
$('#alertdone').removeClass('hidden');
},
success: function (data) {
//hide error message
$('#alertdone').addClass('hidden');
var d = $.parseJSON(data);
$.each(d.users_arr, function(index, element) {
$("#contact_persons").append('<option id="' + element.prename + '">' + element.surname + '</option>');
});
}
});
});

Print results of MySQL query using JQuery JSON without knowing the names of the array keys

I am building a facility on a website (using Symfony2) that allows the user to create reports and display them on a screen using AJAX. The reports are effectively SQL statements that are created on the fly and are then ran on the Database.
The problem I have is that I can't fathom a way to display these results to the screen without first knowing what fields are used in the report. The queries could contain just 2 fields from a table, or 15 fields, and I'd like the code to be robust enough to handle this.
So far, this is the code I'm using:
$.ajax({
type: 'POST',
url: urlLink,
success: function (data) {
var Type = (data.recordType);
var Results = (data.results);
var Name = (data.name);
var Description = (data.description);
var Titles = (data.titles);
$('#reportName').text(Name);
$('#reportDescription').text(Description);
$('#listTable > tbody:last').empty();
$('#listTable > thead:last').empty();
$('#listTable > thead:last').append('<tr>'+Titles+'</tr>');
$.each(Results, function(i, item) {
$('#listTable > tbody:last').append('<tr><td>' + Results[i] + '</td><td>' + Results[i] + '</td><td>' + Results[i] + '</td><td>' + Results[i] + '</td><td>' + Results[i] + '</td><td>' + Results[i] + '</td></tr>');
});
}
});
The variable Titles comes from the query, as when the user is adding fields to the database these are then added to a string which I then explode using PHP in the controller.
Inside the foreach, every column comes back with [object Object]. When I remove the [i] from the code and replace it with .column-name it will then work. But this is what I'm trying to avoid. I'd like to have something similar to what I do with the Table Titles.
Maybe try this, and show output of console.log(data);
console.log(data);
var data = $.parseJSON(data);
$.each(data, function() {
$.each(this, function(k, v) {
/// do stuff
});
});

JSON not fetching success on codeigniter - [object Object]

What i'm trying to do here to populate second select from based from the first one with json format.
Everything goes okay i'm getting the results i need with exact num of rows from the model based on the ID which i send with the request but i have this error :
I'm trying to get the mark id based on the model selected which i have in database :
ID MARK_ID VALUE_MARK
Here is my jquery function :
$(document).ready(function(){
$("#mark").change(function() {
var markId= $("#mark").val();
if (markId!= "") {
$.get(
'upload/car_models?mark_id=' + markId,
function(data){
$.each(data, function(key, value){
$("#model").append("<option value='" + key + "'>" + value + "</option>");
})
},
"json"
);
}
});
})
And in my controller i'm doing json encode like this for the variable which is back from the model
echo json_encode($models);
How can i fix this problem with object Object.
Thanks. Any help will be appreciate.
EDIT :
Json structure :
[{"id":"50","mark_id":"50","value_mark":"Refine","value":"JAC"}, {"id":"50","mark_id":"50","value_mark":"Rein","value":"JAC"}]
Here is my json structure. id mark_id value_mark here have 2 rows returned from the model
Your data is an array of objects. WHen you loop over that array with $.each key will be index, and value will be object at that index.
Try:
$.each(data, function(i, obj){
$("#model").append("<option value='" + obj.value + "'>" + obj.value_mark + "</option>");
});
I guessed at what properties you want to assign to <option> value and text
Try this,
$(document).ready(function(){
$("#mark").change(function() {
var markId= $("#mark").val();
if (markId!= "") {
$.get(
'upload/car_models?mark_id=' + markId,
function(data){
var model=$("#model");
model.empty();
$.each(data, function(key, val){
model.append("<option value='" + val.value + "'>" + val.value_mark + "</option>");
});
},
"json"
);
}
});
})

Failed to fill 2nd drop down list with getJSON and php

I have 2 drop down lists that gets their data from a database. I want depending on the value I choose on the first drop down (#id_univ) to appear corresponding values ​​in the second drop down.
The function I created is as follows:
$("#id_univ").on("change", function(){
$.getJSON("ajax/univ_department.php",{university: $(this).val(), ajax: 'true'}, function(data){
var options = '';
for (var i = 0; i < data.length; i++) {
options += '<option value="' + data[i].id_dpt + '">' + data[i].nameDpt + '</option>';
}
$("#uni_departments").html(options);
})
})
With firebug Ι checked that returns the correct values ​​as I expected:
[{id_dpt: 1, nameDpt: 'Physics'},{id_dpt: 2, nameDpt: 'Mathematics'}]
But I don't see any value at the 2nd drop down (#uni_departments).
Any idea on what I'm doing wrong.
UPDATE
I just try the above code with jquery-1.2.3 and works fine. When I use the jquery-1.8.3, which is the default version that I'm using to my project it breaks.
Any suggestion where the problem may be, because I don't like to use older jquery!
I would try to use jquery's dom manipulation mechanism:
$.getJSON("ajax/univ_department.php",{university: $(this).val(), ajax: 'true'}, function(data){
$("#uni_departments").empty();
for (var i = 0; i < data.length; i++) {
var opt = $('<option value="' + data[i].id_dpt + '">' + data[i].nameDpt + '</option>');
$("#uni_departments").append(opt);
}
})

Categories