Using AJAX to pass variable into PHP array - php

I have looked around various other questions relating to this topic but I am still struggling to find a solution to my query.
In my system I am allowing the admin to append extra form nodes to the file so they may input any extra required data, this data is then submitted to the DB to generate pages in the main portion of the site.
I am new to the concept of passing the data back via AJAX so I may be misunderstanding something but here is my code.
Add Node Control
<div id="nodeControl">
<div id="addNode">
<a id="nodeLink" href="#">+</a>
</div>
</div>
<div id="slideOut">Click to add a new section</div>
Add Node click response function
var nodeCount = 2;
$("#nodeLink").click(function(){
// Local Variables
var newSection = '<br/><div id="sectionInfo"><div id="sectionWrap"><div id="sectionInner"><label class="inst head">Section ' + nodeCount + '</label><input class="textOver" type="text" name="sectionTitle' + nodeCount + '" value="<?php $title; ?>"> <label class="inst ib">Please enter any text you would like associated with the section.</label> <textarea style="margin-top: 3px" name="sectionContent' + nodeCount + '" value="<?php $body; ?>"></textarea> <label class="inst ib">Please upload the image associated with this section, .PNG reccomended.</label> <input type="file" style="visibility:hidden;" name="img' + nodeCount + '" id="upload" /> <input type="button" id="fileStyle" class="fSOver" value="Upload Pump Image!" /> </div> </div> </div>' ;
// Append the new section to the document and increment the node count
$('#sections').append(newSection);
nodeCount += 1;
// Call AJAX to pass to PHP
$.ajax({
type: "POST",
url: "../section.php",
data: { setSection : newSection },
success: function() {
alert("Success, ajax parsed");
}
});
$(".successDiv").slideDown(150);
$(".successDiv").delay(1500).slideUp(150);
return false;
});
Node count is instantiated to "2" here, when a node is added the number is appended to the name attribute of any input elements on my form i.e. header2, header3 etc.
This is so when my form is eventually submitted I can loop through each data field and submit it to the database.
As I currently understand the AJAX data variable uses key pairs { a : b } where a = return key and b = return value, I want PHP to be able to access that returned value and store it into an array which can be looped through at the end.
Currently the success message is triggered on my AJAX call but I am unable to access the values in PHP, instead I am thrown an "Undefined index of sections defined".
$section = array();
$setSection = $_POST['setSection'];
$section[] = $setSection;

PHP won't store every setSection variable you pass it over time; each time your script is called, its variables are reset. You probably want to store the variable in a database or session variable.
Here's one approach, using session variables:
session_start(); // unless you already started one
if (!isset($_SESSION['section'])) {
$_SESSION['section'] = array();
}
array_push($_SESSION['section'], $_POST['setSection']);

Related

multiple dynamically created buttons with same name using ajax

