php browser back after post - php

I have php page where I used a form to submit messaage. It submits to itself :
action="<? php echo $_SERVER['PHP_SELF'];?>"
Then it sends email, and I have a javascript function that uses jnotify, to alert whether message is sent successfully or not. This function checks if php variable $sent=='yes' then notify about sucessful message else notify about error.
The problem is that when user sends message and goes to another page and comes back by using browsers back button, it is displaying notification. I want it to show notification once only and forget about notification when browsers back or refresh used.
What is the best solution for it?

Try something like this:
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (form_is_valid()) {
$_SESSION['form_success'] = true;
} else {
$_SESSION['form_success'] = false;
}
header('Location: ' . $_SERVER['PHP_SELF'];
exit;
} else if (isset($_SESSION['form_success'])) {
if ($_SESSION['form_success'])) {
// insert success javascript
} else {
// insert failure javascript
}
unset($_SESSION['form_success']);
}
// display_form
This should make it so they only see the success/failure message once, and if they use the back button at a later time, they will not receive a warning about re-submitting post data, and they also won't see a success/failure message twice. The only time that javascript should show is if they just submitted the form in the last request.

You can use ajax request to send your form.
$.ajax({
type: 'POST',
url: processor.php,
data: $('#form_id').serialize(),
success: function(data){
if(data==0){ alert('message sent'); }else{ alert('message not sent'); }
}
});

I think the Zend Helper Flash messenger might be what you're looking for.
"This means that the message will be available for retrieval on the next request, but unavailable on the request afterwards."
additional documentation

Related

Passing a $_SESSION failed when creating the $_SESSION within Ajax function

