This question already has answers here:
Fetching data from MySQL database to HTML dropdown list
(4 answers)
Closed 7 years ago.
<script type="text/javascript">
var rowNum = 0;
function addRow(frm) {
rowNum ++;
var row = '<p id="rowNum'+rowNum+'"> Barang: ';
row += '<select name="???">';
row += '<option value="A1">A1</option>';
row += '<option value="A2">A2</option>';
row += '<option value="A3">A3</option>';
row += '<option value="A4">A4</option>';
row += '</select>';
row += ' Satuan: <input type="text" size="5" name="satuan[]" value="'+frm.add_satuan.value+'"> Quantity: <input type="text" name="qty[]" value="'+frm.add_qty.value+'"> <input type="button" value="Remove" onclick="removeRow('+rowNum+');"><hr color=red></p>';
$('#itemRows').append($(row));
frm.add_qty.value = '';
frm.add_nama.value = '';
frm.add_satuan.value = '';
};
</script>
How to make drop-down list but with query mysql to show A1, A2, dll.
When submit button for drop-down can't post data anything. Can I store data with this javascript. For text input success post data.
DO NOT DO WHAT YOU ARE TRYING TO DO. You should never, ever, ever write queries on the front-end. You should do your absolute best to hide every detail of the server/database from the user. It is a massive security risk. Please read about SQL injection attacks for starters.
How you should do this:
Store the values of the dropsdowns in JavaScript. Let's keep them in a single object to make life easy:
Your JS:
var options = {
A1: $("#rowNum select option[value='A1']").text(),
A2: $("#rowNum select option[value='A2']").text(),
A3: $("#rowNum select option[value='A3']").text(),
A4: $("#rowNum select option[value='A4']").text()
};
// Now, send this object to your PHP via an AJAX call. Let's assume for simplicity that you will do this using jQuery:
$.ajax({
url: 'my/php/script.php',
data: options,
success: function (data) { console.log('Yay, it worked!'); },
error: function (jqXHR, textStatus, error) { console.log('crap it didn't work', jqXHR, textStatus, error); }
});
Your PHP
<?php
$options = $_REQUEST['options']
// You need to verify the options are valid (and don't have bad values) but that's a different question
// Build your query here. Your PHP is run on the server only so no one else will see it or be able to change it.
You can try this code with some modification. Use jQuery's each to iterate over the array value.
$('#emptyDropdown').empty();
// Parse the returned json data
//var opts = $.parseJSON(data);//Remove comment if you are using JSON
// Use jQuery's each to iterate over the opts value
$.each(opts, function(i, d) {
// You will need to alter the below to get the right values from your data.
$('#emptyDropdown').append('<option value="' + d.yourID + '">' + d.yourValue + '</option>');
});
Related
I'm creating a data entry page using JS, jQuery and PHP for a MySQL database with about 250 fields in a client table. I didn't want to have to deal with passing so many fields individually
between JS and PHP so I wrote a function to iterate through all the data entry elements and build the entire SQL insert statement to pass to PHP. For each data entry element I
created a custom attribute "fieldname" containing the name of the corresponding database field, as in this example.
<input type='text' fieldname='first_name' ID='txtFirstName' maxlength=25>
Below is the JS function and PHP code. I've tested it and it works but the idea of passing an entire huge SQL statement like this seems peculiar.
If anyone has had a similar requirement for passing large numbers of fields I'd like to know about alternative solutions.
function InsertRecord() {
// Iterate through every data entry element with the "fieldname" attribute to create the field list for the SQL statement
sql_cmd='insert into clients('
$('[fieldname]').each( function() {
sql_cmd=sql_cmd + $(this).attr('fieldname') + ',';
});
sql_cmd=sql_cmd.slice(0, -1) + ') values('; // slice gets rid of the last character (trailing comma)
// Iterate again to get the values
$('[fieldname]').each( function() {
sql_cmd=sql_cmd + "'" + $(this).val().replace(/'/g, "''") + "',"; // replace single quotes in values with 2 single quotes
});
sql_cmd=sql_cmd.slice(0, -1) + ')';
$.ajax({
type: 'POST',
url: 'nwcs.php',
data: { sql: sql_cmd },
dataType: 'text',
success: function(data) { alert(data) },
error: function(jqXHR, textStatus, errorThrown) { alert('Error', '<B>' + errorThrown + '</B>'); } });
}
PHP code:
if (mysqli_query($conn, $sql)) {
echo 'Record added';
}
else {
header('HTTP/1.0 500');
die('Unable to insert record due to database error: ' . mysqli_error($conn));
}
Never build your SQL Query in the client side of your application. This is a huge security concern. Anyone can run any arbitrary query directly to your database this way leaving breaches to someone run something like mentioned in the comment by #VLAZ.
The easiest way I can think of is naming your fields with a prefix like table_1, table_2 ...
This way you can iterate through your $POST array looking for your table_ prefix.
foreach($_POST as $key => $value){
if (startsWith($key,"table_"))
{
// Append to your query string or something
}
}
Also, be aware of SQL Injection attacks which would be possible without user input filtering. You can start learning about it at the OWASP website(https://owasp.org/www-community/attacks/SQL_Injection)
You could do something along the lines shown below:
// simplified Vanilla JavaScript version of jQuery.post:
function post(url,data,cbf){ // cbf: callback function
var xhr = new XMLHttpRequest();
xhr.open('POST',url);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {if (xhr.status === 200) {cbf&&cbf(JSON.parse(xhr.responseText));}};
xhr.send(Object.keys(data).map((k) => encodeURIComponent(k) + '=' + encodeURIComponent(data[k])).join('&'))
}
// scan all input fields:
document.querySelector('.go').onclick=ev=>{
ev.preventDefault();
let dat=[...ev.target.closest('form').children].reduce((a,c)=>{
if (c.tagName=='INPUT' && c.value>'') a[c.name]=c.value;
return a;
}, {});
console.log(dat); // show data for upload in console
// -- uncomment the next line to activate the posting of data:
// post('nwcs.php',dat,response=>console.log(response))
// -- (the above will not work from stackoverflow.com)
}
<form name="frm">
<input type='text' name='first_name' ID='txtFirstName' maxlength=25 placeholder='first name'><br>
<input type='text' name='last_name' ID='txtLastName' maxlength=25 placeholder='last name'><br>
<input type='text' name='email' ID='txtEmail' maxlength=25 placeholder='Email'><br>
<input type='text' name='phone' ID='txtPhone' maxlength=25 placeholder='Phone'><br>
<button class="go">save</button>
</form>
The actual post() can not happen in this snippet, but the Vanilla JavaScript function post() should do that job for you in your "real" environment.
Your backend script nwcs.php then needs to pick up the JSON string and create some safe insert statements from it. Hint: use prepared statements!
Hello my masters,
I want to update (link_name, link_address, link_type). Link_type with tag in HTML page feed. I know many code exist in internet about CURD but I don’t know why my code don’t execute correctly. There is some problem that I mention in following, maybe long so first of all apologize.
First part: fetching data from DB with Ajax. In editlink.blade.php
try {
for(var count=0; count < data.length; count++)
{
html +='<tr >';
html +='<td contenteditable class="column_name" data-column_name="link_name" data-id="'+data[count].id+'">'+data[count].name+'</td>';
html += '<td contenteditable class="column_name" data-column_name="link_add" data-id="'+data[count].id+'">'+data[count].Address+'</td>';
html += '<td contenteditable class="column_name" data-column_name="link_type" data-id="'+data[count].id+'">' +
'<select id="opttypes" value="'+data[count].id+'">' +
'<option id="opt1"'+ check_selected1(data[count].type)+' value="1"'+' >'+d1+'</option>' +
'<option id="opt2"'+ check_selected2(data[count].type)+' value="2"'+' >'+d2+'</option>' +
'<option id="opt3"'+ check_selected3(data[count].type)+' value="3"'+' >'+d3+'</option>' +
'<option id="opt4"'+ check_selected4(data[count].type)+' value="4"'+' >'+d4+'</option>' +
'</select>' +
'</td>';
html += '<td><button type="button" class="btn btn-danger btn-xs delete" id="'+data[count].id+'">Delete</button>' +
'<button type="button" class="btn btn-success btn-xs edite" id="'+data[count].id+"_"+count+'">Update</button></td></tr>';
}
$('tbody').html(html);
}// end try
catch (e) {
document.getElementById("demo").innerHTML = "error accrue in fetch form DB ";
}
Description first part:
1) Data is backed variable from Ajax, that include weblinks table in DB.
2) Spread count in edit button use to refer row in table and then fetch content of cell.
Second part: java code of edit button in editlink.blad.php
$(document).on('click', '.edite', function(){
var allid=$(this).attr("id").split("_");// try to access id of data and number of row in HTML table
var id2=allid[0];// fetch ID of data in DB
var countRow=Number(allid[1])+2;// calculate detected row that user clicked.
var link_name = document.getElementById("html_table").rows[countRow].cells.item(0);// gets links name
var link_add =document.getElementById("html_table").rows[countRow].cells.item(1);// gets link address
var link_type=$("#link_type :selected").val();// gets which option user clicked.
if(link_name != '' && link_add != '' && link_type!='' )
{
if(!confirm("Do you want to edit this row")) {
return false;
}
try
{
$.ajax({
url:"{{ route('weblink.update_data') }}",
method:"POST",
data:{link_name:link_name, link_add:link_add, link_type2:link_type, id:id, _token:_token},
success: function(data){ // What to do if we succeed
if(data == "success")
$('#message').html(data);
},
error: function(data){
alert('Error'+data);
}
})
}
catch (e) {
$('#message').html("<div class='alert alert-danger'>error in receiving data from Ajax </div>");
}
}// end if check empty box
else {
$('#message').html("<div class='alert alert-danger'>Both Fields are required</div>");
}
});
Description this part
1) When I click update button option tag showed -1 that refer the first option which isn’t useful. I use this code for add button work correctly but I don’t know why in this function doesn’t work.
Third part: Function in controller
function update_data(Request $request)
{
if($request->ajax())
{
weblink::where('id', $request->id)->update([
'name' => '$request->link_name',
'Address'=>'$request->link_add',
type=>'$request->link_type2'
]);
echo '<div class="alert alert-success">Data Updated</div>';
}
}
Description this part
1) Weblink is model
Fourth part: web.php for update
Route::post('/weblink/update_data', 'weblinksController#update_data')->name('weblink.update_data');
Excuse me every one, I know my code is boring. If possible help me.If every one like please give me your mail I will send all of my code completely(View, Controller and web).
Best regards.
I have a select box that I is been populated by jQuery. The options are gotten from the server via a REST call and are then used to populate the select box.
The application is also supposed to work offline but when offline these REST calls fail. So what I'm doing is when the REST calls actually pass, I store these values inside localStorage and when offline and the REST call fails, I just get the stored values inside the localStorage and try to populate the select box.
However the select boxes still appear empty. I've printed the stored values in the console and it shows that these values where actually successfully stored and retrieved. I'm not sure why my select boxes still appear empty.
$.getJSON("/openmrs/ws/rest/v1/location", function(result) {
var locations = $("#identifierLocations");
localStorage.setItem("locations", result.results);
$.each(result.results, function() {
locations.append($("<option />").val(this.uuid).text(this.display));
});
}).fail(function(jqXHR, textStatus, errorThrown) {
var data = localStorage.getItem("locations");
if (data) {
var locations = $("#identifierLocations");
for (var i = 0; i < data.length; i++) {
locations.append($("<option />").val(data[i].uuid).text(data[i].display));
}
}
});
I used console.log inside .fail() and I can confirm that data actually has all stored location objects but why does my select box still appears empty.
The issue is because localStorage can only hold strings. You need to serialise the result.results before storing them, then deserialise when retrieving them. Try this:
$.getJSON("/openmrs/ws/rest/v1/location", function(result) {
localStorage.setItem("locations", JSON.stringify(result.results));
populateLocations(result.results);
}).fail(function(jqXHR, textStatus, errorThrown) {
var data = localStorage.getItem("locations");
if (data) {
populateLocations(JSON.parse(data));
}
});
function populateLocations(locations) {
var html = locations.map(function(o) {
return '<option value="' + o.uuid + '">' + o.display + '</option>';
}).join('');
$("#identifierLocations").html(html);
}
I have a multiple select item, which allows me to check multiple items. I want to send those selected items via ajax request and afterwards I want to import the those items into my database. My problem is, that I don't know how to loop thru the passed array, which I get by the POST request.
Ajax Request
function insertPlayers(){
var data = $("#playerCards").serialize();
$.ajax({
url: "/database/playercards.php",
type: "POST",
data: data,
success: function (response) {
}
});
}
This is my HTML multiple select:
<select multiple id="assignAccount" name="assignAccount" class="form-control select">
// Options inserted by JQuery later
</select>
This is how my data looks like when I alert it before sending the Ajax Request:
playersearch=test&buypercentage=85&assignAccount=9&assignAccount=10&assignAccount=11
How I add the options to my multiple selectbox:
// loop the response
$.each(response, function(i, e){
// just use your column names, these are just an example, but you get the idea
opt += '<option value="'+e.id+'">'+ e.email + ' - ' + e.coins + '</option>';
});
// append the markup to that select box
$('#assignAccount').html(opt)
My problem:
It should be clearly now that the assignAccount variable is a array which I want to loop thru in PHP but I don't know how I can do this because I don't know the indices. This is what I've tried:
$accountIds = $_POST['assignAccount'];
foreach ($accountIds as $account){
echo $account;
}
Change
<select multiple id="assignAccount" name="assignAccount" class="form-control select">
to something more like
<select id='assignAccount' name='assignAccount[]' multiple='multiple' class='form-control select'>
make the select statement multiple id an array
<select name='assignAccount[]' id='assignAccount[]'>
on your php page you will now have an array for this post.
$_POST['assignAccount'][0]
$_POST['assignAccount'][1]
and so on.
The select element when multiple send data like this:
playersearch=test&buypercentage=85&assignAccount=9,10,11
Hence, in the PHP side you do this:
$accountIds = explode(",", $_POST['assignAccount']);
foreach ($accountIds as $account){
echo $account;
}
I have an empty form tag, and a function which generates 4000 hidden inputs which contains the data to be send by the form.
Generating the 4000 hidden inputs is pretty fast (takes about 4ms). However, the browser freezes for about 1 second when i am appending the hidden inputs in the form tag.
I have also wrapped the hidden inputs in a <div/> tag, but doesn't helps too much.
Is there any way to set the form data programmatically, without using the input DOM elements?
Something like:
$form[0].setData([{ id: 1, value: "A" }, { id: 2, value: "B" }]);
$form.submit();
Here is the function which generates the hidden inputs
function saveUIPositions() {
var $form = $("#saveUIPositionsForm");
$form.empty();
console.time("ui");
var array = [];
array.push("<div>");
var items = dataTable.dataView.getItems();
for (var i = 0, len = items.length; i < len; i++) {
var item = items[i];
var index = dataTable.dataView.getRowById(item.Id) + 1;
array.push("<input type='hidden' name='[");
array.push(i);
array.push("].Item_Id' value='");
array.push(item.Id);
array.push("' />");
array.push("<input type='hidden' name='[");
array.push(i);
array.push("].Index' value='");
array.push(index);
array.push("' />");
}
array.push("</div>");
console.timeEnd("ui");
// here it gets very costly (and not because of array.join())
$form.append(array.join(""));
$form.submit();
};
Maybe you can send this data using ajax ? If so you will not have to generate and append your 4K hidden inputs to the DOM.
If ajax is not an option, can you give us the code generating and appending your inputs ? Maybe it can be optmized.
I wrote a small jsFiddle (open your debug console to see time informations)
to illustrate the difference between a generate then append all solution:
for(var i=0; i<4000; i++)
inputs += '<input type="hidden" value="' + i + '"/>'
$('form').append(inputs);
and generate and append each:
for(var i=0; i<4000; i++)
$form.append('<input type="hidden" value="' + i + '"/>');
You don't even really need a form element when working in just Javascript, data can be sent to your server with an ajax request.
$.ajax({
url: "myScript.php", //The script on your server that deals with the data
data: {
dataA: "a",
dataB: "b",
dataC: "c" //Your form input name and value key pairs
},
success: function(data){
alert("Form Submitted, Server Responded:"+data); //The server response
},
error: function(data){
alert("Error contacting server:"+data); //Error handler
}
});
You don't even need to reload the page when the form is submitted. Unless you want to, then just add:
location.href="http://link.com";
to the success callback.
You don't need to add the inputs to the DOM, you could create an array of the data an post the form via ajax e.g.
inputNames = 'YourInputNameHere'; // Could be an array of names
generatedData = arrrayOfData //presumably generated elsewhere
for (i=0;i<400;i++) {
formData[inputName][i] = generatedData[i]
// if you are using an array of names you want to change the above line to
// formData[inputName[i]] = generatedData[i]
}
$('body').on('submit', '#myForm', function(e) {
e.preventDefault();
postUrl = 'url/to/send/data';
// get any other use inputs that might have been taken from user ignore
// this line if there are no inputs
formData[] = $(this).serialize();
$.ajax(
{
url: postUrl,
type: 'POST',
data: formData,
dataType: 'html',
success: function( data )
{
// redirect, post message whatever
}
}
)
});
Hope this helps and makes sense.