JSON not fetching success on codeigniter - [object Object] - php

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

Related

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

Populate select box with json data from laravel db query

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/

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

Cant seem to get CSS working on an appended table

I have an ajax request to a php file returning me rows of 3 values each.
I want to append these into a table. This works. I get my info in my table but I can't seem to add classes or id's and get some styling on it.
http://jsfiddle.net/AKh4n/1/
success : function(data) {
$('#lijstbeh').empty();
var data2 = jQuery.parseJSON(data);
$('#lijstbeh').append('<table class="table">');
$('#lijstbeh').append('<tr>');
$('#lijstbeh').append('<th>Behandeling ID</th>');
$('#lijstbeh').append('<th>Behandeling kort</th>');
$('#lijstbeh').append('<th>Behandeling datum</th>');
$('#lijstbeh').append('</tr>');
$.each (data2,function (bb) {
$('#lijstbeh').append('<tr class="tblbehandelingen">');
$('#lijstbeh').append('<td>' + data2[bb].BEH_ID + '</td>');
$('#lijstbeh').append('<td>' + data2[bb].BEH_behandelingkort + '</td>');
$('#lijstbeh').append('<td>' + data2[bb].BEH_datum + '</td>');
$('#lijstbeh').append('</tr>');
});
$('#lijstbeh').append('</table>');
}
EDIT
$(document).ready(function () {
$('.tblbehpatienten').click(function () {
var value1 = $(this).find('td:first').text();
var value2 = $(this).find('td:first').next().text();
$("#beh_voornaampat").text(value1);
$("#beh_familienaampat").text(value2);
$.ajax({
type: 'POST',
url: 'home/getbehandelingen',
datatype: "JSON",
data: {
PA_firstname: value1,
PA_lastname: value2
},
success: function (data) {
$('#lijstbeh').empty();
var data2 = jQuery.parseJSON(data);
var table_string = '<table>' + '<tr><th>Behandeling ID</th>' +
'<th>Behandeling kort</th>' + '<th>Behandeling datum</th></tr>';
$.each(data2, function (bb) {
table_string += '<tr class="tbl"><td>' + data2[bb].BEH_ID + '</td>' +
'<td>' + data2[bb].BEH_behandelingkort +'</td>' +
'<td>' + data2[bb].BEH_datum + '</td></tr>';
});
table_string += '</table>';
$(table_string).appendTo('div#lijstbeh');
};
});
});
});
It's doing my head in now. Can't seem to get it to work. Did i screw up a } somewhere?
EDIT AGAIN
}; should have been } I have it working now. Thanks!
You may want to combine your appends into one single append() statement. Otherwise, jQuery closes tags for each one. Check out the DOM after appending. Your structure looks like this:
<div id="1">
<table></table>
<tr></tr>
<th>Behandeling ID</th>
<th>Behandeling kort</th>
<th>Behandeling datum</th>
<tr class="tbl" <="" tbody=""></tr>
<td>1</td>
<td>2</td>
<td>3</td>
</div>
As you can see, that is not a valid table.
Also, in your click handler, you are referring to an element with ID "tbl", but it should be a class reference like .tbl.
I have also changed your click handler to be deferred using jQuery's on().
$('#1').append('<table>'+
'<tr><th>Behandeling ID</th>'+
'<th>Behandeling kort</th>'+
'<th>Behandeling datum</th></tr>'+
'<tr class="tbl"><td>' + "1" + '</td>'+
'<td>' + "2" + '</td>'+
'<td>' + "3" + '</td></tr>'+
'</table>');
$(document).on('click','tr.tbl',function(){
alert("dfmlgk");
});
http://jsfiddle.net/AKh4n/2/
EDIT:
Alternately, you can use appendTo().
In this example, I'm building the table as a string first. This might be more useful for dynamically generated tables. Building the table as a string can be done using append(), also; the example below demonstrates building the table as a string in addition to the appendTo() method.
var table_string='<table>'+
'<tr><th>Behandeling ID</th>'+
'<th>Behandeling kort</th>'+
'<th>Behandeling datum</th></tr>';
for (var i=1;i<=5;i++) {
table_string+='<tr class="tbl"><td>row '+i+' column 1</td>'+
'<td>row '+i+' column 2</td>'+
'<td>row '+i+' column 3</td></tr>';
}
table_string+="</table>";
$(table_string).appendTo('div#1');
$(document).on('click','tr.tbl',function(){
alert("dfmlgk");
});
http://jsfiddle.net/AKh4n/4/

How to get values from json array using javascript?

I have a PHP file which only return an array with the drivers and a url:
{"drivers":[{"marco":[0],"luigi":[123],"Joan":[2444],"George":[25]}, {"marco":[23],"luigi":[3],"Joan":[244],"George":[234]}],"url":"google.es"}
Is the json correctly structured?
And I'm trying to get the result using jQuery and AJAX by this way:
$.getJSON('calculate.php&someparams=123', function(data) {
alert("url - " + data.url);
var arr = data.drivers;
for (var i = 0; i < arr.length; i++) {
alert(arr[i] + " - " + arr[i][0]);
}
});
I see the first alert() with the url, but the second one does not works...
What am I doing wrong?
If you need more info let me know and I'll edit the post.
The drivers is not an array, it is an object, you use $.each to iterate through the object elements.
$.getJSON('calculate.php&someparams=123', function(data) {
$.each(data.drivers, function(key, value){
$.each(value, function(key, value){
console.log(key, value);
});
})
});
That's an object, not an array. It has named properties, not numerical indexes.
You need a for in loop to loop over the properties.
drivers is an object. Not an array.
How about this?
var json_string = '{"drivers":{"marco":[0],"luigi":[123],"Joan":[2444],"George":[25]},"url":"google.es"}';
var obj = jQuery.parseJSON(json_string);
alert(obj.url);

Categories