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>');
});
}
});
});
Related
I'm developing a web based inventory system. In my project i have a user management page and it has a table to view all the users.
+----------------------------------------+
+ username + user type + + +
+----------+-----------+--------+--------+
+ sample + sample + edit + delete +
+----------+-----------+--------+--------+
+ sample + sample + edit + delete +
+----------+-----------+--------+--------+
+ sample + sample + edit + delete +
+----------+-----------+--------+--------+
It has two buttons to edit user type and to delete user from the database. i need to get username from this table to php script, to execute delete query. I tried this,
$(document).on('click','.remove' ,function(){
var $item = $(this).closest("tr").find('td:eq(0)').html();
console.log($item);
<?php $username = <script>$item</script>?>
});
but i can't pass this 'username' variable to php. How to do this? Thank you :-)
To achieve this you need to perform an ajax request like this:
$(document).on('click','.remove' ,function(){
var $item = $(this).closest("tr").find('td:eq(0)').html();
$.post("url/file.php", { // your php file
username: $item
}, function(data, status){
// you will get response from your php page (what you echo or print)
});
});
PHP side:
$username = $_POST['username'];
//Do whatever you want ...
echo "success";
You can do it by Ajax, this is suggested for your code:
$.ajax({
url: "data.php",//file wich has query select to db table
data: {id:theid},//describe your data here
dataType: 'json',// type of data that will you get (JSON/HTML).
type: 'POST',//sending type (POST/GET)
success: function(data) {
//do change the select option
}
});
Goodluck!
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
});
});
TL;DR at bottom of post
I am building an application for mobile OS. This is the relevant code:
var pageId;
$(document).ready(function(){
var output = $('#output');
$.ajax({
url: 'http://dev.123456789.co.uk/db.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var linkedPage = '<h2>'+item.eventName+'</h2>'
+ '<p>Description: '+item.description+'</p><p>Type: '
+ item.type+'</p><p id="pageid">'+item.id+'</p>';
output.append(linkedPage);
pageId = $('#pageid').html();
localStorage.setItem("pageId", pageId);
});
},
error: function(){
output.text('There was an error loading the data.');
}
});
});
Basically, the code goes to a PHP file stored on our dev server and returns data from the database, in this case its eventName, description, type and id, the id being the id of the row in the database (primary key).
In each iteration it outputs the correct item.id at: '+item.id+''.
However, when you go to click each link to take you to the new page localStorage.setItem -> pageId is always the same, so it always equals 1, the first id in the database. However I need it so that when you click the link it takes you to the correct ID for each iteration.
As far as I am aware I cannot do a get/post because the application cannot read PHP because it is for a smartphone, so the data handling on the device is through javascript/data sent from JSON (and structure with HTML); any ideas?
EDIT: displaySinglePost.html:
var pageId;
$(document).ready(function(){
pageId = localStorage.getItem("pageId");
document.write("pageid: " +pageId);
var output = $('#output');
localStorage.clear();
$.ajax({
url: 'http://dev.xxxxxxx.co.uk/single.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var dataOut = '<h2>'+item.eventName+'</h2>'
+ '<p>Description: '+item.description+'</p><p>Type: '
+ item.type+'</p>';
output.append(dataOut);
});
},
error: function(){
output.text('There was an error loading the data.');
}
});
});
Too Lazy; Didn't Read:
However, when you go to click each link to take you to the new page localStorage.setItem -> pageId is always the same, so it always equals 1, the first id in the database. However I need it so that when you click the link it takes you to the correct ID for each iteration.
As far as I am aware I cannot do a get/post because the application cannot read PHP because it is for a smartphone, so the data handling on the device is through javascript/data sent from JSON (and structure with HTML); any ideas?
Do you mean to set the local storage item "pageID" on every iteration, like on your first example? You may be overwriting the value of it on every iteration(the last iteration would have an item.id of 1).
However, if you want to create a link for each id you should try:
var dataOut = '<h2>'+item.eventName+'</h2>'
+ '<p>Description: '+item.description+'</p><p>Type: '
+ item.type+'</p>';
And have php handle the id via $_GET on page.php
I am using a jquery change event using a slider to present to a user the amount of inputs that they select from the slider. I am struggling to find a way to process these results in php and insert into mysql. I would be grateful if someone could start me off with this. Thank you
for(var i = 0;i < $(this).val();i++) {
$("#boxamount").append('<div data-role="fieldcontain"><label for="boxamount" class="ui-input-text">Enter box ' + (i + 1) + ' number:</label><input type="text" name="boxamount['+i+']" id="boxamount['+i+']" class="boxamount ui-input-text ui-body-null ui-corner-all ui-shadow-inset ui-body-c" /></div>')
}
Well, you could loop over the text boxes, store the values in an object and submit them via an ajax request. Here's some rough code below.
var data = {};
$('input[name^="boxamount"]').each(function(){
data[ $(this).attr('id') ] = $(this).val();
});
Then perform an ajax request.
$.ajax({
type: "POST",
url: "yourServerScript.php",
data: data,
success: function(msg){
alert( "Data Saved: " + msg );
}
});