I have this strange issue, which is hard for me to describe to be honest.
For testing purposes I have set up a SQL db containing id (autoincrement), first name, last name.
I have 2 entries there.
I call the db and list the entries in inputs like this:
while($row = $result->fetch_assoc()) {
$id = $row['id'];
$fname = $row['fname'];
$lname = $row['lname'];
echo "<div id='$id'>
<form method='post'>
<p>ID: <input type='text' name='id' id='id".$id."' value='$id' /></p>
<p>New first name: <input type='text' name='fname' id='fname".$id."' placeholder='$fname' /></p>
<p>New last name: <input type='text' name='lname' id='lname".$id."' placeholder='$lname' /></p>
<input type='submit' name='update' class='update' value='ID = $id' />
</form>
</div>";
}
Works perfectly fine and I get a page with both entries and a button to update them.
I am updating them with this function
$('.update').click(function(){
var row = $(this).parent().parent().attr('id'); // I've stored the SQL id in the parent div
// construct the input ids so i know where I am getting the data from
var idSource = '#id'+row;
var fnameSource = '#fname'+row;
var lnameSource = '#lname'+row;
// store the input values in variables
var id = $(idSource).val();
var fname = $(fnameSource).val();
var lname = $(lnameSource).val();
// use ajax to update sql table
$.ajax({
url : 'aiai.php',
method : 'post',
data : {id: id, fname: fname, lname: lname},
success: function(response){
console.log(response);
}
});
});
I am doing this so that every entry can be edited & updated on it's own.
An while this basically working I am getting a strange lag.
Example:
I load the page, update the first name, click the update button --> Works
Then I edit the same entry again, click the update button --> i am
getting the old value again
When I refresh the page I get the name update I just saved
Lag continues until I refresh the page
I load the page, update the first name, click the update button --> Works
Then I edit the same entry again, click the update button --> i am getting the old value again
When I refresh the page I get the name update I just saved.
Lag continues until I refresh the page.
It's like that info gets cached in the browser.
BUT, and this confuses me:
When I hardcode the inputs where I am calling the values from, everything works perfect.
So when I use
var id = $('#id2').val();
... instead of
var id = $(idSource).val();
... I am not experiencing this lag.
Anyone got an idea what I am doing wrong?
Related
I am making a webpage where the user can use a form to search for a string and then divs will appear showing rows with matching info from a database. Then when a checkbox is clicked on a row it will move up to another div. I would like for the rows which have been selected via the checkbox to remain where they are when the form is resubmitted but still disappear when the checkbox is unclicked.
I have taken this video to show how it is currently working, which should hopefully make my question make sense.
https://imgur.com/a/DmkP0ut
This is the code for my form
<form action = "" method = "POST">
<div class = "searchcontainer">
<input id = "search" type="search" name = "search" class = "textbox" placeholder
= "Type the students name and press Enter to search...">
<input type = "submit" style="display:none" id = "submitsearch"/>
</div>
</form>
Then when the form is submitted this code will run to create the divs that appear (This is just a really short version, let me know if you need to see all of it)
<?php
if(isset($_POST['search'])){
$input = $_POST['search'];
$result = $conn->query("select * from logins");
let r<?php echo $studentid ?> = document.createElement("div");
r<?php echo $studentid ?>.id = "r<?php echo $studentid ?>";
r<?php echo $studentid ?>.className = "rowcontainer";
document.getElementById("tablecontainer").appendChild(r<?php echo $studentid ?
>);
Then this is the Javascript code which moves the rows to the 'selected' container when the checkbox is ticked and back to the 'tablecontainer' when unckecked.
<script>
const main = document.querySelector(".tablecontainer");
const selected = document.querySelector(".selected");
main.addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.classList.contains("move")) {
const rowContainer = tgt.closest(".rowcontainer");
if (tgt.checked) {
selected.append(rowContainer);
}
}
})
selected.addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.classList.contains("move")) {
const rowContainer = tgt.closest(".rowcontainer");
main.append(rowContainer)
}
})
</script>
From what I found online it looks like I will need to se session variables to keep the rows in place once they have been selected, but I dont really know how to do this, so help would be appreciated.
Thanks
Edit: I have a had a look through these answers but as a beginner they do not make much sense to me. I have found that I can use
var rowsselected = document.getElementById("selected").children;
to get a list of all the children divs in my selected div, so is there a way I can save this list so it persists when the form is resubmitted and take the children from this list and append them to selected again. If you could show examples that would be good. Also I should have mentioned this in the main post but I would also like to carry over info from the rows which have been selected to the next page so if I could make the ids of these rows into session variables or something like that that would be good.
I have a dynamically added HTML form field which takes a list of company names to store in MySql database. Since I have only 1 column in database, I am using serialize function to save & unserialize function to display again (on the edit page). The saving part works fine.
The issue is, I am unable to figure out how to display the various companies in the dynamic fields. I have hard coded $internname[0] at the first field (which is a static field) & added $internname[1] to the dynamic field (in script). This displays the first company name in the first field & the second company name in all the remaining fields.
I know, I need to pass an incremental number into the dynamic field, but how do i write this function? Tried using the already available xint variable which is incrementing anyway, didn't work.
<?php
$query = "SELECT * FROM user WHERE mail = '$mail' LIMIT 1";
$result=mysqli_query($db,$query);
while($row = mysqli_fetch_array($result))
{
?>
<div class="field_wrapperint">
<div class="inlineinput2b">
<div align="left">Internships:</div>
<?php $internshipname = unserialize($row['internshipname']);
foreach ((array) $internshipname as $internname[])
?>
<input type="text" name="internshipname[]" placeholder="Company Name" value="<?php echo htmlspecialchars($internname[0]);?>"/>
</div>
<div class="inlineinputb">
<img src="add-icon.png"/>
</div>
</div>
<input type="submit" name="update_profile" class="action-button" value="Update Profile" />
<?php
}
mysqli_close($db);
?>
<!-- Script for dynamic button adding -->
<script type="text/javascript">
$(document).ready(function(){
var maxField = 4; //Input fields increment limitation
var xint = 0; //Initial field counter is 1
var addButtonint = $('.add_buttonint'); //Add button selector
var wrapperint = $('.field_wrapperint');
var fieldHTMLint = '<div><div class="inlineinput2b"><input type="text" name="internshipname[]" placeholder="Company Name" value="<?php echo htmlspecialchars($internname[1]);?>"/></div><div class="inlineinputb"><img src="remove-icon.png"/></div></div>' ; //New input field html
//Once add button is clicked
$(addButtonint).click(function(){
//Check maximum number of input fields
if(xint < maxField){
xint++; //Increment field counter
$(wrapperint).append(fieldHTMLint); //Add field html
}
});
//Once remove button is clicked
$(wrapperint).on('click', '.remove_buttonint', function(e){
e.preventDefault();
$(this).parent('div').parent('div').remove(); //Remove field html
xint--; //Decrement field counter
});
});
</script>
i need a help here. i want to automatically update my iD whenever i submit my data. let me explain a bit more.
Here is the scenario when i submit a form the id of my page needs to update automatically. for example if i enter id 3 and submit the html form, when i open the form again it must check the Id from database and show the next id.
This means if the last data i entered has id 3 it then show me id 4 automatically when i refresh the page and want to submit new data
how can i add ID validation query in that code
need your expert advises.. thanks alot!!!
Html
<form action="survey-data-entry.php" name="1st-form" id="form-control" method="post" >
<label>Id.</label>
<input type="text" class="form-control" placeholder=" 0451211315" name="ID" id="id" required>
php
if(isset($_POST['ID'])){
$ID = $_POST['ID'];
$sql= "INSERT INTO phpstartup (ID, )
VALUES('$ID') ";
if(!mysql_query($sql))
{
die('caution' . mysql_error());
}
echo"1 record added";
}
You need to get the maximum of id + 1 from the query to use it for your next submission.
$rslt = mysql_query('SELECT MAX(ID) + 1 as nextId FROM phpstartup');
$row = mysql_fetch_assoc($rslt);
$nextId = $row['nextId'];
Now you can use the variable $nextId in your forms for re submission.
I have created a simple (but long) HTML form, i need the used to be able to save the form progress and return to it at a later date (security is not a big issue). But i am having trouble going about saving the form state and then recalling it later. (warning, im a noob)
So what is have is:
I have a form
<form action="phpSaveTry1.php" form method="post">
When the form is submitted with the save button
<INPUT TYPE = "Submit" Name = "Save" VALUE = "Save and Submit">
I try to save all the posted variables in a file on the server in the following way... (other suggestions are welcome)
$varNameArray = array("fname","mname","lname","comment","email","website","saveFile");
if (isset($_POST['Save'])) {
for($i = 0; $i < count($varNameArray); ++$i) { //go through every variable and add it to array
$arrayOfVars[$varNameArray[$i]] = ($_POST[$varNameArray[$i]]);
}
}
$saveFileName = "NameOfSavedState";
$var_str = var_export($arrayOfVars, true);
$var = "<?php\n\n\$$arrayOfVars = $var_str;\n\n";
file_put_contents(sprintf("/home/pansyc5/public_html/Jul17/SavedForms/%s.php",$saveFileName), $var);
Then in the html header where the form is contained i want to recall the variables
$saveFileName = "NameOfSavedState";
include sprintf("/home/pansyc5/public_html/Jul17/SavedForms/%s.php",$saveFileName);
and recall the values into the fields by first repopulating the variables
for($i = 0; $i < count($varNameArray); ++$i) { //go through every variable and declare it
$varNameArray[$i] = ( $arrayOfVars[$varNameArray[$i]] );
}
And then repopulating the form by setting the html values as e.g;
Last Name: <input type="text" name="lname" value="<?PHP print $lname; ?>">
I am new to website design, but this seems like a quite convoluted way of going about saving a form session ( not to mention, it is not working ).
What is the correct way of repopulating or saving a form state ?
Throw all of this code away. By writing data to a PHP file, you're creating a security nightmare. There's really no reason for most of your code. Try something simpler:
session_start();
$_SESSION['lastFormData'] = $_POST;
Then when you populate your form later...
echo '<input name="lname" value="' . htmlspecialchars($_SESSION['lastFormData']['lname']) . '" />';
The news feed on the sites dashboard I'm working on has multiple items from different users; and can also be commented on. However, whenever you write a comment under each post, it only posts to the post at the top of the feed (the most recent one). Comments are posted instantly by pressing the enter key, which then runs this JS code which is on the index.php page.
$(function(){
$('#comment_body').live( 'keypress' , function (e) {
var boxVal = $(this).val();
var sendTo = $('#to_id').val();
if ( e.keyCode == '13' ) {
e.preventDefault();
$.post( 'instantcom.php' , { 'comment_body' : boxVal , 'activity_id' : sendTo } , function () {
// reload data or just leave blank
} );
$('#comment_body').val('');
}
} );
});
Then, the HTML for the comment box on each post is as follows:
<p align="center" style="height:45px;">
<input type="text" name="comment_body" id="comment_body" style="margin-top:12px;border:1px solid blue !important;width:329px;height:21px;" />
<span class=" glyphicons-icon camera" style="position:relative;bottom:50px;left:155px;"></span></p>
<input name="type" type="hidden" value="a" />
<input name="activity_id" id="to_id" type="hidden" value="' . $act_item_id . '" />
The ' . $act_item_id . ' is just a PHP variable which contains the unique ID of the status update.
So then, any ideas as to why comments are only posting to the most recent posts instead of the ones they're meant to post to?
You're using an id to identify which post you're commenting against? to_id right? Well, that's an id on the page, id's should be unique to the page.