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.
Related
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
Just realized I was going about this all wrong:( I have a bunch of input fields that I want to submit using JQuery .post() or equivelant so I don't navigate away from the page. I have a database driven form that creates a row of multiple inputs using foreach $row and the output looks like this:
<tr class="even"><td width=200>Settings</td><input type="hidden" id="Settings[0]" value="1"><td><input type="textbox" id="Settings[1]" size="75" value="settings.php"></td><td><select id="Settings[2]"><option value="0" selected>No Parent</option><option value="1">Settings</option><option value="2">Grid Demo</option><option value="3">TEST</option><option value="4">Grid Options</option><option value="5">setGridOptions</option><option value="6">Menu Items</option><option value="7">Ajax Menu</option></select></td><td><input type="textbox" id="Settings[3]" size="5" value="0"></td><td><input type="hidden" id="Settings[4]" value="INACTIVE"> <input type="checkbox" id="Settings[4]" value="ACTIVE"></td></tr>
<tr class="odd"><td width=200>Grid Demo</td><input type="hidden" id="Grid_Demo[0]" value="2"><td><input type="textbox" id="Grid_Demo[1]" size="75" value="grid.php"></td><td><select id="Grid_Demo[2]"><option value="0" selected>No Parent</option><option value="1">Settings</option><option value="2">Grid Demo</option><option value="3">TEST</option><option value="4">Grid Options</option><option value="5">setGridOptions</option><option value="6">Menu Items</option><option value="7">Ajax Menu</option></select></td><td><input type="textbox" id="Grid_Demo[3]" size="5" value="100"></td><td><input type="hidden" id="Grid_Demo[4]" value="INACTIVE"> <input type="checkbox" id="Grid_Demo[4]" value="ACTIVE"></td></tr>
<tr class="even"><td width=200>TEST</td><input type="hidden" id="TEST[0]" value="3"><td><input type="textbox" id="TEST[1]" size="75" value="test.php"></td><td><select id="TEST[2]"><option value="1">Settings</option><option value="2">Grid Demo</option><option value="3">TEST</option><option value="4">Grid Options</option><option value="5" selected>setGridOptions</option><option value="6">Menu Items</option><option value="7">Ajax Menu</option></select></td><td><input type="textbox" id="TEST[3]" size="5" value="0"></td><td><input type="hidden" id="TEST[4]" value="INACTIVE"> <input type="checkbox" id="TEST[4]" value="ACTIVE"></td></tr>
I had been working so hard in php to pull the data into an array and run it through json_encode getting it ready to send to .post() when I realized that it would only continue to save whatever it was when the page was loaded, and not the current state after edits.
Now being so much older and wiser than I was when I started this project, I realize that won't work and I need to be using the .val(), but not sure how I should be setting this up since I don't know how many rows there will be, or what the names will be, how do I keep everything associated so things don't get mixed up?
The PHP side looks like this before it gets processed.
<?
include 'db.php';
$i=0;
foreach($db->query('SELECT * from navmenu') as $row) {
$rowarray[$row[0]] = array();
echo ($i % 2)?'<tr class="odd">':'<tr class="even">';
print_r("<td width=200>" . $row[2] . "</td>");
print_r("<input type=\"hidden\" id=\"");
$row[2] = str_replace(' ', '_', $row[2]);
print_r("". $row[2] . "[0]\" value=\"" . $row[0] . "\">");
print_r("<td><input type=\"textbox\" id=\"" . $row[2] . "[1]\" size=\"75\" value=\"" . $row[3] . "\"></td>");
//parent selection
print_r("<td><select id=\"" . $row[2] . "[2]\">");
if($row[1] == "0"){
print_r("<option value=\"0\" selected>No Parent</option>");
}
foreach($db->query('SELECT * from navmenu') as $option) {
print_r("<option value=\"" . $option[0] . "\"");
if($row[1] == $option[0]){
print_r(" selected");
}
print_r(">" . $option[2] ."</option>");
}
// end foreach
print_r("</select></td>");
print_r("<td><input type=\"textbox\" id=\"" . $row[2] . "[3]\" size=\"5\" value=\"" . $row[4] . "\"></td>");
// setup status whether active or not
print_r("<td><input type=\"hidden\" id=\"" . $row[2] . "[4]\" value=\"INACTIVE\"> "); //set value so it never passes NULL
if ($row[3] == "ACTIVE"){
print_r("<input type=\"checkbox\" id=\"" . $row[2] . "[4]\" value=\"ACTIVE\" checked=\"true\"></td></tr>");
}
else{
print_r("<input type=\"checkbox\" id=\"" . $row[2] . "[4]\" value=\"ACTIVE\"></td></tr>");
}
print_r("\n");
$rowarray[$row[0]]= array("id" => "$row[0]", "parentid" => "$row[1]", "name" => "$row[2]", "url" => "$row[3]", "sortorder" => "$row[4]", "status" => "$row[5]", "tooltip" => "$row[6]");
$i++; //increment by one
}
?>
This was what I was trying to use for the JQuery:
<script>
$(document).ready(function () {
$("a[id^=formsubmit]").click(function ( event ) {
$.post( "functions.php?do=adminmenu", $( "#saveForm" ).serialize() );
}
,function (data) {
$( ".contentarea2" ).html( data );
},"html");
});
</script>
If I understand your question correctly, you're asking how to send all form data without knowing ahead of time what that form data is? Like so:
$("#form").submit(function(e) {
e.preventDefault();
// abort any pending request
if (request) {
request.abort();
}
var $form = $(this);
var $inputs = $form.find("input, select, button, textarea");
var postData = $form.serialize();
// note: we disable elements AFTER the form data has been serialized
$inputs.prop("disabled", true);
request = $.ajax({
url: "submit.php",
type: "POST",
data: postData
})
.done(function(response, textStatus, jqXHR) {
// do something
})
.fail(function(jqHXR, textStatus, errorThrown) {
console.error('Error: ' + textStatus, errorThrown);
});
});
As far as processing it on the PHP end, you should name the fields which might have a variable number of values as an array (using brackets), for example:
<input type="text" name="ids[]" />
Then you can loop through it and process accordingly.
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 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."
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.