I'm trying to implement a comment section and after button-press I want to update the comment section with ajax so the page doesn't have to refresh...
In this comment section I have 1 textarea + 1 button + a couple of hidden fields for every comment so users can answer specific comments...
so if there are 50 comments there are also 50 answer-fields, 1 for each...
And every thing works except for 1 thing...
- either I name all id's of the buttons and fields the same name (ie. id="sendAnswer" and id="answer", id="userID", ...) and then only the first one works...
-or I dynamically name them all (ie. id="sendAnswer(echo $i) ) thereby naming them all id="sendAnswer0", "sendAnswer1", "sendAnswer2", ... and then I do that for the textarea and hidden fields too (ie. id="answer(echo $i), id="userID(echo $i), ...)
And that works great too... except for now I have to make a jQuery-script for each... and since they are dynamically created that's difficult - as how many there are changes as more comments comes in...
Code for approach 1: naming them all the same...
$(document).ready(function(){
"use strict";
$("#sendAnswer").click(function(){
var comment = $("#comment").val();
var userID = $("#userID").val();
var randomStringVideo = $("#randomStringVideo").val();
var commentID = $("#commentID").val();
$.ajax({
type: "POST",
url:'../scripts/comment.php',
data:"comment="+comment+"&userID="+userID+"&randomStringVideo="+randomStringVideo+"&commentID="+commentID,
success:function(){
$("#commentDiv").load(location.href + " #commentDiv>*", "");
$("#commentsDiv").load(location.href + " #commentsDiv>*", "");
$("#comment").val('');
}
});
});
});
And as I said... this works fine for the first one and the rest are duds...
Code for approach 2: I dynamically name all values...
$(document).ready(function(){
"use strict";
$("#sendAnswer"+$(this).val()).click(function(){ // this +$(this).val() doesn't work, only if I put #sendAnswer3 - then the 4th works and the rest are duds etc.
var comment = $("#comment"+$(this).val()).val(); // works perfectly no matter what #sendAnswer I use
var userID = $("#userID"+$(this).val()).val(); // works perfectly no matter what #sendAnswer I use
var randomStringVideo = $("#randomStringVideo"+$(this).val()).val(); // works perfectly no matter what #sendAnswer I use
var commentID = $("#commentID"+$(this).val()).val(); // works perfectly no matter what #sendAnswer I use
$.ajax({
type: "POST",
url:'../scripts/comment.php',
data:"comment="+comment+"&userID="+userID+"&randomStringVideo="+randomStringVideo+"&commentID="+commentID,
success:function(){
$("#commentDiv").load(location.href + " #commentDiv>*", "");
$("#commentsDiv").load(location.href + " #commentsDiv>*", "");
$("#comment"+$(this).val()).val(''); // this +$(this).val() doesn't work, only if I put #comment3 (matching the #sendAnswer)- then the 4th works and the rest are duds etc.
}
});
});
});
With this I would have to name every single possible #sendAnswer-number + #comment-number for it to work... and with an infinite set of numbers to choose from 0-(infinite) - that's not viable...
If of any interest...
Php that dynamically creates the buttons and fields in question
.
.
.
<?php if ($_SESSION[numberOfComments] != 0) {
for ($i=0; $i<$_SESSION[numberOfComments]; $i++) ?> // run through all comments that aren't answers to other comments
// show comment info
<div class="media">// answer comment box starts here
<img class="mr-3 rounded" src="<?php $file = USER . $_SESSION['randomString'] . THUMBNAIL; if ( file_exists ( $file ) ) {echo $file; } else { echo USER . "default" . THUMBNAIL; } ?>" width="50" height="50" data-toggle="tooltip" data-placement="left" title="<?php echo $_SESSION['username']; ?>">
<div class="media-body">
<textarea class="form-control" rows="2" type="text" name="comment<?php echo $i; ?>" id="comment<?php echo $i; ?>" value="" placeholder="Great video!"></textarea>
<input type="hidden" name="userID<?php echo $i; ?>" id="userID<?php echo $i; ?>" value="<?php if ( isset ( $_SESSION['id'] ) ) { echo $_SESSION['id']; } ?>">
<input type="hidden" name="randomStringVideo<?php echo $i; ?>" id="randomStringVideo<?php echo $i; ?>" value="<?php echo $_GET['v']; ?>">
<input type="hidden" name="commentID<?php echo $i; ?>" id="commentID<?php echo $i; ?>" value="<?php echo $_SESSION['commentID_getComment']; ?>">
<button type="button" class="btn btn-primary float-right margin-top-5" id="sendComment<?php echo $i; ?>" value="<?php echo $i; ?>">
Answer
</button>
</div>
</div> // answer comment box ends here
<?php if ($_SESSION[numberOfAnswers][$i] != 0) {
for ($j=0; $j<$_SESSION[numberOfAnswers][$i]; $j++) { ?> // run through all answer to this comment
// show answer info
<?php }
}
}
} ?>
.
.
.
two ways .. 1st use classes instead of ids .OR. 2nd use selector id starts with [id^="something"] .. and on both ways you need to use $(this) to refer to the same section .. And for me its bad practice to use .load() to refresh the whole comment section you can directly get the specific comment and append it to the #commentDiv
by using $("#sendAnswer"+$(this).val()) $(this) in this case refer to nothing/window or something else but not to your element
$(document).ready(function(){
"use strict";
$('button[id^="sendAnswer"]').on('click',function(){
var ThisIs = $(this);
var ClosestDiv = ThisIs.closest('.media-body');
var comment = ClosestDiv.find('textarea').val();
var userID = ClosestDiv.find('[id^="userID"]').val();
var randomStringVideo = ClosestDiv.find('[id^="randomStringVideo"]').val();
var commentID = ClosestDiv.find('[id^="commentID"]').val();
$.ajax({
type: "POST",
url:'../scripts/comment.php',
data:"comment="+comment+"&userID="+userID+"&randomStringVideo="+randomStringVideo+"&commentID="+commentID,
success:function(){
var commentDiv = ThisIs.closest('.BigDiv').find('[id^="commentDiv"]'); // change `.BigDiv` with the div id/class which hold both commentDiv and comment section
commentDiv.load(location.href + " #commentDiv>*", "");
ClosestDiv.find('textarea').val('');
}
});
});
});
Note: Change .BigDiv with the div id/class which hold both
commentDiv and comment section
Using your current approach, where everything is identified with ids, the best option would be to use event delegation. Create just one event handler, on some parent element which exists at the time the page is loaded, which via delegation will handle any of your buttons - existing and future. Once the handler fires, you can determine which set of elements you are working with, and continue as normal.
Here's an example, using body as the parent, but you can use any element which contains all your present and future buttons/inputs, eg maybe you have a parent <div id="something">. This also assumes your button inputs are actual button elements, you'll have to adjust if that's not the case:
$(document).ready(function(){
"use strict";
// A single event handler on body, which handles any child button
$("body").on('click', 'button', function(event) {
// $(this) will be the button that was clicked. We can find its id,
// and if your buttons all have ids like sendAnswer1, sendAnswer2,
// sendAnswerX, we can find the X
var id = $(this).attr('id').replace('sendAnswer', '');
// Now we can use the X to access each of this button's matching
// inputs etc. Again this assumes your other elements have ids like
// commentX.
var comment = $("#comment" + id).val(),
userID = $("#userID" + id).val(),
// ... etc, rest of your code
As well as the article linked above, the jQuery .on() docs have a good description of event delegation (see "Direct and delegated events").
Update
Another option, which I find neater, is to wrap each comment section in a div (or any identifying element, such that each comment/input/button set is nested inside it), and use only classes for each element. Again using event delegation, you can find the section which contains the button that was clicked, and therefore identify which input elements you're working with.
For example, your HTML might look like:
<div id="all-comments">
<div class="comment-section">
<textarea class="comment" name="whatever"> ... </textarea>
<button name="button" type="submit">Post!</button>
<!-- your hidden fields, etc -->
</div>
<div class="comment-section">
...
</div>
<!-- ... etc, many comment sections -->
</div>
Now your JS would look something like this:
$(document).ready(function(){
"use strict";
// A single event handler on the parent div, which handles any child button
$("#all-comments").on('click', 'button', function(event) {
// $(this) will be the button that was clicked. We need to find the
// .comment-section containing that button
var div = $(this).closest('div.comment-section');
// Now we can find all elements inside that particular section
var comment = $(".comment", div).val(),
userID = $(".userID", div).val(),
// ... etc, rest of your code

access pair value in array in php which send using ajax

I'm new in php ajax and get two problem. The first problem, I want to save pairs of values (consist of value in text and it attribute) in an array every I click button. Is my method to push in array true? and the second, how I can access the array in php and insert to database? below is my HTML code
<script>
var a=0;
var b=1;
var tanya= new Array();
var object = {};
var pilgan= new Array();
function question(){
var x = $('#jenis').val();
a++;
if (x=="Multiple Choice") {
$("select").css("display","none");
alert("Pilihan :"+a);
$('ol').append('<li><input type="text" name="tanya" id="thequestion" uruts="'+a+'" class="thequestion" style="color: black; width: 50%;"><button style="margin-left:10px;" id="tambah" class="tambah">Choice</button><div id="thechoice" class="thechoice"><input type="radio" id="pilihan"><input type="text" name="text" urutp="'+a+'" class="text" id="text"><br/></div></li>');
}else if(x=="Essay"){
$("select").css("display","none");
$("#jenis").css("display:none;");
$('ol').append('<li><textarea name="text" uruts="'+a+'" id="thequestion" style="color: black; width: 50%;"></textarea>');
}
}
function uploadQuestion(){
$.ajax({
url : "questionDosenAjax.php",
type : "POST",
async : false,
data : {
upload : 1,
question : tanya,
choice : pilgan
},
success : function(res){
$('#coba').html(res);
}
});
}
$(document).ready(function(){
$("#backMakeAss").click(function(){
changePage("pilihanAssignAjax.php");
});
$('ol').on('click','button',function(){
alert("Pilihan :"+a);
//$pilgan.push(pilihan:$('#thechoice').val(), id:$('#thechoice').attr('urutp'))
$(this).siblings('#thechoice').append('<input type="radio" id="pilihan"><input type="text" name="text" class="text" id="text" urutp="'+a+'"><br/>');
});
$("#kumpul").click(function(){
object[$('#thequestion').attr('uruts')] = $('#thequestion').val();
tanya.push(object);
//$pilgan.push(pilihan:$('#thechoice').val(), id:$('#thechoice').attr('urutp'))
uploadQuestion();
});
$('#add').click(function(){
var id = $('#thequestion').attr('uruts');
var value = $('#thequestion').val();
object["id :"+id] ="value :"+value;
tanya.push(object);
//$.each(tanya, function (index, value) {
//alert({"id: "+value.id +" and value: "+ value.value});
//});
//$pilgan.push(pilihan:$('#thechoice').val(), id:$('#thechoice').attr('urutp'))
});
});
</script>
This is my php code, I don't know why it doesn't work.
<?php
$con = mysqli_connect("localhost", "root", "", "lantern");
if(isset($_POST['upload'])) {
$pertanyaan = count($_POST['question']);
$pilihan = $_POST['choice'];
for($i=0;$i<sizeof($pertanyaan);$i++){
echo $_POST['question'][$i+1]."\n";
}
}
?>
Thank you and sorry if my english not good.
There are several issues with your code.
Firstly, you're generating multiple elements with the same ID (#thequestion). IDs are supposed to be unique. When you try to access the elements through jQuery later on it is not clear which element it is that you want. You could reference the elements by their (unique) uruts attribute like so:
$('.thequestion[uruts="' + number + '"])
, but it would probably be a better idea to give each thequestion element a unique ID like
<input type="text" name="tanya" id="thequestion_' + a + '" uruts="' + a +'" class="thequestion" style="color: black; width: 50%;">
and then reference them as
$('#thequestion_' + number)
But since you never seem to be calling the question() function, it's not really clear to me where those elements are coming from in the first place. (It could be helpful if you also posted your HTML.)
Next, what you probably want in the event listener for #add instead of
object["id :"+id] ="value :"+value;
is just
object[id] = value;
or maybe (but I doubt it, because it's neither the way you do it in the #kumpul event listener (where you do it differently from here) nor does it seem to be what your php expects):
object[id] = {
'id': id,
'value': value
};
However, since you extend the object object every time the event is fired and then push the extended object into the tanya array, you push a new copy of the entire object in there every time, when what you really want is more likely just the new value. So
tanya[id] = value;
should be sufficient. Also it's not really clear to me why you do the pushing again in the event listener for #kumpul. Actually, it seems like you could just get rid of the object object altogether.
Then in your PHP, you could drop the $pertanyaan variable and rewrite
for($i=0;$i<sizeof($pertanyaan);$i++){
echo $_POST['question'][$i+1]."\n";
}
as
foreach($_POST['question'] as $question){
echo $question ."\n";
}
Your method is not necessarily wrong, it's just that there's an easier way to achieve the same thing. (Edit: actually it is wrong, I didn't look properly before. With $pertanyaan = count($_POST['question']); you already have an integer in $pertanyaan. You do not need to use sizeof on that. count and sizeof are aliases, they do exactly the same thing.)
(Also, google "PHP SQL injection" sometime. You really do not want to send user input to the database as-is, but I'll leave it at that for the moment. You mention a database so I'm assuming that's what you want to do with the $_POST data eventually.)
Then, in these two lines:
$("select").css("display","none");
$("#jenis").css("display:none;");
, the first line is the correct way to do this with jQuery, while the second one is incorrect and won't work.
Finally, is there any reason why your AJAX call needs to be synchronous (async: false in the settings)? This is generally discouraged these days (see https://stackoverflow.com/a/6685294/1901379).

Dynamically added form elements are posted to PHP but cannot access them

I'm posting dynamically added form elements to PHP via AJAX.
I can see that the serialised form data is posted to the php, but when I try to access the data within it, some of the fields come up NULL i.e. var_dump in the PHP below shows NULL.
this is the Jquery that adds the dynamic elements:
$(function(){
var count=0;
$('#more_edu').click(function(){
count ++;
$('#education_add').append('<br><br><label>University/Institution: </label><input type="text" class="searchbox" id="edu_inst'+count+'" name="edu_inst[]" maxlength="200" value="">);
event.preventDefault();
});
});
and the Jquery posting to php:
function profileSub(){
var myform;
event.preventDefault();
myform = $('form').serialize();
$.ajax({
type: 'POST',
url: 'tutorprofileinput.php',
data: {"form": myform},
success:function(data, response, xhr){
console.log(response);
console.log(data);
console.log(xhr);
},
error:function(){
// failed request; give feedback to user
$('#ajax-panel').html('<p class="error"><strong>Oops!</strong> Try that again in a few moments.</p>');
}
});
}
This is the original form:
<form id="tutor_profile_input" onsubmit="return false;">
<label>University/Institution: </label>
<input type="text" class="searchbox" id="edu_inst" name="edu_inst[]" maxlength="200" value=""> </br></br>
<label>Subject:</label>
<input type="text" class="searchbox" id="edu_subj" name="edu_subject[]" maxlength="200" value=""></br></br>
<label> Level </label>
<select id="edu_level" name="edu_level[]">
and the PHP itself:
<?php
if (isset($_POST['form'])){
$form = $_POST['form'];
var_dump($_POST["edu_inst"]);?>
This is the var dump of the whole $_POST:
location=&price=&tutorname=&edu_inst%5B%5D=Uni1&edu_subject%5B%5D=subje1&edu_level%5B%5D=BA&edu_inst%5B%5D=uni2&edu_subject%5B%5D=subj2&edu_level%5B%5D=BA&bio=%09&exper
The form you've posted has an ID of #tutor_profile_input, where as the one you're appending to in the jQuery function is #education_add - Unless I've misunderstood?
Otherwise I'd look at specifying a more specific target in the AJAX request - You're just targetting $('form') at the moment which could be any form on the page..
Have discovered the answer so thought I would share - The Jquery serialize() function encodes the data into a string, which is then posted to PHP as an array with the key of "form".
In order to deal with this in php I had to first use the urldecode function in PHP to convert the string encoded elements (%5B%5D) from the name attributes. This was because there might be multiple values in these so they were declared in the form as an array ("name="edu_insts[]"). Then use parse_str to split the string into an array.
<?php
$querystring = $_POST['form'];
$querystring = urldecode($querystring);
parse_str($querystring, $params);
$insts = $params['edu_inst'];
echo $insts[0]."<br>";
echo $insts[1]."<br>";
?>
This will create an array named $params with keys corresponding to the form name attributes.
Note that if you have multiple values within the same name, then each one will be placed within an array itself, so with the above text you will have $insts[0] = University 1
and $insts[1] = University 2 etc.
Hope this helps anyone with the same problem.

How do I pass a dynamically created list to the controller to save into the database?

I am working in Concrete5 and am new to the MVC concept. I have a some jquery that creates an unordered list from a textbox in my view. If your familiar with Concrete5 this is the view for the block I am adding the list to. It is basically a list of features for a product. This view needs to save the list to the database base file. Usually this is done pretty simply using a variable that the information gets saved to (aka this is how everything else in the view is saved). The problem I am having is I do not know how to use the controller to pass the unordered list from the view to the controller to the database so that it saves it. Any help and sample code would be appreciated. I'm pretty sure I need to write a php function in my controller to get the list but I am not sure what the code would be.
auto.js
$("#addList").click(function() {
var text = $("#inputList").val() + '<button>x</button>';
if(text.length){
$('<li />', {html: text}).appendTo('ul.featureList')
};
});
$('ul').on('click','button', function(el){
$(this).parent().remove()
});
add/edit.php
<div class="ccm-block-field-group">
<h2><?php echo t('Features') ?></h2>
Right now 'features' is the name of the field in my database file db.xml
The area featureList is where the list get generated into. I know it needs to be changed around a bit to work, just not sure.
<?php echo $form->textarea('features', $features, array());?>
<input type="test" id="inputList" />
<button type="button" id="addList">Add</button>
<ul class="featureList"></ul>
</div>
view.php
echo "<h2>{$proName}</h2>";
echo "{$description}";
echo "<h3>{$features}</h3>";
echo "<h2>{$price}</h2>";
echo "<p>{$priceInfo}</p>";
db.xml
<field name="features" type="X2"></field>
With concrete5 blocks, there are two different situations you could be in:
admin user is editing the block (or adding a new block), and you want to save this data to the database.
public user is viewing the block, but the block view itself has a form (for example, a contact form block) and you want to do something when the public form is submitted (for example, send a notification email to an admin that someone has filled out the form, or store the submission in a database for future review).
If you're talking about situation #1, you need to put some custom code in the controller's save() method. If you're talking about situation #2, you need to create your own action method in the controller, AND you need to actually have a <form> in the view.php file.
UPDATE: Based on the sample code you added to your question, here is the solution:
The only way your data can get back to the server is via a form POST. <li> elements are not form fields, and hence the data in them doesn't get POST'ed with the form. So when you add the new <li> element to the page, you should also add a hidden form field, like so:
var listItemCounter = 0;
$("#addList").click(function() {
listItemCounter++;
var text = $("#inputList").val() + '<button data-id="' + listItemCounter + '">x</button>'; //assign a unique id number to this button, so it knows which hidden field to remove when clicked
if(text.length){
$('<li />', {html: text}).appendTo('ul.featureList');
$('<input type="hidden" name="features[]" value="' + text + '" data-id="' + listItemCounter + '" />').insertAfter('ul.featureList');
};
});
$('ul').on('click','button', function(el){
$('input[data-id="' + $(this).attr('data-id') + '"]').remove(); //remove the hidden field so it does not get POSTed when user saves
$(this).parent().remove();
});
Now, in your block's controller.php file, you will want to add a save() method that will take all of the data from those hidden fields, combine them and put them into the "features" field that you declared in your db.xml file:
public function save($args) {
$args['features'] = implode("\n", $args['features']); //combine all feature items into one string, separated by "newline" characters
parent::save($args);
}
Finally, in your view.php file, you can convert the list of features (which was saved to the database as one string, with each item separated by a "newline" character) like so:
<?php echo nl2br($features); ?>
Or if you want to output it as separate list items, you could do something like this:
<ul>
<?php
$features = explode("\n", $features);
foreach ($features as $feature) {
echo '<li>' . $feature . '</li>';
}
?>
</ul>
You dont pass stuff from the view to the controller. The controller is executed BEFORE the view, so you only pass from controller to view.
Try accessing the stuff you pass from jquery to your application using
$this->getRequest()->getParam('yourParametersName');
inside the controller.
Lucian
I changed around the auto.js file so it is as follows. Seems to work fine.
var listItemCounter = 0;
$("#addList").click(function() {
listItemCounter++;
var text = $("#inputList").val(); //assign a unique id number to this button, so it knows which hidden field to remove when clicked
var buttonDataId = text + '<button data-id="' + listItemCounter + '">x</button>';
if(text.length){
$('<li />', {html: buttonDataId}).appendTo('ul.featureList');
$('<input type="hidden" name="features[]" value="' + text + '" data-id="' + listItemCounter + '" />').insertAfter('ul.featureList');
};
});
$('ul').on('click','button', function(el){
$('input[data-id="' + $(this).attr('data-id') + '"]').remove();//remove the hidden field so it does not get POSTed when user saves
$(this).parent().remove()
});
I left the view the same as what Jordan Lev put. (Thanks!)
Then I changed the controller.php to
public function save($args) {
$args['features'] = implode("\n", $args['features']);//combine all feature items into one string, separated by "newline" characters
parent::save($args);
}
If anyone sees any problems or a better way to put my code please let me know!
My new problem now is once it is saved, if I go to edit the list, it wipes out my past entries and saves the new one. If anyone knows the function I would have to write to show the current list and add to it when editing that would be great. Please give some example code.

how to remember input data in the forms even after refresh page?

what to do in order to make the form remember the previous input or the current input of the user even after he/she refreshed the page ?
should I do ,
<div class="row">
<label>Contact Messenger </label>
<input type="text" name="messenger" id="messenger" size="50" maxlength="50" value="<?php echo $_SESSION['messenger']; ?>"/>
</div>
or
<div class="row">
<label>Contact Messenger </label>
<input type="text" name="messenger" id="messenger" size="50" maxlength="50" value="<?php echo $_POST['messenger']; ?>"/>
</div>
or
there's a trick to do it ?..how ?
on the page where your form is submitting do something like this
session_start();
$_SESSION['data'] = $_POST['data'];
$_SESSION['data_another'] = $_POST['data_another'];
and than you can access those session variables any where like this
session_start(); // this should be at the top of the page before any html load
<input type="text" name="name" value="<?php echo $_SESSION['data'];?>"/>
refresh your page on success call like this
$.ajax({
type: "POST",
url: "yourfile.php",
data: 'data='+ data,
success: function(){
location.reload();
}
});
I had similar issue at one of my project so I wrote some js to handle this using cookies.
First I found two simple functions to set and get cookies values:
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
function getCookie(c_name) {
var c_value = document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1) {
c_start = c_value.indexOf(c_name + "=");
}
if (c_start == -1) {
c_value = null;
} else {
c_start = c_value.indexOf("=", c_start) + 1;
var c_end = c_value.indexOf(";", c_start);
if (c_end == -1) {
c_end = c_value.length;
}
c_value = unescape(c_value.substring(c_start, c_end));
}
return c_value;
}
Than I wrote two other functions to set and get input values:
function saveValue(input) {
var name = input.attr('name');
var value = input.val();
setCookie(name,value);
}
function getValue(input) {
var name = input.attr('name');
var value = getCookie(name);
if(value != null && value != "" ) {
return value;
}
}
And using jQuery I save user's input value to session cookie
$('input[type=text]').each(function(){
var value = getValue($(this));
$(this).val(value);
}).on('blur', function(){
if($(this).val() != '' ) {
saveValue($(this));
}
});
I hope it'll help ;)
That quite depends on where the data in the fields is coming from.
If your scenario is that you are presenting a blank form, the user enters some data and then without submitting it, refreshes the page, there is nothing you can do. That's up for the browser to handle.
You might be able to do some very weird JavaScript hacking there, but I would not suggest that.
On the other hand, if your data is coming from a previous page or something like that, that's a different story. But then you need to tell us where the data is coming from, so I can give you a reasonable answer.
If you mean, filling out form fields and clicking refresh, then there is no direct way, as the data isn't submitted. That sort of behavior is up to the browser.
The only thing you could do is post the data via AJAX back to your server as the fields change. Your PHP script receiving the data would set some session variables. When the form loads, you would set their default values to the appropriate session values.
Rarely though is there a need for this kind of behavior. There will be many requests sent back and forth to your server.
Session is a good way to store and remember data but why complicate things? Consider if the form has many fields, developer has to store lots of values in session. Why not simply print or echo.
Example:
Form is submitted with input ssName and hidden field ssAct with value of send
Get the ssName and ssAct on form submit
$ssAct=$_REQUEST["ssAct"];
$ssName=$_REQUEST["ssName"];
and the form
<input type="text" name="ssName" value="<?php if($ssAct=='send' && $ssName!='') { echo "$ssName"; } ?>">
<input type="hidden" name="ssAct" value="send">
On submit name will be echoed if it was submitted and was not empty.
None of your suggestions will help you "remember" data after a refresh (action that not send data to the server). What you need is to grab data via javascript (maybe with onkeyup events type) and grab it using cookies. With jquery is very easy.
There are some main issues to check in order to get the data appear after refresh or any event handler:
1) Be aware of the signature. it must contain the method="post" attribute as follows:
<form method="post"/>
else the using of the $_POST['messenger'] will not work.
The default value of the method attribute in the form is get.
<form> equals to <form method="get">
2) Many programmers mix between the attributes id vs name.
Be aware of using the correct attribute. The $_POST associative array is using the name to get data from it. That is why the next example will not work correctly:
<input type="text" id="data" value="<?php echo isset($_POST['data']) ? $_POST['data'] : "" )?/>"
To get it work right you must add the attribute name="data" as follows:
<input type="text" name="data" id="data" value="<?php echo isset($_POST['data']) ? $_POST['data'] : "" )?/>"
Good luck
You could also do without session like the below code:
<input type="text" name="Fname" value="<?php if(isset($_POST['Fname'])){ echo $_POST['Fname']; } ?>" /><br/>
This will keep the typed data inside the input box!
after posting your details to session, write like this in value
<?php print $_SESSION['messenger'] ?>
if you are writing both php and HTML in same file then you can do like this
<?php print $messenger] ?>
try the attribute autocomplete, maybe it will work on some browsers...
<input type="text" autocomplete="on" />
You can use autocomplete for a form too.

Categories