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/
Related
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>');
});
}
});
});
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/
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
});
});
My database contains records with included HTML scripting tags. I have read many different options on how to handle this scenario while also using json_encode/AJAX.
Should I use a JS function to escape special characters client side or might there be a PHP solution I'm missing?
Edit Assumption: The user does not want to strip/remove the html tags, just wants a way or a suggestion in to encoding them either on the server or client side!
PHP (process.php):
$records = array();
if($results = $db->query("SELECT * FROM cust_tbl")) {
if($results->num_rows) {
while($row = $results->fetch_object()) {
$records[] = $row;
}
echo json_encode($records);
$results->free();
}
}
AJAX:
function show() {
clear();
$.ajax({
type: "POST",
dataType: "json",
url: "process.php",
data: "action=show",
success: function(data) {
$.each(data, function(index, data) {
$('#tablebody').append('<tr>');
$('#tablebody').append('<td>' + data.JL_JOB_DATE + '</td>');
$('#tablebody').append('<td>' + data.JL_YR + '</td>');
$('#tablebody').append('</tr>');
});
}
});
}
If you are looking to encode HTML to be sent: you can use htmlentities()
If you are looking to remove the html tags and just leave the text: use strip_tags()
UPDATE:
I noticed in your $.each you have 2 arguments you are using data for. In a $.each what i typically do is this:
$.each(data, function() {
//use data.<column name>
});
Unless you really need the index of your data i suggest leaving it out for readability. Documentation on $.each can be found here.
Also, try doing your full append all at once.
$.each(data, function() {
$('#tablebody').append( '' +
'<tr>' +
'<td>' + data.<column name> + '</td>' +
'<td>' + data.<column name> + '</td>' +
'</tr>' +
'');
});
Doing it your way basically creates a new row then adds table datas to the end of the table instead of specifically in the tr you want it in.
use php strip_tags($records);
http://www.w3schools.com/Php/func_string_strip_tags.asp
Use underscore.js
escape_.escape(string)
Escapes a string for insertion into HTML, replacing &, <, >, ", and ' characters.
_.escape('Curly, Larry & Moe');
=> "Curly, Larry & Moe"
Added function to my code:
$.each(data, function(index, data) {
$('#tablebody').append('<tr>');
$('#tablebody').append('<td>' + escape(data.JL_JOB_DATE) + '</td>');
$('#tablebody').append('<td>' + escape(data.JL_YR) + '</td>');
$('#tablebody').append('</tr>');
});
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"
);
}
});
})