I am using javascript for getting dropdown select id id='odrid',
here is the script:
$('#odrid').change(function(){
$.getJSON(
'fetch.php',
'odrid='+$('#odrid').val(),
function(result){
$('#item').empty();
$.each(result, function(){
$('#item').val(this['item']);
});
}
);
});
This drop down script runs in another script for adding dynamic form field:
<script>
$('#odrid').change(function(){
$.getJSON(
'fetch.php',
'odrid='+$('#odrid').val(),
function(result){
$('#item').empty();
$.each(result, function(){
$('#item').val(this['item']);
});
}
);
});
$(function() {
// register listener
$('.form-control1').on("change.add", calculateSum);
// initial calculation
calculateSum();
// button for adding new row
$(".addmore").click(function() {
$('.form-control1').off("change.add");
//addRow();
var count = $('#counter').val();
$("<tr>" +
"<td><input type='checkbox' class='case'/></td>" +
"<td><select id='odrid'><?php
$query = mysql_query('select * from cart_sample');
while($row = mysql_fetch_assoc($query)) {
echo '<option value='.$row['odrid'].'>'.$row['odrid']. '</option>';
}
?></select></td>" +
"<td ><input id='item' type='text' name='txt_quantity[]' value='' /></td>" +
"</tr>").insertAfter("tr:last-child");
count++;
$('#counter').val(count);
$('.form-control1').on("change.add", calculateSum);
calculateSum();
});
</script>
this is my front end:
The problem is that I didn't get the value of #item in my output.
How can I fix this issue? does anyone know the problem in my code?
Thanks in advance!
i think the problem is with your id
you are using $("#item") in your jquery and you have defined items as your id
<input id='items' type='text' name='txt_quantity[]' value='' />
change it to item
<input id='item' type='text' name='txt_quantity[]' value='' />
or change
$("#items") in jquery
and it should work as expected
Related
I'm trying to POST submit the data to mysql using php from append javascript.
Here's the modal where data come from append which is in php.
<tr onload="calculate()">
<?php
foreach ($conn->query("SELECT * FROM panapricelist") as $info){
echo "<td><input type='checkbox' id='promotitle' name='check' value='".$info['ProductId']."' ></td>";
echo "<td><textarea rows='4' cols='7' maxlength='60' name='pcode' class='pcode' id='ProductCode' disabled>".$info['ProductCode']."</textarea></td>";
echo "<td><br><textarea rows='5' cols='40' maxlength='50' name='puse' class='productuse' id='productuse' disabled>".$info['ProductUse']." </textarea></td>";
echo "<td><br><textarea rows='4' cols='50' maxlength='50' name='pdesc' class='description' id='productDesc' disabled>".$info['ProductDesc']."</textarea></td>";
echo "<td id='msrp'><textarea rows='4' cols='10' maxlength='50' name='Msrp' class='msrp' id='productMsrp' disabled>".$info['Msrp']."</textarea></td>";
echo "<td style='width: 10%;'><textarea rows='4' cols='10' name='cost' maxlength='50' class='cost' id='cost' disabled>".$info['DealerPhp']."</textarea></td></tr>";
}
?>
</tbody>
Here's the append js from modal to table.
$(document).ready(function() {
$("#button_add").click(function() {
var favorite = [];
$.each($("input[name='check']:checked").each( function() {
// favorite.push($(this).val());
var getRow = $(this).parents('tr'); //variable for the entire row
var value = (getRow.find('td:eq(1)').html()); // Product Code
var value1 = (getRow.find('td:eq(2)').html()); // for Suggested Product Use
var value2 = (getRow.find('td:eq(3)').html()); // for product Description
var value3 = (getRow.find('td:eq(4)').html()); // for MSRP PHP
var value4 = (getRow.find('td:eq(5)').html()); // for Dealer PHP
var value5 = (getRow.find('td:eq(0)').html()); // for Dealer PHP
$('#item-row').append('<tr><td class="item-name"><textarea value="'+ value +'</textarea></td><td class="item-name"><textarea class="check" name="check[]" value= "' + value1 + ' </textarea> </td><td class="item-name"><textarea value= "' + value2 +' </textarea></td><td class="item-name"><textarea value= "' + value3 + ' </textarea> </td><td><textarea name="Msrp" value="' + value4 + '</textarea></td><td class="item-name"><textarea class="qty" id="qty" name="qty[]"> </textarea></td><td class="item-name"><textarea id="price" class="price" name="price[]" disabled></textarea></td></tr>');
}));
});
});
Questions is. how can i POST submit to mysql using PHP PDO the value come from append javascript??
You'll need to put any input data inside of a form, then create a PHP script that handles the POST request and INSERTS the data into your MySQL database.
Your form tag should look something like this:
<form class="post-form" action="script_that_handles_post.php" method="post">
So, you'll want to use $_POST['']. For example, the name in your first table row is name="check", you'll use $_POST['name'] to get the value of that field. Do that for each field that you want to store. Preferably, you should store each of those in their own variables or an array.
Then, for your AJAX you'll have to include the library somehow. If you aren't already, put this in your footer below the jquery source:
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
Now you can add your AJAX POST request. Here's some code that should do it:
$(".post-form").submit(function (event) {
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
url:$form.attr('action'),
type:'POST',
data: serializedData
});
request.fail(function (jqXHR, errorThrown){
console.error(
"Error: " + errorThrown
);
});
request.always(function () {
$inputs.prop("disabled", false);
});
event.preventDefault();
});
What this code is doing is taking the action path of your form and posting the data from the inputs of the fields there.
I hope this helps.
I am looping through data form a database to a form that makes a Ajax request to add an item to a shopping basket/cart. Everything works fine except that only the first item in the array is added? I have tried using classes as apposed to id's(unique
echo "<div class='col-100 border-temp bg-orange'>";
echo "<div class='col-50 border-temp'>";
foreach ($result as $key => $result) {
$m = $result["model_no"];
$q = $result["qty_available"];
echo "<form method='post' action='/stock-clearance' class='stock_clearance bg-blue'>";
echo "<label for='model_no'><h2>Model No</h2></label>";
echo "<input id='model_no' name='model' type='text' placeholder='Paste model no... ' value='$m' />";
echo "<span id='model_error'></span>";
echo "<label for='quantity'>Quantity</label><br />";
echo "<input id='quantity' name='quantity' value='1' type='number' min='1' max='$q'>";
echo " <span id='quantity_error'></span>";
//echo "<input id='sc_add_to_cart' name='' value='$key' type='button'>";
echo "<input id='sc_add_to_cart' name='sc_add_to_cart' value='Add to Basket' type='submit'>";
echo "</form>";
} // End foreach loop
echo "</div>";
)
My JS code is as follows:
$('#sc_add_to_cart').on('click', function(e) {
e.preventDefault();
var form = $('.stock_clearance');
hideStockClearanceMessages(form);
var request = $.ajax({
beforeSend: function() { form.css({ opacity: 0.4 }); },
url: 'ajax.php',
cache: 'false',
data: {
action: "sc-add-to-cart",
model: $('input[name="model"]').val(),
quantity: $('input[name="quantity"]').val()
}
});
enter image description here
You can not have the same one ID for a different inputs. ID must be UNIQUE. Instead of ID use CLASS attribute
1- Sometimes because of caching problem it will not work so you have to add seed to your call.
seedrandom()
function seed() {
return Math.floor((Math.random() * 10000) + 1);
}
$('#sc_add_to_cart').on('click', function(e) {
e.preventDefault();
var form = $('.stock_clearance');
hideStockClearanceMessages(form);
var request = $.ajax({
beforeSend: function() { form.css({ opacity: 0.4 }); },
url: 'ajax.php?sid=' + seed(),
cache: 'false',
data: {
action: "sc-add-to-cart",
model: $('input[name="model"]').val(),
quantity: $('input[name="quantity"]').val()
}
});
Please use IDs only for one element. They must be unique. You can use CLASS instead.
I have a form with the option to add another row at the click of a button.
This new row will have a select list as it's input type.
The select list needs to process information from a database that was retrieved on page load.
How can I have the new select list perform a while loop on the data from the database once it is created via the add button.
Here is the code I have so far.
PHP:
echo "<div id=\"FieldGroup\">";
echo "<select name=\"add_project_service_1\" class=\"project_details_service\" value=\"\" required >";
while($result->fetch())
{
echo "<option value=\"".$item_number."\">".$item_number." - ".$description."</option>";
}
echo "</select> ";
echo "<label>Quantity: </label><input type=\"text\" name=\"add_project_quantity_1\" class=\"project_details_quantity\" placeholder=\"Quantity\" value=\"\" /> ";
echo "<label>Value: </label><input type=\"text\" name=\"add_project_value\" class=\"project_details_value\" placeholder=\"Value\" value=\"\" /><br>";
echo "</div>";
echo "<input type=\"button\" value=\"Add Button\" id=\"addField\"><input type=\"button\" value=\"Remove Button\" id=\"removeField\">";
Javascript:
<script>
$(document).ready(function() {
var counter = 2;
$("#addField").click(function () {
if(counter>50){
alert("Only 50 extra fields allowed.");
return false;
}
var newFieldDiv = $(document.createElement('div'))
.attr("id", 'FieldDiv' + counter);
newFieldDiv.after().html('<select name="add_project_service_' + counter + '" class="project_details_service" value="" required >' +
'while($result->fetch())
{
echo "<option value=\"".$item_number."\">".$item_number." - ".$description."</option>";
}</select> ' +
'<label>Quantity: </label><input type=\"text\" name=\"add_project_quantity_' + counter + '\" class=\"project_details_quantity\" placeholder=\"Quantity\" value=\"".$quantity."\" /> ' +
'<label>Value: </label><input type=\"text\" name=\"add_project_value_' + counter + '\" class=\"project_details_value\" placeholder=\"Value\" value=\"".$value."\" /><br>');
newFieldDiv.appendTo("#FieldGroup");
counter++;
});
$("#removeField").click(function () {
if(counter==2){
alert("No more fields to remove.");
return false;
}
counter--;
$("#FieldDiv" + counter).remove();
});
});
</script>
Inserting the while loop into the javascript doesn't work.
How can this be accomplished so when I add a field the options are listed and fields are populated?
javascript is exectued on client side while php interpreted on the server side.
Once you've send the page to the client, the only way to edit the page without reloading a new one is with javascript and ajax call (xmlhttprequest). The client doesn't use php neither download php page from the server.
You could do an ajax call to your page with jquery
$.ajax{
url: "mypage.php",
type: "GET",
dataType: "jsonp",
success: function( myObject ) {
console.dir( myObject );
}
}
// mypage.php
header('Content-type: application/json');
echo json_encode( $myObject );
// for you it will be
echo json_encode( $result->fetch() );
I have a table and a script that makes each cell an input field when clicked on the edit button at the end of a row.
I submit the edited data via Ajax, but I want to make the input field back to normal text after I have edited it.
Here is the code:
//// EACH CELL INTO INPUT FIELD ////
$(document).ready(function(){
$(".edit").click(function(){
var tr = $(this).closest("tr");
tr.find(".td").each(function(){
var name = $(this).attr("title");
var value = $(this).html();
var input = "<input type='text' name='"+name+"' value='"+value+"' />";
$(this).html(input);
});
var submit = "<input type='button' name='Submit' value='Submit' />";
tr.find(".button").html(submit);
});
});
//// END ////
//// ONCLICK SUBMIT SEND DATA VIA AJAX ////
$(".button input[type=button]").live('click', function() {
var data = $('form#muuda').serialize();
// post data using ajax
$.ajax({
type: "POST",
url: "index.php?leht=kast",
data: data,
success: function(data) {
alert("Andmed muudetud"); // show response from the php script.
}
});
});
//// END ////
HTML:
<form id="muuda" method="post" action="#">
<table>
<?PHP
$sql="SELECT * FROM nimed";
$result = mysql_query($sql)or die(mysql_error());
WHILE ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo '<tr class="row">';
echo '<td class="td" title="id">'.$row["id"].'</td>';
echo '<td class="td" title="eesnimi">'.$row["eesnimi"].'</td>';
echo '<td class="td" title="perenimi">'.$row["perenimi"].'</td>';
echo '<td class="button" title="button"><button class="edit">Edit</button></td>';
echo '</tr>';
}
?>
</table>
</form>
Here is a picture of the preview:
https://lh6.googleusercontent.com/-vVnabdBzFlA/UBjTRhifpWI/AAAAAAAACAo/RvAgpi7x2ik/s488/Ajax%2520submit.jpg
You can just reverse the process you use to turn it from text to an input box:
tr.find('.td').each(function () {
var value = $(this).find('input').val();
$(this).html(value);
});
You will have to set the variable tr to the right row, of course.
id car make sales
1 panamera porsche 100
2 italia ferrari 200
3 volante astonmartin 300
4 avantador lamborghini 400
5 slk mercedes 500
So guys, i have this simple table in my database. And i'm gonna echo this table in a while loop.
<ul>
<?php
$query = "SELECT * FROM inplace LIMIT 0, 6";
$result = mysql_query($query) or die ('Query couldn\'t be executed');
while ($row = mysql_fetch_assoc($result)) {
echo '<li class="editable" id="'.$row['id'].'">'.$row['car'].'</li>';
echo '<li class="editable2" id="'.$row['id'].'">'.$row['make'].'</li>';
}
?>
</ul>
The idea is to update this table using jQuery in-place editor. So here is the code-
$(document).ready(function()
{
$(".editable").bind("dblclick", replaceHTML);
$(".editable2").bind("dblclick", replaceHTML2);
$(".btnSave, .btnDiscard").live("click", handler);
function handler()
{
if ($(this).hasClass("btnSave"))
{
var str = $(this).siblings("form").serialize();
$.ajax({
type: "POST",
async: false,
url: "handler.php",
data: str,
});
}
}
function replaceHTML()
{
var buff = $(this).html()
.replace(/"/g, """);
$(this).addClass("noPad")
.html("<form><input type=\"text\" name=\"car\" value=\"" + buff + "\" /> <input type=\"text\" name=\"buffer\" value=\"" + buff + "\" /><input type=\"text\" name=\"id\" value=\"" + $(this).attr("id") + "\" /></form>Save changes Discard changes")
.unbind('dblclick', replaceHTML);
}
function replaceHTML2()
{
var buff = $(this).html()
.replace(/"/g, """);
$(this).addClass("noPad")
.html("<form><input type=\"text\" name=\"make\" value=\"" + buff + "\" /> <input type=\"text\" name=\"buffer\" value=\"" + buff + "\" /><input type=\"text\" name=\"id\" value=\"" + $(this).attr("id") + "\" /></form>Save changes Discard changes")
.unbind('dblclick', replaceHTML);
}
}
);
This is an in-place edit code i got it from the internet and i just tore it down to basic level just to understand the codes. Dont worry bout the update query, its is in "handler.php".
The problem here is, i have to write separate function for each column. In this case, i have to write a separate function to update 'car' column, separate function to update 'make' column and goes on. I dont think this is the correct method to do. Because, here i just have 3 columns. What if i had 10 to 15 columns? I dont think writing 15 functions is the correct method. And "$(this).html()" takes only one form's value. Please help.
Modify your PHP script to generate HTML similar to this:
<table>
<tbody>
<tr data-id="1">
<td data-col="car">panamera</td>
<td data-col="make">porsche</td>
<td data-col="sales">100</td>
</tr>
</tbody>
</tbody>
The id of the database row corresponding to each HTML table row is specified with data-id in each tr. And each td specifies to which DB column it corresponds using data-col.
Using these information you can pass enough information back to the PHP script that updates the database. So essentially when a cell is clicked, you can get its column name using:
$(this).data('col')
And you can get the ID for its row using:
$(this).parent('tr').data('id')
Then you can pass these to the PHP page that updates the DB.
EDIT 1:
You can use ul/li instead of table/tr/td. You can also use class=car, class=make, etc. instead of data-col='car', data-col='make', etc. if you are using an older version of jQuery that does not support HTML5-style data- attributes.
EDIT 2: Complete solution
Change your while loop to this:
while ($row = mysql_fetch_assoc($result)) {
echo '<li class="editable" data-id="'.$row['id'].'" data-col="car">'.$row['car'].'</li>';
echo '<li class="editable" data-id="'.$row['id'].'" data-col="make">'.$row['make'].'</li>';
}
As you can see we store the database row ID in data-id and the database column name in data-col.
Now with this setup you would only need one handler:
function replaceHTML()
{
var rowId = $(this).data('id');
var colName = $(this).data('col');
var buff = $(this).html().replace(/"/g, """); // Are you sure you need this?
$(this).addClass("noPad")
.html("<form><input type=\"text\" name=\"" + colName + "\" value=\"" + buff + "\" /> <input type=\"text\" name=\"buffer\" value=\"" + buff + "\" /><input type=\"text\" name=\"id\" value=\"" + rowId + "\" /></form>Save changes Discard changes")
.unbind('dblclick', replaceHTML);
}
$(".editable").bind("dblclick", replaceHTML);
Finally, always try to write readable code! Please! :)
EDIT 3: JSFiddle
Please see this live solution. It shows how you can get the column name and row ID. You just have to adopt it to work with your PHP script.