I am fairly new to js. Here I have a js script that adds a text box input on click for queries to a database using php based mysql. Each new added textbox has an id name with a successive number at the end for the number of added text boxes from the js button, like id_0, id_1, etc. I am wondering if its possible to run the php query for each successive textbox individually. The problem I am having is keeping track of how many new text boxes have been added to know how many iterations of the query I should run since the click number is a js variable. Is there a way to iterate a php query based on the number of js clicks, or specifically, a js variable? (or am i think of doing this in the wrong way?)
script to add input box:
<input id="btnAdd" type="button" value="Add" />
<br />
<br />
<div id="TextBoxContainer">
</div>
<br />
<input id="btnGet" type="button" value="Get Values" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
var click_number = 0;
$("#btnAdd").bind("click", function () {
var div = $("<div />");
click_number++;
console.log(click_number);
div.html(GetDynamicTextBox("id"+click_number));
$("#TextBoxContainer").append(div);
});
$("body").on("click", ".remove", function () {
$(this).closest("div").remove();
click_number--;
console.log(click_number);
});
});
function GetDynamicTextBox(value0) {
return '<label>Input <textarea rows="1" name="id_'+ value0 +'"><?php echo $_POST["id_'+ value0 +'"]; ?></textarea></label> ';
}
</script>
for the php part, I turn the $_POST variable into a php variable and run a simple query to the database matching the php variable to a specific column. So far I can only do this if I know how many $_POST variables there will be.
The way I do this (it may not be the best way), is to have a hidden HTML input which contains the number of textboxes you have created. Each time you add a new text box in JS you increment the value of your hidden input.
Then you can make a loop in PHP to get each POST element.
You don't need to know how many $_POST variables there are if you write the query dynamically. Just be sure that all your POST indexes match up with column names in the table:
For example, if you have:
$_POST['name']="bob"
$_POST['age'] = "102"
You can dynamically turn that into a query..
// First, for security, we should create an array
// with column names to check against to avoid SQL injection
$tableColumns = array("name", "age", "birthday", "favorite_color");
// This will contain the data that we want to insert
$insertables = array();
// Get the data from the post variables that
// are named after columns in our table
foreach($_POST as $k->$v)
if(in_array($k, $insertables))
$insertables[$k] = $v;
// Create a a query dynamically
// I'm assuming you're using PDO since you didn't specify
$sql = $pod->prepare("INSERT INTO `table` (`".implode("`, `", array_keys($insertables))."`) VALUES (:".implode(", :", array_keys($insertables)).")");
// Execute it
$sql->execute($insertables);
Now you can send any POST data you want and if the POST key exists as a column in the table it will be inserted.
Related
first post so be gentle :)... OK, I'm trying to create a very simple inventory ordering site, but i'm having issues with the following:
Let's say you have (n) items in your inventory, so based on that number i run a 'for' loop and list a hidden input field with an ID of that inventory item and display a button to order. For example:
<form>
for ($i=0; $i<$num_items;$i++) {
<input type="hidden" name="item" value="<?=$ID[$i]?>">
<input type="submit" value="Order" onclick="InsertIntoDB()">
}
</form>
Now, lets say a user want to order only 2 item out of 5 in inventory. They would click on corresponding "Order" buttons and the appropriate hidden input values would be send to DB without redirecting (it would be a seamless experience for a user where once the user clicks on buttons they want the page will not reload or redirect). Here's the script that i have for the button click:
<script type="text/javascript">
function InsertIntoDB (){
var order = $('form input[name="item"]').val();
$.post('send_to_DB.php', {updateDB:order} ); }
</script>
This is what i have for send_to_DB.php file:
|code for connecting to DB|
$writetoDB=$_POST['uptadeDB'];
foreach ($writetoDB as $n) {
$insert = "UPDATE `test` SET onorder=1 WHERE ID='$n'";
mysql_query(insert);
}
I am struggling to get those 2 values that user clicked into the DB. Any help would be much appreciated, lost many hours of sleep due to this one :). Thanks!!!
The form will send values for all the inputs in it. One way of overcoming this could be trying to enclose each set of inputs in its own uniquely identified form inside the iteration loop. But consider the following solution which will achieve the required purpose without using a form, and with a single button instead of two inputs for each item:
For the the inputs in the test.php file, assuming that array $ID is already defined:
<?php
$num_items = count($ID);
for ($i=0; $i<$num_items;$i++) {
?>
<button type="button" value="<?=$ID[$i]?>" onclick="InsertIntoDB(this.value)">Order<?= $i + 1 ?></button>
<?php } ?>
For the posting script in the test.php file:
<script type="text/javascript">
function InsertIntoDB (order){
$.post('send_to_DB.php', {updateDB:order} );
}
</script>
For the handler send_to_DB.php file:
$writetoDB=$_POST['updateDB'];
$insert = "UPDATE `test` SET onorder=1 WHERE ID='$writetoDB'";
mysql_query($insert);
In the above $insert query, you might want to use SET onorder = 1 + onorder in order to keep track of the number of orders for each item.
However.......: I hope you are aware that we should stop using mysql_query: http://php.net/manual/en/function.mysql-query.php
Try this out
<form>
for ($i=0; $i<$num_items;$i++) {
//<input type="hidden" name="item" value="<?=$ID[$i]?>">
<input type="submit" value="Order" onclick="InsertIntoDB(<?=$ID[$i]?>)">
}
</form>
So that in your script you can try this
<script type="text/javascript">
function InsertIntoDB (order){
$.post('send_to_DB.php', {updateDB:order} );
}
Where order will now have the value id of the selected order
I have a project in which I have to be able make a multiple input if needed. I'm really new to JavaScript and the insert method that I'm familiar with is only POST method which I parsed it from Form. My question is how do I do to use query in my script?
This is my code and the query is needed between Do...While at the bottom:
<div id="form" class="hidden">
Nama : <input type="text" name="nama"><br/>
Kuantitas : <input type="text" name="kuantitas"><br/>
Kategori : <select name="idKategori">
<?php
while ($rowKategori = mysqli_fetch_object($resultKategori)) {
echo "<option value='".$rowKategori->id."'>".$rowKategori->nama."</option>";
}
?>
</select>
<input type="hidden" name="hidden" value="bahan">
<input type="button" id="remove" value="Remove">
</div>
<form>
<input type="button" value="Tambah barang lain" id="add">
<input type="button" id="insert" value="Insert" style="margin-left: 50%;">
$(document).ready(function() {
var form_index = 0;
$("#add").click(function() {
form_index++;
$(this).parent().before($("#form").clone().attr("id", "form" + form_index));
$("#form" + form_index).css("display", "inline");
$("#form" + form_index + " :input").each(function() {
$(this).attr("name", $(this).attr("name") + form_index);
$(this).attr("id", $(this).attr("id") + form_index);
});
$("#remove" + form_index).click(function() {
$(this).closest("div").remove();
});
});
$("#insert").click(function() {
var i = 0;
do {
i++;
} while (i != 5);
});
im really bad at english , so let me explain it as simple as i can.
i wanted to make a form field with submit button, like the usual.
the difference is i wanted to make a clone button so i could add
more form field with single submit button.
the code that i write is something that i learn from another page and im not familiar with it.
i dont know how to get vallue from the cloned page, and i dont know how to handle the value itself in the script as i really noob at javascript
what i wanted to do is how do you get value from all cloned form field while i click the submit button? the method i familiran with is POST method, but i thinking about writedown all my query on the javascript since the POST method could not do the looping for all the formfield, thats why i make the loop on the javascript
and im sorry with my english, im not really good at it
Ok here you go, here is a fiddle of it.
https://jsfiddle.net/2ngjqxge/3/
HTML/PHP
<div id="form_block_wrapper" class="hidden"> <!-- added an outside wrapper -->
<div class="form_block" class="hidden">
Nama : <input type="text" name="nama[]"><br/>
Kuantitas : <input type="text" name="kuantitas[]"><br/>
Kategori : <select name="idKategori[]">
<?php while ($rowKategori = mysqli_fetch_object($resultKategori)): ?>
<option value="<?php echo $rowKategori->id; ?>">
<?php echo $rowKategori->nama; ?>
</option>
<?php endWhile; ?>
</select>
<input type="hidden" name="hidden[]" value="bahan">
<input type="button" name="remove" value="Remove">
</div>
</div> <!-- close #form_block_wrapper -->
<input type="button" value="Tambah barang lain" id="add">
<input type="button" id="insert" value="Insert" style="margin-left: 50%;">
Please note, I changed a number of things. Most importantly all the names of the inputs that would get submitted i added [], so nama becomes nama[] etc. Now if you were to submit this as a form, on the server side you would get arrays instead of single elements. Single elements would get overwritten by the next dynamically created "form_block" so this is what we would need to process them. The data you would expect on submission of the form would be like this ( assuming we had 3 "form_blocks" ):
$_POST['nama'] = [
0 => 'nama from first form block',
1 => 'nama from second form block',
2 => 'nama from third form block',
];
$_POST['kuantitas'] = [
0 => 'kuantitas from first form block',
1 => 'kuantitas from second form block',
2 => 'kuantitas from third form block',
];
//etc...
Next, I removed any ID's as we know ids in HTML elements must be unique, so there is no point messing with them when we are creating and destroying dynamic content. We could append an index as you originally did, but the selectors are simple enough so we don't really need to do this. And it's worth it to keep things simple, why over complicate it.
I also used the "alternative" PHP syntax for the while block. while(..): with a colon instead of while(..){ with a bracket. It just looks better to me when mixed with HTML to have the <?php endWhile; ?> insteadd of <?php } ?>. It doesn't matter much here as this is small. But after adding buches of PHP, you would have all these hanging } brackets everywhere. It's easier to keep track of the close of code blocks when they are like endIf; endWhile; etc. I also kept the HTML as HTML and not a big string that has to be echoed out, again because it looks better to me that way. It also makes dealing with the quotes " easier then having to concatenate PHP '<tag attr="'.$php.'">'.
These things you can do either way, just I'm a bit particular and a perfectionist when it comes to formatting and readability. Sort of set in my ways.
Javascript (jQuery)
(function($){
$(document).ready(function() {
//get and cache Outer HTML for .form_block
var selectHtml = $('.form_block:eq(0)')[0].outerHTML;
$("#add").click(function() {
$('#form_block_wrapper').append(selectHtml);
});
//use .on for events on dynamic content ( event delegation )
$("#form_block_wrapper").on('click', 'input[name="remove"]', function() {
$(this).closest(".form_block").remove();
});
$("#insert").click(function() {
//I have no idea what you want to do here?
//Are you trying to insert something into the page
//or Are you trying to insert the data into the DB, ie submit it to the server.
//you can serialze all the data https://api.jquery.com/serialize/
//$('#form_block_wrapper').serialize();
//you can get the selected options and get their value
var d = [];
$('select[name="idKategori[]"]').each( function(){
d.push($(this).val());
});
alert(d.join(','));
});
}); //document.ready
})(jQuery); //assign jQuery to $ - for compatibility reasons.
The first thing to do here is not clone the select but instead take a snapshot of it's html. Stored in selectHtml. There is several reasons why this is better.
if user changes the value of these fields, when we clone we have to reset all those values.
if we remove all form blocks, there is nothing to clone and we are struck on a page without our form elements, tell we refresh.
based just on the length of my code -vs- your orignal code, it should be obvious which method is simpler to handle. Simple is easy to read and maintain, do more with less.
Another thing to note, is you were attaching the remove button's event to each button as they are created. While this is ok, we can do better by using event delegation $.on to handle this element.
I still have no Idea what you want done with Insert,
do you mean insert something into the page
do you mean submit the form and insert the data somewhere.
but hopefully this helps
I work with a PHP foreach loop that generates many datas from the server. In the same time, it also generates multiple CKEditor elements matching specific datas.
To have multiple CKEditor elements, I used :
<script>
$(document).ready(function() {
CKEDITOR.replaceClass = 'ta-contribution'; //Here ta-contribution is a class
});
</script>
Instead of
<script>
CKEDITOR.replace('ta-contribution'); //Here ta-contribution is an id
</script>
Here is my php file (with a foreach loop), assuming I put off all my php variable :
<?php
foreach ($this->data as data) {
?>
<!-- blah-blah -->
<div id="contributions">
<textarea class="ta-contribution" id="ta-contribution" name="text" class="col-md-10" style="height:300%; padding: 0px;" required autofocus></textarea>
<input class="btn-contribution btn btn-primary col-md-2" type="submit"/>
<input id="num_user" type="hidden" name="num_user" value="<?=$this->numuser?>">
</div>
<!-- blah-blah -->
<?php
}?>
<!-- blah-blah -->
I want to retrieve the current CKEditor content of the button where I click for Ajax purpose.
I know we can use this to retrieve CKEditor content:
ckEditor = CKEDITOR.instances.ta-contribution.getData();
But it only works when we have one instance of CKeditor with an id, I have multiple instance with a same class.
Here is the beginning of my ajax.js file where I want to retrieve the contents :
$(document).ready(function() {
$('.btn-contribution').click(function (e) {
e.preventDefault();
//I am stuck
})
})
But I'm blocked because I can't get CKEditor contents.
How can I do that. Please help.
Your first problem is that your for loop is causing many fields to all have the same id (contributions, ta-contribution, and num_user). I'd add a counter to your loop and then append that counter to all those ids (and probably the name attributes too). Once you did that, you would be able to access them by id using the instances property as you mentioned.
You can still keep the ta-contribution class and instantiate all the editors using that class while still allowing you to access each instance by id.
CKEDITOR.replaceClass('ta-contribution');
CKEDITOR.instances.ta-contribution1.getData();
CKEDITOR.instances.ta-contribution2.getData();
CKEDITOR.instances.ta-contribution3.getData();
Hi i have three check box where i want that which one check box i select regarding that check box value should retrieve from database
Here is my check box
<input type="checkbox" name="test" value="X-Ray" style="margin-top:10px;margin-left:120px;"><label>X-Ray</label>
<input type="checkbox" name="test" value="Ecg" style="margin-top:10px;margin-left:20px;"><label>ECG</label>
<input type="checkbox" name="test" value="Blood Test" style="margin-top:10px;margin-left:20px;"><label>Blood Test</label>
mysql query
SELECT SUM(price) from test where test='x-ray' or test='' or test='bloodtest'
how can i get my desired output? Any help will be appreciated.
You could get a hold on the specific input checkbox using the jquery selector :checked. So something like this in your javascript should get you started :
$( "input" ).on( "click", function() {
var sel = $( "input:checked" ).val();
//Here you can just make a simple ajax request to a php script passing the
//specific checkbox value and let that script perform the mysql query.
$.post( "test.php", { test: sel })
.done(function( data ) {
alert( "Completed");
});
});
Your test.php script could look something like this:
<?php
$test = $_POST["test"];
//Replace with your sql database credentials
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT SUM(price) from test where test='".$test."'");
mysqli_close($con);
?>
This is a barebone starting template of how you could proceed with your problem. Ofcourse, the specific use case could vary. For instance you could make a get request instead of a post request and make your php script interact and fetch data differently.
I just gave you an example of how the workflow would look like in simple jquery and php. So you just get the value of input checkbox and pass on the value to a script that interacts with the database and fetches the specific SUM. You should probably read some documentation on Jquery Ajax or PHP Mysql to get a better hang of this. Hope it helps.
I think that the best solution to this is to output all the prices as a JavaScript variable somewhere on the page, Let's alter the HTML a little bit.
<input type="checkbox" class="chkbox-update" name="test" value="X-Ray"><label>X-Ray</label>
<input type="checkbox" class="chkbox-update" name="test" value="Ecg"><label>ECG</label>
<input type="checkbox" class="chkbox-update" name="test" value="Blood Test"><label>Blood Test</label>
Now, the prices. Use PDO to itterate through results and construct a JSON-formatted variable:
<script>
var prices = {"X-ray": 3900, "ECG": 2000, "Blood Test": 1200};
</script>
Then use JavaScript to update the price field, I'm using jQuery for this.
$('.chkbox-update').click(function() {
var total;
$.each($('.chkbox-update'), function(k,v) {
total += prices[$(this).val()];
});
$('#result').text('The total price is '+total);
});
Make Sure that the key for the prices variable matches the value of the <input>
I want to develop a webpage wich dynamically adds and removes particular webforms (all webforms with the same structure) on the page (when pressing add and remove buttons). Adding and removing the webforms already works in the code below (using a jquery function), but I still struggle to create the related unique name values when submitting more forms. My idea is:
- to put all forms in an array (forms() )- each with unique name values
- ...and maintain in a array (formsavailable()) which forms have been added/used and which have been removed.
I already added the code (below) to maintain formsavailable() when adding forms. But I dont know how to code formsavailable() for removing forms.
Any ideas? Or are there simpler ways for creating the unique name value's with the described context?
Please your comments.
Thank you.
The code:
<script>
var forms = Array();
var formsavailable = Array();
forms = getProductconfigforms(); //create a list of strings with the product forms
var NUMBER_OF_FORMS = 5;
for (var i=1; i<=NUMBER_OF_FORMS;i++)
{
formsavailable[i] = true; //at the start all forms are
}
//script for adding and removing productss
$(document).ready (function () {
var i;
$('.btnAdd').click (function () {
i = formsavailable.indexOf(true);
$('.buttons').append(forms[i]); // end append
formsavailable[i] = false;
$('div .btnRemove').last().click (function () {
$(this).parent().last().remove();
}); // end click
}); // end click
}); // end ready
</script>
</head>
<body>
<h2> text here </h2>
<div class="buttons">
<input type="button" class="btnAdd" value="Add"><br>
</div>
<p> tekst </p>
<input type="button" value="Terug naar stap 1" onclick="goBack()">
</body>
You actually don't need to make a unique index or unique name. The HTTP protocol supports sending multiple data points with the same name.
For example, this is totally fine: &name=me&name=you&name=them&name=her. On the back end, depending on which framework and language you are using, you simply get an array.
So in your form, you can use
<label> Product 1 <input name="product_name" type="text" /></label>
<label> Product 2 <input name="product_name" type="text" /></label>
...
And so on, until you've added however many forms you wish. When you submit the form, your page will automatically take care of sending them on to your backend form, where you can parse out each form programmatically.