I already get the id from a php loop for my checkboxes, and pass them as a string(maybe not because I could not split them with comma) in parameter, then I need to check if the checkbox is checked in javascript using the ids I passed through.
It doesnt seem like I can split it in javascript as well, and after I ran the for loop, the data is undefined in the new string.
Do you have any ideas? Please help
here is my php
echo "<div id='addstock'>";
$ids = '';
while($row_add = mysqli_fetch_array($result_add)){
$id=$row_add['id'];
$company = $row_add['companyname'];
//create checkbox for company
echo "<p class='checkbox'><input type='checkbox' name='stocks' id='".$id."' value='".$id."'>".$company."</p><br>";
$ids .= $id;
}
echo "</div>";
echo "<p class='input'><input type='submit' class='submitbutton' value='Submit' onclick='updatetable(".$ids.",".$user.")'></p>";
here is my javascript
//update table after add to stock
function updatetable(ids,user){
var url = "update.php";
//var res= ids.split(" ");
alert(ids);
var stocks = "";
//check if the checkbox is checked
for(var id in ids){
if(document.getElementById(ids[id]).checked)
{
stocks += ids[id];
alert(ids[id]);
}
}
//alert(stocks);
var data = "ids="+stocks+"&user="+user;
alert(data);
ajaxRequest(url, "POST", data, true, proceedUpdate);
}
function proceedUpdate(response){
target_div = document.getElementById("tablediv");
target_div.innerHTML = response;
}
Try this:
<div id="addstock">
<?php
$ids = array();
while($row = mysqli_fetch_array($result_add)) {
$ids[] = $row_add['id'];
echo '<p class="checkbox"><input type="checkbox" name="stocks" id="' . htmlspecialchars($id) . '" value="' . htmlspecialchars($id) . '">' . htmlspecialchars($company). '</p><br>' . "\n";
}
?>
</div>
<p class="input">
<input type="submit" class="submitbutton" value="Submit" onclick="updatetable('<?php echo htmlspecialchars(implode(',', $ids)); ?>', '<?php echo htmlspecialchars($user); ?>')">
</p>
Related
[Sample Look]
I'm trying to make an interface where you can edit/add/remove fields of a mySQL database. This is how it looks visually, and I have all the functionality on the client side working.
My question is: How can I pass any edits/adds/removals to the server side? I'll include a link for my JSFiddle.
And the code below will show how I currently great the table.
<?php
$servername = "localhost";
$username = "lalalal";
$password = "lalalal";
$link = mysqli_connect("localhost", "lalala", "lalala", "lalala");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sqlStart = "SELECT `Name`, `EXT`, `Returning Time`, `Returning Date`, `Out`, `Reset`, `Booked` FROM `lalala`";
if($result = mysqli_query($link, $sqlStart)){
if(mysqli_num_rows($result) > 0){
echo "<table id = contactTable>";
echo "<tr id = row1>";
echo "<th id = sortTable onclick=sortTable(0)>Name ↕</th>";
echo "<th style = width:100px;>EXT</th>";
echo "<th style = width:300px;>Returning Time</th>";
echo "<th style = width:300px;>Returning Date</th>";
echo "<th style = width:70px;>Out</th>";
echo "<th style = width:100px;>Reset</th>";
echo "<th style = width:600px;>Booked</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
$currentCheck = $row['Out'];
if ($currentCheck == 0) {
echo "<tr>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['EXT'] . "</td>";
$currentTime = $row['Returning Time'];
if ($currentTime == 0) {
echo "<td> <form> <input type = 'time', id = 'timePickChange'> </form> </td>";
} else {
echo "<td> <form> <input type = 'time', id = 'timePickChange' value =" . $currentTime . "> </form> </td>";
}
$currentDate = $row['Returning Date'];
echo "<td> <form> <input type = 'date', id = 'datePickChange' value =" . $currentDate . "> </form> </td>";
echo "<td> <form onclick = 'checkIfOutRow(this)'> <input type = 'checkbox', onclick = 'checkIfOutValue(this)'> </form> </td>";
echo "<td> <button onclick = 'clearForm(this)', id = buttonClear>Reset</button> </td>";
echo "<td> <textarea rows = '1', cols = '60'> </textarea> </td>";
} else if ($currentCheck == 1) {
echo "<tr style = 'background-color: #E2E9FD'>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['EXT'] . "</td>";
$currentTime = $row['Returning Time'];
echo "<td> <form> <input type = 'time', id = timePickChange disabled> </form> </td>";
$currentDate = $row['Returning Date'];
echo "<td> <form> <input type = 'date', id = datePickChange disabled> </form> </td>";
echo "<td> <form onclick = 'checkIfOutRow(this)'> <input type = 'checkbox', onclick = 'checkIfOutValue(this)' checked> </form> </td>";
echo "<td> <button onclick = 'clearForm(this)', id = buttonClear>Reset</button> </td>";
echo "<td> <textarea rows = '1', cols = '60'> </textarea> </td>";
}
echo "</tr>";
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sqlStart. " . mysqli_error($link);
}
?>
Depending on your data validation model, you might want to control the inputs value client side before posting them to your back-end.
AFAIK, you're already adding/editing/removing your contacts on the client side, so If I understand correctly, when your user should click on Edit/Remove & confirm , it would be a confirmation of what the user has done in the browser, this doesn't really change much apart from the fact that otherwise you might need dedicated buttons/row (or any other bindable events).
For these operations what you could do is proceed to bulk delete / edit, and this could be easily done by filtering out in your JS all the modified/deleted data and sending it to your back end PHP with Ajax/jQuery in the form of a stringified array.
As for insertion operation you'd submit them at the same time you add them to your table, by executing a POST operation.
And it could be done with something like this :
$.ajax({
method: "PUT",
url: "some.php",
data: JSON.stringify(myUpdatedDataInAnArray)
// you might need to stringify your array to ensure format ?
})
.done(function( msg ) {
alert( "Data Updated: " + msg );
});
In your back end php, you'd listen for POST/PUT/DELETE methods with something like that :
if (isset($_POST['add'])){
do your thing
}
if (isset($_PUT['updated'])){
//Since you're sending a stringified array, you must parse it with
$myArray = json_decode($_PUT['updated']);
do your thing
}
if (isset($_DELETE['deleted'])){
do your thing
}
I say Ajax because using a traditional POST/PUT/DELETE form would result in refreshing the page.
Here are some useful refs :
JS JSON Stringify and JSON Parse
PHP : JSON DECODE and JSON Encode
Ajax docs
Ajax Examples
I have a PHP form.
The form elements are created based off the user's selection which is in a dropdown menu.
What I am trying to accomplish is loop through that form and validate the values of two elements with the id's of "action" and "amt".
Now, I should mention the form which I am trying to validate can have x amount of elements because it needs to be based on the users needs. When I call my validate function it does check the id's and alerts the value, however, it alerts the value of the first input element with the id "amt" three/multiple times.
This is bad as because I need to perform some computation and the duplicate entries would cause an error in the the computation.
Here is my script
<script type="text/javascript">
function validate(){
var i;
var passtest = 0;
var test = "";
var form = document.getElementById("myForm");
alert("Enter function");
for( i = 0; i < form.elements.length; i++){
if(form.elements[i].id === "action" && form.elements[i].value === "Debit" || form.elements[i].value === "Credit"){
test = form.elements[i].value;
// Alerts action
alert(test);
if(document.getElementById("amt").value !=""){
// Get the value from the input element id amt
test = document.getElementById("amt").value;
// Alerts value from id amt
alert(test);
//passtest = 1;
}
else{
document.getElementById("amtTD").innerHTML = "Check Amounts";
return false;
}
alert("End of if stmt");
}
else{
// If it is not id action or id amt just Alert value if any
test = form.elements[i].value;
alert(test);
}
}
///****** END OF FOR LOOP ****** ///
if(passtest === 1){
return true;
}
else{
alert("Submission failed");
return false;
}
}
</script>
Here Is the php code that which displays the form
<form name='transaction' id="myForm" onsubmit="return validate()" action='' method='post'>
<?php
if (isset($_POST['add'])) {
if (isset($_POST['acctN'])) {
echo "<table class='table' id='myRow'' style=''>";
echo "<thead>";
echo "<tr>";
echo "<th>Account Name</th>";
echo "<th>Action</th>";
echo "<th>Amount</th>";
echo "</tr>";
echo "</thead>";
foreach ($_POST['acctN'] as $name) {
$query = "SELECT * FROM ChartOfAccounts WHERE AccountName = '$name'";
$results = mysqli_query($cxn, $query) or die(mysqli_error($cxn));
$row = mysqli_fetch_assoc($results);
echo "<tbody>";
echo "<tr>";
echo "<td class ='col-md-6'><select name='account[]' class='form-control' style=''><option>" . $row['AccountName'] . "</option></select></td>";
echo "<td class ='col-md-2'><select name='debOrCred[]' id='action' class='form-control' style=''>
<option value='Debit'>Debit</option>
<option value='Credit'>Credit</option>
</select></td>";
echo "<td class ='col-md-2'> <input type='text' name='amount[]' class='form-control' id='amt' style=''/> <span id ='amtTD' style='color:red;'> </span></td>";
echo "<td class ='col-sm-2'>$</td>";
echo "<td class ='col-sm-2'><button type='button' onclick='removeCell()' class='btn btn-danger'value='Remove' name='".$row['AccountName']."'>Remove</button></td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
}
echo "<label style='margin-left:7px;'>Documentation</label>";
echo "<textarea name='src-doc' class='form-control' rows ='4' cols='50' placeholder='Description' style='max-width:575px; margin-left:8px;' ></textarea>";
echo "<div style='padding:10px;'>";
echo "<label>Source</label>";
echo "<input type='file' name='fileToUpload' id='fileToUpload'>";
echo "</div>";
echo "<input type='submit' class='btn btn-primary' value='Submit' name='subTrans' style='margin-top:7px; margin-left:8px; '/>";
}
?>
</form>
Thank you all that help and provide input.
This page generates a table contaning routes, and in the end of every "tr" there is a button that should copy the text inside those 2 fields in each line to the Name3 and Name 4 inputs, respectively.
But when I click, nothing is happening, I think that getElementById("Name1_".index) is making the hole code invalid, but how to make it correctly?
<script type="text/javascript">
function copyTextValue(key) {
var index = key;
var text1 = document.getElementById("Name1_".index).value;
var text2 = document.getElementById("Name2_".index).value;
document.getElementById("Name3").value = text1;
document.getElementById("Name4").value = text2;
}
</script>
<input type="text" id='Name3' />
<input type="text" id='Name4' />
<?php
$get_rotas = file_get_contents('routes.txt');
$array = explode("\r\n", $get_rotas);
foreach($array as $key=>$rota) {
//Route(rota) Example: TRM J169 BLH V16 BXK|3666
$rota_distance = explode("|", $rota);
echo "<tr bordercolor='#FFFFFF'>";
echo "<td><input type=\"text\" id=\"Name1_$key\" value='" . $rota_distance[0] . "'/></td>";
echo "<td><input type=\"text\" id=\"Name2_$key\" value='" . $rota_distance[1] . "'/></td>";
echo "<td><input type=\"button\" onclick=\"copyTextValue($key);\" value=\"Copy\" ></td>";
echo "</tr>";
}
?>
For concatenating strings in JavaScript use + instead of ..
This is my PHP code and each post has a More button with the same class. I want if I click on More button of post A, only the comments under it should be displayed :
<?php
for ($i = 1; $i <= 10; $i++) {
echo "<div class='col-md-6'>";
echo "<div class = 'feeds'>"; ?>
<form method='post' class='murconform form-horizontal' name='signinform'
action =''>
<?php
echo "<p>". $post . "</p>";
echo "<div class = 'murcons btn-group'>";
echo "<span class = 'likecount'>". $likes . "</span><button class='mlike pacedown' value='".$assigned_id."' name = 'like' type='submit'><span class = 'buttons'>Like</span><span class='glyphicon glyphicon-heart'></span></button>";
//Problem 1: I want whenever the next button with the class 'mmore' is clicked, the class
'comment_data' should be displayed. It is set to "display:none" by default but
whenver I click it, all other comment are displayed.
echo "<button class='mmore pacedown' value='".$post_id."' name = 'more' type='submit'><span class = 'buttons'>More</span><span class='glyphicon glyphicon-chevron-down'></span></button>";
echo " "."<span class = 'slanted'>". $time . "</div>";
echo "</form>";
// fetch and display comment for each post...
$qry = "SELECT user_id, comment FROM comments WHERE post_id = ? ORDER BY time DESC";
$q = $conn->prepare($qry) or die("ERROR: " . implode(":", $conn->errorInfo()));
$q->bindParam(1, $post_id);
$q->execute();
if($commentz = $q->fetchAll()){
echo "<div class = 'comment_data'>";
foreach ($commentz as $comment){
echo "<div class = 'per_comment'>";
echo "<p>". $comment[0] ." ". $comment[1] . "</p>";
echo "</div>";
}
echo "</div>";
}?>
<form method='post' class='murconform form-horizontal' name='signinform' action ='<?php echo htmlentities($_SERVER['PHP_SELF']);?>'>
<?php
echo "<div class = 'commentdiv'>";
echo "<input type='hidden' name='post_id' value='".$post_id."'>";
echo "<textarea autocomplete = 'off' name='commentdata' maxlength='480' class='commenttext form-control' rows = '1' placeholder='Have your say...'></textarea>";
echo "<span class='counter_msg'></span>";
echo "<button class='btn btn-xs btn-primary onespacedown comment' name = 'comment' type='submit'>Comment</button>";
// Problem 2: How do I get the content of this textarea whenever the submit button is clicked via AJAX?
echo "</form>";
echo "</div>";
echo "</div>";
echo "</div>";
}
?>
This is my jQuery code for Problem 1:
$( ".comment" ).click(function() {
var $this=$(this);
$(".murconform").submit(function(e){
return false;
});
$('.comment_data').slideToggle("slow");
});
And this is the AJAX code for Problem 2:
$(".mlike").click(function () {
$(".murconform").submit(function(e){
return false;
});
var $this=$(this);
var post_id = $('.post_id').val();
var comment = $(".commentdata").text();
var request = $.ajax({
url: "comments.php",
type: "POST",
data: { post : post_id , comment : comment },
dataType: "html"
});
request.done(function( msg ) {
$this.prev('.comment').html( msg );
});
});
Any good solution/advice(with regards to best practice) would be deeply appreciated.
Hard to know for sure unless you post the generated HTML, not the code that generates it but it seems that what you are trying to do is target elements within a group, not those outside of that group that have the same class name.
To do this you find a common parent of those elements (for example a div that wraps those elements), in your case .feeds seems to occur once per iteration.
$('.mmore').on('click', function(){
var $commonparent=$(this).closest('.feeds');
Then you find the elements you want within $commonparent
var post_id = $commonparent.find('.post_id').val();
var comment = $commonparent.find(".commentdata").text();
This might clear up both problems. For a better answer please post the generated HTML and move your problem explanations to outside of the code.
To clarify, div.feeds can be used as the closest ancestor allowing you to find child elements by class name that only exist within that particular div.feeds
<div class="feeds">
<input class="post_id" />
<textarea class="commentdata"></textarea>
<button class="mmore">More</button>
</div>
<div class="feeds">
<input class="post_id" />
<textarea class="commentdata"></textarea>
<button class="mmore">More</button>
</div>
<div class="feeds">
<input class="post_id" />
<textarea class="commentdata"></textarea>
<button class="mmore">More</button>
</div>
I posted this code minutes 15 mins ago and I did get help for the preventDefault issue , but now I'm not getting my alerts to work , yet firebug doesn't show any error related to this code .. May i ask where I'm going wrong ,
<?php
header ("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header ("Expires: Sat 26 Jul 1997 05:00:00 GMT"); // Date in the past
require_once ("../_includes/functions.php");
?>
<link rel="stylesheet" title="Style CSS" href="../_reports/report_assets/cwcalendar.css" type="text/css" media="all" />
<script src="../_js/jquery-1.6.2.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../_js/timer.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" src="../_reports/report_assets/calendar.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#select').click(function(event){
$(':checkbox').prop("checked", true);
event.preventDefault();
});
$('#deselect').click(function(event){
$(':checkbox').prop("checked", false);
event.preventDefault();
});
$('#add').click(function() {
var field = '<input class="project_fields" type="text" size ="30" name = field_settings[] /> ';
var checkbox = '<input class ="checkbox" type ="checkbox" name ="check_field[]" /> ';
var delete_link = '<a class ="delete_link" style="text-decoration:none;" href="#"> Delete field </a> <br /><br />';
var input = field + checkbox + delete_link;
$('#input_fields').append(input);
});
$('#project_fields_submit').click(function(event) {
event.preventDefault();
var array_fields = new Array();
$('.checkbox').each(function() {
if($(this) .is(':checked')) {
array_fields.push('1');
alert('checked!!!');
}
else {
array_fields.push('0');
alert('not checked !!!')
}
});
$('#checkboxes').val(array_fields);
});
$('#edit_fields_submit').click(function(event) {
event.preventDefault();
var edit_fields = new Array();
$('.edit_check').each(function() {
if($(this) .is(':checked')) {
alert('checked !!!'); // doesn't alert anything after filling out the fields , though it used to
edit_fields.push('1');
}
else {
edit_fields.push('0');
alert('not checked !!!');
}
});
$('#edit_checkboxes').val(edit_fields);
alert($('#edit_checkboxes').val()); // doesn't work
});
var nextRowID = 0;
$('#add_edit').click(function() {
var id = ++nextRowID;
var new_field = '<input class ="class'+id+'" type="text" size ="40" name = edit_field_value[] value =""> ';
var new_checkbox = '<input class ="class'+id+'" type ="checkbox" name ="check_field[]" > ';
var delete_edit = '<a id ="'+id+'" class ="new_delete_edit" style="text-decoration:none;" href="#" > Delete field </a><br><br>';
var new_input = new_field + new_checkbox;
$('#new_input_fields').append(new_input);
$('#new_input_fields').append(delete_edit);
});
$('a.delete_edit').click(function(event) {
event.preventDefault();
var ID = $(this).attr('id');
var delete_field_id = 'edit_field'+ID;
var field_data = $('#'+ delete_field_id).val();
var project_id = $('#edit_project_id').val();
var string = {field : field_data, pid : project_id };
$.ajax({
type: "POST",
url: "_ajax/delete_field.php",
data: string,
success: function(data){
$('#'+ID).remove();
$('#'+delete_field_id).remove();
$('#new_check'+ID).remove();
}
});
});
$('.new_delete_edit').live('click', function(event) {
event.preventDefault();
var id = $(this).attr('id');
$('.class'+id).hide();
$('#'+id).hide();
});
});
</script>
<?php
if (isset($_GET['pid']) && isset($_GET['user_id'])) {
$id = $_GET['user_id'];
$pid = $_GET['pid'];
$show_id = $_GET['show_id'];
"
$query_settings ="SELECT project_settings FROM projects WHERE project_id ='$pid'";
$result_settings = mysql_query($query_settings);
$row_settings = mysql_fetch_array($result_settings,MYSQL_ASSOC);
if($row_settings['project_settings'] == NULL) {
echo "<h2> Project Settings </h2>";
echo "<br><br>";
echo " <b> Add fields </b>";
echo " ";
echo "<img id ='add' src='_assets/add.png' /><br><br><br>";
echo '<form action ="" method="post">';
echo'<input type="hidden" name="pid" value="'.$pid.'">';
echo "<input id ='checkboxes' type ='hidden' name ='checkboxes' value ='' >";
echo "<div id='input_fields'> </div>";
echo '<input id ="project_fields_submit" type ="submit" name ="project_fields_submit" class="button" value ="Save Settings" /><br><br>';
echo '</form>';
echo "<br><br><br><br><p></p>";
}
else {
echo "<h2> This Project Settings </h2>";
echo "<br><br><br><br>";
echo "<b> Add fields</b> <img id ='add_edit' src='_assets/add.png' /><br><br><br>";
$fields_data = unserialize($row_settings['project_settings']);
$i = 0;
echo '<form action ="" method="post">';
echo'<input id ="edit_project_id" type="hidden" name="edit_project_id" value="'.$pid.'">';
echo "<div id='new_input_fields'> </div>";
echo "<input id ='edit_checkboxes' type ='hidden' name ='edit_checkbox' value ='' >";
foreach ($fields_data as $key => $value) {
if($value =="1") {
echo "<input id ='edit_field".$i."' class ='edit_data' type ='text' size ='40' name = edit_field_value[] value ='".$key."' /> ";
echo "<input id ='new_check".$i."' class ='edit_check' type='checkbox' name ='edit_checkboxes' checked /> ";
echo "<a id ='".$i."' class ='delete_edit' style='text-decoration:none;' href='#'> Delete field </a><br><br>";
} else {
echo "<input id ='edit_field".$i."' class ='edit_data' type ='text' size='40' name = edit_field_value[] value ='".$key."' /> ";
echo "<input id ='new_check".$i."' class ='edit_check' type='checkbox' name ='edit_checkboxes' /> ";
echo "<a id ='".$i."' class ='delete_edit' style='text-decoration:none;' href='#'> Delete field </a><br><br>";
}
$i++;
}
echo '<input id ="edit_fields_submit" type ="submit" name ="edit_fields_submit" class="button" value ="Save Settings" /><br><br>';
echo '</form>';
}
echo '</div>';
echo '<div id="project-setting-results"></div><div class="clear"></div>';
echo '</div><!-- end fragment-6 -->';
}
?>
I suggest changing your design. Using <form> codes and posting isn't always the best way of sending your data to another (or the same) page for PHP processing. Instead, switch over to using AJAX code to submit your form.
For one thing, this will allow you to get away from the e.preventDefault kludges. A number of things will iron themselves out if you use the AJAX approach (instead of submitting a form). I can see that you're already using AJAX in your code, but if you're still uncomfortable with it you can check out these other answers:
Form not posting correctly
Place PHP results inside HTML Page
Update data in a DIV
Change your #edit_fields_submit input field from type="submit" to type="button" and use javascript/AJAX to:
Get all the values you would normally submit as a <form>;
Use AJAX to submit them to a PHP file for processing
In the success: function of the AJAX code block, use javascript to send the user over to whatever page you want them to see next
Example:
$('#edit_fields_submit').click(function(event) {
var edit_fields = new Array();
$('.edit_check').each(function() {
if($(this) .is(':checked')) {
alert('checked !!!'); // doesn't alert anything after filling out the fields , though it used to
edit_fields.push('1');
}
else {
edit_fields.push('0');
alert('not checked !!!');
}
});
$('#edit_checkboxes').val(edit_fields);
alert($('#edit_checkboxes').val()); // doesn't work
var field_data = //you know how to get these values
var project_id = //etc
var string = {field : field_data, pid : project_id };
$.ajax({
type: "POST",
url: "_ajax/myprocessor.php",
dataType: "json",
data: string,
success: function(data){
document.location.href='yournewpage.php';
}
});
});