I have a simple registration form and the new comers will be registered with an ajax function. There I create a $_SESSION['is_logged'] when the registration is finished.
On var_dumb I get that the var is set. But when redirect on another page it is empty (I have included already the session_start() on the both pages...
I have read somewhere in the net that:
"Sessions are ONLY written on a page load/refresh".
Is this the case, or I have to look for some other issues within my code.
the ajax:
$.ajax({
url:"../controllers/register.php",
type:"POST",
data:res,
success: function(responce){
if (responce==1) {
$('#msg').addClass('msg-warning');
$("#form").css('display',"none");
$('#msg').append("<p>It seems that you have already submited the form. Click to "+
" <a href='login.php'>log-in</a> or to <a href='register.php'>register</a>.</p>");
}
else if (responce==2) {
$('#msg').addClass('msg-warning');
$("#form").css('display',"none");
$('#msg').append("<p>You have successfully created account. Click to "+
" <a href='start.php'>welcome</a> to start your .</p>");
$('.menu').append("<li><a href='logout.php'>Log out</a></li>")
}
else{
$('#msg').text(responce);
}
},
error: function(){
$('#msg').text("Opss, try again");
}
});
the register.php file:
if (isset($_SESSION['submited'])) {
echo 1;
exit;
}
include_once('../models/functions.php');
// Give the post parametters to another var
$arr=$_POST;
// function for uploading
$reg = registerMe($arr);
if ($reg === true) {
$_SESSION['submited']=1;
$_SESSION['is_logged']=1
echo(2);
}
else{
echo($reg);
}
exit;
The session_start(); is included in the header of the first page where from the ajax is started.And the second page - where the $_SESSION['is_logged'] is lost, again the session_start(); is part of dc_header(); function. start.php:
<?php
dc_header("Речник|Регистрация");
if (!isset($_SESSION['is_logged'])) {
#header("location: ../views/login.php");
var_dump($_SESSION);
}
?>
add
session_start();
to the top of register.php
You need to specify session_start, so your server who was commanded to execute "register.php" (either from ajax, direct call, browser scripts, cron job or whatever possible you-name-it) will handle the execution and the setting of $_SESSION variables in reference to the connected clients session. Server won't guess by itself that this is an "ajax call from an already session_start page". You need to specify that whatever is done in register.php is done in the current client's session.

PHP form validation alerts without redirecting page

Basically whats happening is I have a php form to send an email. There are several different validation steps all along the way, which all work great. What i'd like to do is have a javascript alert pop up if there is a validation error when the form is submitted. I have this working with the following php:
// Validate email
if(!filter_var($EmailFrom, FILTER_VALIDATE_EMAIL))
{
echo "<script language=javascript>alert('Please Use a Valid Email Address')</script>";
exit;
}
The alert pops up but the page redirects to domain.com/sendemail.php which leaves the user with a blank page. I'd really like to have the alerts pop up without reloading the page. How would I do this?
You can use ajax to accomplish this. But if you don't want to use ajax, instead doing an exit on error, you could redirect back to the form page along with a query string parameter.
header("Location: http://www.example.com/form.php?error=1");
And on your form page you could put the script withing php if. Something like
<?php if(isset($_GET['error']) && $_GET['error']==1): ?>
<script>
....
</script>
<?php endif; ?>
That would achieve what you are looking for. In fact you can perform multiple checks and set error based on your checks. But I would still suggest Ajax will give a better user experience.
Edit: Super easy solution, use jQuery form plugin : http://jquery.malsup.com/form/
I do something similar in some of my web apps, you might find it useful.
I do my validation server side and if I encounter an error I do this :
json_die(array(
'status' => 'error',
'message'=> 'Your error message'
));
and for success :
json_die(array(
'status' => 'success',
'message'=> 'Your success message'
));
The json_die is function is :
function json_die($array) {
header("content-type: application/json");
die(json_encode($array, true));
}
Then on the front end I do something like this:
$.post('/your_url', {
'your': vars
}, function (r) {
if(r.status == 'success') {
alert(r.message);
} else if (r.status == 'error') {
alert(r.message);
//handle error
} else {
alert('server exploded / no connection');
}
},'json');
This is a script I used in some forms I created to validate them fast. It's very simple and effective, I hope it helps you.
<script type="text/javascript">
function validate(){
emailfilter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
condition = 1;
mensaje = "Complete: ";
//Validate 1st input (Check if empty)
if (document.formname.forminput1.value.length==0){
condition = 0;
msg = msg + "-Input 1 is empty "
}
//Validate 1nd input (Check email)
if (!emailfilter.test(document.formname.forminput1.value)) {
condition = 0;
msg = msg + "-Input 1 has a invalid email adresss "
}
if (condition == 0){
alert(msg)
document.formname.forminput1.focus()
return 0;
}
//send
alert("Form sended.");
document.formname.submit();
}
</script>

No Ajax response even though PHP file set up correctly

I have a simple sign up mailing list form. It sends the user's email address to a store-address.php file. I use jQuery's ajax object to send a request to the php file and then receive a response.
The problem is I am not getting a response from the php file. I tried setting the cache to false in the request. I also tried send the information through the URL like so:
http://www.fifthtribe.com/inc/store-address.php?ajax=true&cache=false&email=test4%40gmail.com
When I do it that way it works and gives me a reponse. But when I do it through ajax it doesn't give me a response. This is from Firebug:
And here's snippets from my code:
HTML:
<div id="mlist">
<form id="mlist_form" method="POST" action="">
<input type="text" id="email" name="email" placeholder="Email" />
<input type="submit" id="submit_btn" value="Join" />
</form>
<div id="response"></div>
</div>
JQuery:
/* Add to mailing list */
$("#mlist_form").submit( function(e){
//$('#response').append('<div id="thanks-mce"><div id="mce-arrow"></div>Thanks for signing up!</div>');
var email = escape( $('#email').val() );
e.preventDefault();
data = {
"ajax" : "true",
"email" : email,
"cache" : "false"
}
$.ajax({
type: "POST",
url: 'inc/store-address.php',
data: data,
success: function( msg ){
// successfully signed up
$('#response').html( msg );
$('#email').val('');
},
error: function( err ){
// error while signing up
$('#response').html('Error: Is your email correct?');
}
});
return false;
});
PHP:
function storeAddress(){
// Validation
if(!$_GET['email']){ return "No email address provided"; }
if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*$/i", $_GET['email'])) {
return "Email address is invalid";
}
require_once('MCAPI.class.php');
// grab an API Key from http://admin.mailchimp.com/account/api/
$api = new MCAPI('xxxxxxxxxxxxxxxxxxxxxxxxxxxxx-us4');
// grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
// Click the "settings" link for the list - the Unique Id is at the bottom of that page.
$list_id = "xxxxxxxx";
if($api->listSubscribe($list_id, $_GET['email'], '') === true) {
// It worked!
return 'Success! Check your email to confirm sign up.';
}else{
// An error ocurred, return error message
return 'Error: ' . $api->errorMessage;
}
}
// If being called via ajax, autorun the function
if($_GET['ajax']){ echo storeAddress(); }
?>
You realize that your PHP script is using GET method but your jQuery code is using the POST method right?
If the information is being posted to PHP, PHP will need to use $_POST to retrieve it. This explains why the URL method using $_GET works but the jQuery POST doesn't.
Good luck!
It looks like you're using $_GET instead of $_POST. Try echoing out the contents of $_REQUEST to see what that holds.
Debug your script!
Place an alert in the success and error parts of your script and then you will know whether the AJAX is working.
If not, you can then work your way up the document and see where the problem is.
In addition, the error here is quite simple. You are using $_GET in PHP and you are POSTING your data using AJAX, this will not show an error. Although the PHP document will not process your request because it is not being fed any parameters.

