jQuery created element cannot be sent through post - javascript

I am dynamically creating input of type text in my form with a value. I can see the new input, but every time I'm sending this through ajax to my php file, it doesn't get the new created input.
The input is put into a table, which is in a form.
I tried with javascript and jQuery, but the two examples do not use the same data, because the javascript way was only for testing purpose
Javascript way
var input = document.createElement("input");
input.setAttribute("type","text");
input.setAttribute("name","moi");
input.setAttribute("disabled","disabled");
input.setAttribute("value","HEY");
$('#actor_form').append(input);
jquery way
var r_name = "<td>" + "<input type='text' name='role[]' disabled value=" +$('#role_name').val()+ " ></td>" ;
var a_name = "<td>" + "<input type='text' name='name[]' disabled value=" +$('#actor_list').val()+ "></td>";
var r_gender = "<td>" + "<input type='text' name='gender[]' disabled value=" +$('#role_gender').val()+"></td>";
var tr = a_name + r_name + r_gender;
$('#actor_table').append("<tr>"+tr +"</tr>");
Sending of data
$.post("assign_roles.php", $("#actor_form").serialize() ,function(data){
alert(data);
});
PHP file
echo $_POST['element'];

The inputs are disabled, so they won't be included in the serialized data.
Ref: http://api.jquery.com/serialize/
"Note: Only "successful controls" are serialized to the string."
Ref: http://www.w3.org/TR/html401/interact/forms.html#h-17.13.2
"Controls that are disabled cannot be successful."

Related

POST submit to mysql using php the value from append javascript

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.

Allow editing of Text dynamic php table

