How to remember form values across different pages? - php

I need to send form values from one page to another and from that page to a third page. I would need the form values from the first page in the third page. How can I do it?
I have the code that transfers form values to the next page. How can I send the same form values to the third page?
<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
<script type="text/javascript">
// we will add our javascript code here
$(document).ready(function(){
$("#ajax-contact-form").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "contact.php",
data: str,
success: function(msg){
$("#note").ajaxComplete(function(event, request, settings){
if(msg == 'OK') // Message Sent? Show the 'Thank You' message and hide the form
{
result = '<div class="notification_ok">Your message has been sent. Thank you!</div>';
window.location.href = "http://www.google.com";
$("#fields").hide();
}
else
{
result = msg;
}
$(this).html(result);
});
}
});
return false;
});
});
</script>

you can use GET
window.location.href = "http://yourdoamin?value= serialize text variable";
Get URL parameters & values with jQuery

Assuming you're using only simple values (not passing arrays), you can do something like this:
echo "<form id='second_page' method='post' action='third_page.php'>";
foreach ($x in $_POST) {
echo '<input type="hidden" name="' . htmlspecialchars($x) . '" value="' . htmlspecialchars($_POST[$x]) . '" />';
}

Use sessions - here is a Tutorial

You can set the values from Form #1 as input tags with hidden type in Form #2. That way, when you submit Form #2, values will be available in Form #3.

Related

PHP not echoing back data from form submit