Redirecting to a new page based on an AJAX call

I am using ajax with jQuery to make a request from a page on my site. Now if the login failed (or the call failed for a different reason), I return an error message and put it in a label. But if the call succeeds, I want to navigate to another page. My issue is that if the call succeeds, I end up with the text of the new page in my label.
Here's my Javascript:
$.post("chklogin.php", { username: username, password: password }, function(data) {
$('#msg').html(data);
});
And here's the PHP that it calls:
if(mysql_num_rows($result)==0) {
$msg="<h3>Enter valid Username and Password.</h3>";
echo $msg;
} else {
$row=mysql_fetch_assoc($result);
$_SESSION["userid"]=$row["pgmail"];
header("location:user.php");
}
Well this issue could have been clearer, and I would encourage you to check your spelling and code before you post again.
The issue is that you haven't sent the page to redirect, you have sent the page being called to redirect.
To fix this issue:
Firstly, get rid of the header redirect on your PHP code and replace with:
echo 'SUCCESS';
Secondly, change your AJAX code to the following:
$.post("chklogin.php", { username: username, password: password }, function(data) {
if(data=='SUCCESS'){
window.location.href = "user.php";
}else{
$('#msg').html(data);
}
});
This will make the page redirect, not the page called by AJAX.

jQuery to database - registration form with validation

I find this tutorial in 9lessons.com : http://www.9lessons.info/2011/01/gravity-registration-form-with-jquery.html
It's about a registration form with validation.
I want to send data to DB.
// Submit button action
$('#submit').click(function()
{
var email=$("#email").val();
var username=$("#username").val();
var password=$("#password").val();
if(ck_email.test(email) && ck_username.test(username) && ck_password.test(password) )
{
$("#form").show().html("<h1>Thank you!</h1>");
///// if OK
///// Show thanks
//// else
//// Error, try again
}
return false;
});
How can I do ?? I searched in internet in jQuery tutorial and I find much codes ...
This tutorial will walk you the entire process:
http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/
It implements jQuery.post and calls a PHP script that will allow you to process the data.
You will need to use Ajax to submit the data to a backend script (such as PHP) to do the actual database interaction. I'd recommend using POST:
http://api.jquery.com/jQuery.post/
you can use jquery post method
$.post("test.php", $("#testform").serialize());
or for more detail visit this link
jquery form post method
Finally I inserted data form to database... I have a problem.. I forgot to verify if email is available or not !
I added this lines from an other tutorial in email verification to test if email exist in DB or not.
First I send email to check_availability.php
if mail exist an error message appear else, the password fiel must appear ...
Like you see in picture, I verify the existence of an email adress and availibality and unavailability message appear but not correctly ...
$('#email').keyup(function()
{
var email=$(this).val();
if (!ck_email.test(email))
{
$(this).next().show().html("Enter valid email");
}
else
{
//$(this).next().hide();
//$("li").next("li.password").slideDown({duration: 'slow',easing: 'easeOutElastic'});
$.ajax
({
type: "POST",
url: "user_availability.php",
data: "email="+ email,
success: function(msg)
{
$("#status").ajaxComplete(function(event, request, settings)
{
if(msg == 'OK')
{
/*$("#email").removeClass('object_error'); // if necessary
$("#email").addClass("object_ok");
$(this).html(' <img align="absmiddle" src="accepted.png" /> ');*/
//////////////////
$(this).next().hide();
$("li").next("li.password").slideDown({duration: 'slow',easing: 'easeOutElastic'});
//////////////
}
else
{
$("#email").removeClass('object_ok'); // if necessary
$("#email").addClass("object_error");
$(this).html(msg);
}
});
}
});
}
});
The tow first comment lines are the default ines used to show the next field //$("li").next("li.password").slid ...
Like you see I add them in Ok test section ....

Categories