I have a html table that is generated VIA PHP and data in a database, what I want to do is have a button in the last cell of each row that says edit and when you click that button the text in the other cells becomes textboxes or other types of input fields so that you can edit them and then press submit which would send that form off to be updated in the database. The code I have right now to generate the table is:
<table style="width:100%; " class = "table table-striped table-bordered table-hover">
<tr>
<th>Name</th>
<th>Status</th>
<th>Description</th>
<?php
if($_SESSION['editGroup'] != 0){
echo "<th>Edit</th>";
}
?>
</tr>
<?php
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$checkQuery = "SELECT userGiven, userStatus, userDesc FROM user_Status WHERE organization = 'myOrg' ORDER BY userGiven ASC";
$prepared = $dbh->prepare($checkQuery);
$prepared->execute();
$data = $prepared->fetchAll(PDO::FETCH_ASSOC);
foreach($data as $row){
echo "<tr>";
if($_SESSION['editGroup'] != 0){
echo "<td width='20%'>" . $row['userGiven'] . "</td><td width='10%'>" . $row['userStatus'] . "</td><td width='70%'>" . $row['userDesc'] . "</td><td width='10%'><button type='button' class='btn btn-info'>Edit</button></td>";
}else{
echo "<td width='20%'>" . $row['userGiven'] . "</td><td width='15%'>" . $row['userStatus'] . "</td><td width='75%'>" . $row['userDesc'] . "</td>";
}
echo "</tr>";
}
?>
</table>
What I am trying to do is change the cell with userStatus to a drop down field with the current value as the starting value and the other value in/out as the other value to select between.
I also want to change the userDesc to a textarea and I think I know how to do all this but I am running into a problem conceptually when I try to apply it to the dynamic table.
What I was thinking was that I could use jquery/javascript to get the innerhtml of span variable that could surround those two cells and then change the html to the various input fields containing the current text allowing the user editing them to change those values.
How do I do this for this sort of problem though, I would need onClick events for all the buttons and I wouldn't know how many buttons there would be, that's based off of the number of rows in the table.
That would result in hundreds of lines of redundant code so I assume there has to be a much better way. Anyone know what a way to accomplish this? I found this: http://stackoverflow.com/questions/16202723/how-to-edit-data-onclick which is close to what I want but that seems to be static values where I want to be able to do this for any of the rows in the table.
In your for loop, you'll want to put something identifiable in the <tr> and <td> elements. I'd personally go with a data-attribute. For example:
Echo Row Code
foreach($data as $row){
echo "<tr data-row='{$row[id]}'>";
if($_SESSION['editGroup'] != 0){
echo "<td width='20%' data-column='name'>" . $row['userGiven'] . "</td><td width='10%' data-column='status'>" . $row['userStatus'] . "</td><td width='70%' data-column='description'>" . $row['userDesc'] . "</td><td width='10%'><button type='button' class='btn btn-info'>Edit</button></td>";
}else{
echo "<td width='20%'>" . $row['userGiven'] . "</td><td width='15%'>" . $row['userStatus'] . "</td><td width='75%'>" . $row['userDesc'] . "</td>";
}
echo "</tr>";
}
So, as you can see I've added a data-row attribute to <tr> which should get the value of the database record's ID. Change it as necessary - I made the assumption it'd be named 'id'. Also, I added the data-column attribute to <td> which should identify each column for us. This is all the modification needed in the PHP.
Now, here's what the JQuery for the edit button looks like:
Front-End Event Listener: Part 1
$( function(){
$(document).on("click", ".btn-info", function(){
var parent = $(this).closest("tr");
var id = $(parent).attr("data-row");
var name = $(parent).children("[data-column='name']");
var status = $(parent).children("[data-column='status']");
var desc = $(parent).children("[data-column='description']");
var nameTxt = $(name).html();
var statusTxt = $(status).html();
var descTxt = $(desc).html();
$(name).html("<input name='name' data-dc='name' value='" + nameTxt + "'>");
$(status).html("<input name='status' data-dc='status' value='" + statusTxt + "'>");
$(desc).html("<textarea name='desc' data-dc='description'>" + descTxt + "</textarea>");
$(this).replaceWith("<button class='btn-info-save'>Save</button>");
});
}
Finally, we need to define what happens upon hitting save (the above example changes the "edit" button into a "save" button). That could be anything, but we'll assume it'll be an AJAX call:
Front-End Event Listener: Part 2
$( function(){
$(document).on("click", ".btn-info-save", function(){
var parent = $(this).closest("tr");
var id = $(parent).attr("data-row");
var data = {id: id};
$("[data-dc]").each( function(){
var col = $(this).attr("data-dc");
var val = $(this).val();
data[col] = val;
});
$.ajax({
url: "/dynamic-edit/edit.php", // Change this to your PHP update script!
type: 'POST',
dataType: 'json',
data: data,
success: function(ret){
//Do Something
console.log(ret.response);
},
error: function(ret){
console.log(ret.response);
}
});
});
}
Now, in your PHP script that handles the AJAX request:
PHP Code for 'edit.php'
$name = $_POST['data_name'];
$status = $_POST['data_status'];
$description = $_POST['data_description'];
// Do whatever with the data
// Output JSON - get the response in JS with ret.response
// either inside the success or error portion of the AJAX
echo json_encode( ["response"=>"Row edited successfully."] );
This is a very simple example, but it gets the point across. Be sure to change the AJAX url from "/dynamic-edit/edit.php" to wherever you'll make your PHP script that will actually make the updates after submitting.
You'll likely want to do cleanup after a successful edit; for example, changing the text boxes back to just text in a <td>. Also, please note that I just changed them to textboxes. I know you said in your post you wanted to make one the status a dropdown and the description a textarea, but this example should be easy enough to change. I don't know what the values of the dropdown should be, so you'll have to do that part.
Notes
I went with $(document).on("click" ... instead of $(".btn-info").on("click" ... because whenever you're dealing with dynamic content, you always want the event listener on the document, not the element. Why? Because if you click the "edit" button, it disappears and a "save" button appears, you now lose that event listener forever. If you were to re-add the "edit" button (say, after a successful save), that button would need the event listener added again. When you go the route of attaching the event listener to the document, however, you can remove/add all you want and it'll still work.
You can add 'data' attribute to each button with the user id that you want to update. For example:
<button data-iduser='<?= $use["id"] ?>' class='btn btn-info'>Edit</button>
$("btn btn-info").click( function() {
var idUser = $(this).attr("data-iduser");
// some ajax if you want with that iD
});

How to use Javascript to insert new field in PHP and perform while loop

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() );

$(#form).submit() is not working in chrome browser

i have inserted one hidden form in the page using jquery and i am submitting the form using jquery on button click event.The hidden form is getting submitted in firefox but it does not get submitted in chrome.
Following is the form i have inserted using jquery on document.ready function.
$('#leftnav').after(
"<tr><td><form name='login1'" +
"action='https://abc.com/FormPost/Submit' method='post'" +
"id='login' >" +
"<input type='hidden' name='MerchantIdentifier' value='abc' />" +
"<input type='hidden' name='Url'" +
"value='http://chcnq.chxcg.servertrust.com/one-page-checkout.asp'/>"+
"<input type='hidden' name='Description'" +
"value='Volusion Order' />"+
"<input type='hidden' name='Data' value='' />"+
"<input type='hidden' name='TransactionIdentifier'"+
"value='12' />" +
"<input type='hidden' name='Amount' value='' />"+
"<input name='Token' type='hidden' value='" + token + "' />"+
"<input type='hidden' name='ErrorUrl' />" +
"</form></td></tr>");
and on button click i have written following code:
$("#btnSubmitOrder").click(function() {
$("#login").submit();
});
Please can you advise why it is not working in chrome browser.
try this:
$("#btnSubmitOrder").click(function() {
$("form[name=login1]").submit();
});
Based on my comments:
It is generally a bad practice to submit two forms on one action, but:
1) You can add target iframe to your both forms. That way Browser does not get redirected by submittin either of them.
or
2) you can prevent default behavior and send data to #login form url by using $.ajax and then (on callback) call submit on the first form.
Use this javascript code.
$("#btnSubmitOrder").click(function() {
document.forms['login1'].submit();
});

Using only one function to update different columns of a table in database

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.

Categories

Resources