My page has an html form to collect email, first name, last name and a checkbox. The form begins with this header:
<form action="echo_test.php" method="post" name='register' id='register'>
I submit the form with this button:
<div class="EMail_Pwd_JoinPage"><button class="btn_joinnow" style="color:rgb(255,255,255);" id="btn_submit" onclick="GetDate(); GetCkBx();">Submit data</button></div>
That calls this jquery function:
<script type="text/javascript">
$("#btn_submit").on("click", function (event) {
event.preventDefault();
form_data = $('form').serialize()
console.log("Okay, I'm starting");
console.log(form_data);
console.log("More Info");
GetDate();
return $.ajax({
type: "POST",
url: "echo_test.php",
data: form_data,
success: function (responseText) {
console.log("Server Reply " + responseText);
},
error: function (error) {
console.log("Okay, I failed" + error);
}
});
});
</script>
It submits to echo_test.php on my server:
<?php
echo 'Hello ' . htmlspecialchars($_POST["firstname"]) . '!';
?>
In the onclick event submit code above it should reply from the server:
success: function (responseText) {
console.log("Server Reply " + responseText);
},
But the Chrome dev console does not show any reply. The other console.log messages above do appear correctly (including the serialized form data).
I asked a similar question back in May, but the situation is different here.
Why doesn't this code echo back from the server?
Idk what does onclick attribute mean,
onclick="GetDate(); GetCkBx();"
So i think just remove onclick attribute. And here new code,
<div class="EMail_Pwd_JoinPage"><button type="submit" class="btn_joinnow" style="color:rgb(255,255,255);" id="btn_submit">Submit data</button></div>
Also update your button action jQuery code,
$("#btn_submit").on("submit",
As per my comment, remove onclick="GetDate(); GetCkBx();" from the button tag and call those two functions in the click event handler you created.
New Button Tag:
<button class="btn_joinnow" style="color:rgb(255,255,255);" id="btn_submit">Submit data</button>
in echo_test.php return the echo statement or use die().
<?php
echo 'Hello ' . htmlspecialchars($_POST["firstname"]) . '!';
return;
?>

Ajax display msg on submit without refresh

I am submitting form data via Ajax and would like to display a message above the form on successful submit.
Currently the form does send the data successfully. It should render the feedback message on form submit <?php $this->renderFeedbackMessages(); ?> as defined in my config.php
Where am I going wrong? Possibly doing things in the wrong order due to first time working with mvc?
my config.php file I have the following defined;
define("FEEDBACK_BOOK_ADD_SUCCESSFUL", "Book add successful.");
my model;
public function addIsbn($isbn)
{
// insert query here
$count = $query->rowCount();
if ($count == 1) {
$_SESSION["feedback_positive"][] = FEEDBACK_BOOK_ADD_SUCCESSFUL;
return true;
} else {
$_SESSION["feedback_negative"][] = FEEDBACK_NOTE_CREATION_FAILED;
}
// default return
return false;
}
my controller;
function addIsbn()
{
// $_POST info here
header('location: ' . URL . 'admin/searchIsbn');
}
my searchIsbn.php;
<?php $this->renderFeedbackMessages(); ?>
<div>
//my html form here
</div>
<div id="result"></div>
<script>
$('#form').submit(function() {
event.preventDefault();
var isbn = $('#isbn_search').val();
var url='https://www.googleapis.com/books/v1/volumes?q=isbn:'+isbn;
$.getJSON(url,function(data){
$.each(data.items, function(entryIndex, entry){
$('#result').html('');
var html = '<div class="result">';
html += '<h3>' + entry.volumeInfo.isbn + '</h3>';
html += '<hr><button type="button" id="add" name="add">add to library</button></div>';
$(html).hide().appendTo('#result').fadeIn(1000);
$('#add').click(function(ev) {
$.ajax({
type: 'POST',
url: '<?php echo URL; ?>admin/addIsbn',
data: {
'isbn' : isbn
}
});
});
});
});
});
</script>
No console error messages.
You are redirecting here:
header('location: ' . URL . 'admin/addIsbn');
remove it.
echo the success message here and add it to an HTML element's .html() API.
Your page will not be refreshed.
Your page is making the call to admin/addIsbn which is redirected to admin/searchIsbn. So you already have the output of renderFeedbackMessages() being sent to your function.
Use the success callback to output the results to the page:
$.ajax({
type: 'POST',
url: '<?php echo URL; ?>admin/addIsbn',
data: {
'isbn' : isbn
},
success: function(data) {
$('#result').html(data);
}
});
The only way I could get this to work was to add an auto-refresh to my Ajax success function as follows;
window.location.reload(true);
Working however open to suggestions.

Sending array data to PHP from jQuery and retrieving the value

I am working on a login form. The form fields are validated via jQuery . After jQuery validation the control goes to the php page then it fetches the values from the table in the form of array and send it back to the jQuery.
Now the problem is I want to redirect the users to the new page with the values in the array. How can I do that?
Here is my jQuery code:
$.ajax({
type:'POST',
url:baseurl,
data:data1,
success: function (response){
if (response != false)
{
window.location = index.php?u= "+response;
}
}
})
Can I send those values via post method and how do I get those values in index.php page?
EDIT-
Perhaps, its better if you change the approach. what you want is a data array in the page in which you get redirect after ajax complete.
so- better use php session.
Your controller-
class myclass extends CI_Controller {
function myfunction()
{
$data=array(
// set your data array here
);
$this->session->set_userdata($data);
}
}
Now when ajax runs this function gets executed and data array is stored in session.
$.ajax({
type:'POST',
url:'<?php echo site_url() ?>myclass/myfunction',
data:data1,
success: function (response){
if (response != false)
{
window.location = '<?php echo site_url() ?>newcontroller/newfunction';
}
}
})
now, retrieve it in your target view.
print_r($this->session->all_userdata());
/////////////////////////////////////////////////////////////////////
EDIT ENDS
For what you are asking, you cant acheive it directly, but that does'nt means it cant be done.
You can acheive it by this-
var url = 'http://example.com/vote/';
var form = $('<form action="' + url + '" method="post">' +
'<input type="text" name="api_url" value="' + Response + '" />' +
'</form>');
$('body').append(form);
$(form).submit();
Now , on index.php, use $_POST to retrive the value posted by this form.
You should use absolute URL and put in between quotes :
window.location = "http://domain.com/index.php?u=" + response[0];

Ajax call and returning result

I don't know what i did wrong in the ajax call. I want to return the data back to my script and work with it but its not returning result. Here are some things i will like to clarify as well as i am new to ajax programming. if the ajax call is successful and it returns result to the script. Where in the script will the result be. Will i have to create an array that holds the result or ...
Here is the html
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" id="reserveform">
<div id="response"></div>
<div>
<label>Name</label><input type="text" name="name" id="nameid">
</div>
<div>
<label>Phone Number</label><input type="text" name="phone" id="phoneid">
</div>
<div>
<button type="submit" class="btn" id="btnsubmit">Submit</button>
</div>
</form>
<div id="success"></div>
//my script
$('#btnsubmit').click(function(e){
e.preventDefault();
var nameid = $('#nameid').val();
var phoneid = $('#phoneid').val();
var validate_msg = '';
if (nameid == ''){
validate_msg = '<p> Name is Required. </p>';
}
if (phoneid == '' || ($.isNumeric(phoneid) == false)){
validate_msg += '<p> Phone field is either empty or non numeric. </p>';
}
if (validate_msg != ''){
$('#response').addClass('error').html('<strong>Please correct the errors below </strong>' + validate_msg);
} else {
var formData = $('form #reserveForm').serialize();
submitForm(formData);
}
});
function submitForm(formData){
$.ajax({
type: 'POST',
url: 'reservation.php',
data:formData,
dataType:'json',
success: function(data){
$("#success").html(data);
},
error: function(XMLHttpResponse, textStatus, errorThrown){
$('#success').removeClass().addClass('error').html('<p>There was an ' + errorThrown + ' due to ' + textStatus + 'condition');
}
});
}
If you are trying ajax form submission and need to populate the result in the success div without refresh, you need return false
Don't use
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" id="reserveform">
Here don't need the action in form, try like
<form id="reserveform" onsubmit="return submitForm();">
In function use form serialize so all input elements value in form will available
function submitForm(){
var formData = $("#reserveform").serialize();
$.ajax({
type: 'POST',
url: 'reservation.php',
data:formData,
dataType:'json',
success: function(data){
$("#success").html(data);
},
error: function(XMLHttpResponse, textStatus, errorThrown){
$('#success').removeClass().addClass('error').html('<p>There was an ' + errorThrown + ' due to ' + textStatus + 'condition');
}
});
return false; // use this otherwise the form will be submitted and results an entire page refresh
}
please try this
you have to put the btnsubmit click event inside onload or document ready
$(document).ready(function()
{
$('#btnsubmit').click(function(e){
e.preventDefault();
var nameid = $('#nameid').val();
var phoneid = $('#phoneid').val();
var validate_msg = '';
if (nameid == ''){
validate_msg = '<p> Name is Required. </p>';
}
if (phoneid == '' || ($.isNumeric(phoneid) == false)){
validate_msg += '<p> Phone field is either empty or non numeric. </p>';
}
if (validate_msg != ''){
$('#response').addClass('error').html('<strong>Please correct the errors below </strong>' + validate_msg);
} else {
var formData = $('form #reserveForm').serialize();
submitForm(formData);
}
});
}
);
You cant use like this $("#success").html(data); because data is in json format. here, the data is an object. You need to parse it and assign to tags.
I see you configured the form to submit to the same document that you are in already. This is fine, we do this all the time.
However, you are also stopping the form from submitting and then using AJAX to submit the values. You specify reservation.php as your ajax processor. Is this the same PHP page you are on already? If so, then I know what the problem is: you can't do that.
By design, AJAX must use an external PHP file to process the AJAX. If you try to do this inside the same document, the AJAX will only echo back the full HTML of the document itself.
Short answer: use an external PHP file. This is by design.
See this other answer for more information about exactly this issue.
See these other posts for further info about AJAX and getting info into the PHP processing script, and returning info back from the PHP processing script:
A simple example
More complicated example
Populate dropdown 2 based on selection in dropdown 1

Easiest Way To Make A Form Submit Without Refresh

I have been trying to create a simple calculator. Using PHP I managed to get the values from input fields and jump menus from the POST, but of course the form refreshes upon submit.
Using Javascript i tried using
function changeText(){
document.getElementById('result').innerHTML = '<?php echo "$result";?>'
but this would keep giving an answer of "0" after clicking the button because it could not get values from POST as the form had not been submitted.
So I am trying to work out either the Easiest Way to do it via ajax or something similar
or to get the selected values on the jump menu's with JavaScript.
I have read some of the ajax examples online but they are quite confusing (not familiar with the language)
Use jQuery + JSON combination to submit a form something like this:
test.php:
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="jsFile.js"></script>
<form action='_test.php' method='post' class='ajaxform'>
<input type='text' name='txt' value='Test Text'>
<input type='submit' value='submit'>
</form>
<div id='testDiv'>Result comes here..</div>
_test.php:
<?php
$arr = array( 'testDiv' => $_POST['txt'] );
echo json_encode( $arr );
?>
jsFile.js
jQuery(document).ready(function(){
jQuery('.ajaxform').submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
dataType: 'json',
data : $(this).serialize(),
success : function( data ) {
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
return false;
});
});
The best way to do this is with Ajax and jQuery
after you have include your jQuery library in your head, use something like the following
$('#someForm').submit(function(){
var form = $(this);
var serialized = form.serialize();
$.post('ajax/register.php',{payload:serialized},function(response){
//response is the result from the server.
if(response)
{
//Place the response after the form and remove the form.
form.after(response).remove();
}
});
//Return false to prevent the page from changing.
return false;
});
Your php would be like so.
<?php
if($_POST)
{
/*
Process data...
*/
if($registration_ok)
{
echo '<div class="success">Thankyou</a>';
die();
}
}
?>
I use a new window. On saving I open a new window which handles the saving and closes onload.
window.open('save.php?value=' + document.editor.edit1.value, 'Saving...','status,width=200,height=200');
The php file would contain a bodytag with onload="window.close();" and before that, the PHP script to save the contents of my editor.
Its probably not very secure, but its simple as you requested. The editor gets to keep its undo-information etc.

Categories