Ajax request and SESSION - javascript

I have a form that the users complete and then press "Submit" button to register.
I wanted to preview the data to the user before the form is submitted, so i used AJAX to do this. The procedure is as follows:
1) User clicks "submit" button (ex. registration.php)
2) JS script, prevents the default action (which is to submit it) and calls another PHP script via AJAX (registrationAJAX.php), that:
a) Performs some database changes
b) stores some variables in a $_SESSION array
$_SESSION['userID'] = $uID;
$_SESSION['userEmailAddress'] = $email;
$_SESSION['hash'] = $hash;
c) json_encodes the following array:
$results = array(
'result' => 'success',
'message' => 'registration was successful'
);
echo json_encode($results);
d) then exits
exit();
3) Back to JS script and on AJAX success, i check to see whether the result is "success" and then redirect the user to a script that sends an automated email for account verification:
$.ajax({
type: "POST",
url: "js/ajax/registrationAJAX.php",
data: {form data...},
cache: false,
success: function(output){
var outputJSON = $.parseJSON(output);
var status = outputJSON.result;
if(status == 'success')
{
location.href = "https://domain.com/verify.php";
}
}
});
The verify.php script MUST have access to the $_SESSION variables to be executed correctly.
//the code will only executed if the $_SESSION['hash'] is set:
if(isset($_SESSION['hash']))
{
//SEND EMAIL ACTIVATION EMAIL TO USER
//INFORM THE DATABASE THAT THE EMAIL IS SENT
}
Sometimes i see that some of my users don't receiver the activation email. This will happen if the verify.php script doesn't have the $_SESSION variables i stored during registrationAJAX.php and then fail (as shown at the code above).
Question:
1)Is there a possibility that the variables delay to get stored in the $_SESSION and the redirection to verify.php is performed with no $_SESSION variables?
2) Does the exit() command cause a problem?

You should consider move to OAuth authentication to avoid the issue with the cookies disabled:
http://www.sitepoint.com/creating-a-php-oauth-server/
Regards,

Related

Show alert from php action page after fetching the records from the database

I have been trying to show alert message from php action page after the form records are fetched from database. I have 2 php pages. In one.php I am making a ajax call to action page two.php. Till now I am able to make successful ajax call from one.php to two.php and I am able to receive all the parameters passed from one.php to two.php. But I would like to show an alert message in one.php after the records are fetched into the database in the file two.php.
two.php
$query = "SELECT status FROM dash_apparel_reprint WHERE piece_number='" . $piece_info[0] . "' ";
$result = mysql_query($query);
if(($row = mysql_fetch_array($result)) != false) {
$status = $row[0];
}
if($status == "New" || $status == "Out of Stock"){
echo('<script type="text/javascript">window.alert("fetching records done"); window.location.href="one.php"</script>');
exit();
}
I am using POST method for both one.php and two.php. referring to this Display alert box upon form submission
Any kind of advice or suggestion will definitely help me learn this concept
If you want to use an alert you need to set it in the success part of your ajax call.
See below:
$.ajax({ url: 'two.php',
data: {var1: var1value} //Pass your variables here
type: 'post',
success: function(output) { //This is where you receive the result from two.php
//Do whatever you want with the data stored in output
alert('It worked!'); //Alert whatever you need here
},
error: function() {
alert('That did not work...'); //Handle errors here
}
});
In the success or error functions you can update other DOM elements in your page as well, which may be more elegant than just an alert.

How to send form data to specific email?

I have an html form and I would like to achieve two things with it:
1) - When user clicks on "submit" the data is automatically sent to a specific email and 2) - the user is redirected to a "confirmation page". I do not want to use mailto function as it is pretty bad since its browser dependent. I would like to use a light script... Is it possible using js?
You cannot do this with JavaScript alone.
What you can do is use AJAX to send your form data to a server-side script which will send your email, then the AJAX success handler can redirect the page to some confirmation page.
Some hosts have email scripts installed, like CGI scripts, to handle sending email for you on the server side.
This is essentially the best you can do on the client side (using jQuery for ease):
var data = {
name: $("#form_name").val(),
email: $("#form_email").val(),
message: $("#msg_text").val()
};
$.ajax({
type: "POST",
url: "email.php",
data: data,
success: function(){
// Redirection on success
var url = "http://example.com/confirmation.html";
$(location).attr('href',url);
}
});
and the essential server-side script:
<?php
if($_POST){
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
// Input sanitation omitted
// Send the email
mail("my.email#gmail.com", "Message from {$name} - {$email}", $message);
}
No, it's not possible in pure JavaScript.

File being called by Ajax contains error

I have 2 pages, process page and form page.
So basically the form page consists of a lot of input text and once the user click the submit button, it runs the ajax call and call the process page. the process page requires user's credentials like id and password.
My ajax call basically success run, but the process page is not running. When there is no user logged in, the process page will output the undefined index message. In this case is the id or password, because basically there is no data passed(ID and Password) to the process page.
This is my ajax call function
function postTweet(){
$.ajax({
url : 'blablabla',
type : 'POST',
data : blablabla,
success: function() {
div1.append("Success!");
}})
.fail(function(data){
console.log(data);
});
}
So basically after the non-loggedin user click the submit button, the Success message will still be displayed out, eventhough basically there is no process running in the process page.
What I want is, if the process basically is not running, I should prompt out a proper message.
Can someone help me please?
Any help given is highly appreciated. Thanks
Your success function can handle arguments (look at ajax success here)
For example:
PHP File
<?php
echo json_encode(array('test' => "hello world")); // echo any array data
exit(); // Stop php from processing more, you only want the json encoded data to be echoed
?>
Javascript File
...
dataType: 'json', // This is needed to convert the echoed php data to a json object
success: function (response) { // "response" will be the converted json object
console.log(response);
},
...
The console.log(response); would look something like Object {test: "hello world"}
EDIT
In your case, you could do something like this:
<?php
if ( ! isset($username) ) {
echo json_encode(array('success' => FALSE, 'message' => "Username is incorrect."));
}
...
exit();
?>
To alert the above error message in javascript:
...
success: function (response) {
if (response.success) {
alert('success!');
} else {
alert(response.message);
}
},
...
There are 2 ways to handle this issue.
if form page contain login credential input then you can validate login credentials are filled or not in java script and then call ajax process.
you can validate login credentials in ajax file using isset() method and if login credentials are not validated then you can send a simple message to ajax calls about login failed.

"Continue" a PHP redirect with AJAX?

I have an HTML form that is processed via PHP, and it's a simple login script. This works fine, but I want to catch the error with AJAX. Basically, if the PHP function to check the login returns false, it should write that error onto the DOM via jQuery. However, if I catch the form submission with AJAX, it will stop the PHP file from doing the redirect. I want to stop the form from redirecting only if the PHP file returns false. Any help would be much appreciated. Here's some code to illustrate what I'm talking about:
controller_login.js
$(document).ready(function(){
$('form.loginSubmit').on('submit',function(){
var that = $(this),
url=that.attr('action'),
type=that.attr('method'),
data={};
that.find('[name]').each(function(index,value){
var that=$(this),
name=that.attr('name');
value=that.val();
data[name]=value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
errorHandle(response);
}
});
return false;
});
});
function errorHandle(error)
{
console.log(error);
}
This is the file that will eventually modify the DOM if there is a PHP error. For now, it just logs.
checkLogin.php
if($verifySqlRequest==1){
session_register("loginUsername");
session_register("loginPassword");
header("location:http://localhost/asd/dashboard.html");
echo "login success!";
}
else{
echo "Wrong user name or password...";
}
This is just a snippet of the login authentication, but essentially I want that last echo to be communicated to controller_login.js, but it should continue the redirect if the login is successfully authenticated. Any help would be much appreciated!, thanks!
The browser isn't going to respond to a 302 or 301 (redirect) from an Ajax call. You can still certainly respond with that code, but, you'll have to handle the redirect manually via script:
window.location.replace("http://localhost/asd/dashboard.html");
or you can do it like this
> echo '<script>window.location.replace("http://localhost/asd/dashboard.html")</script>';
and
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
$('#response_element').html(response);
}
The point of using Ajax is to avoid reloading the page. If the user is going to be redirected upon login you may as well just submit the form synchronously and let PHP display the error.
Just for the sake of argument, if you wanted to do an Ajax function and display a message returned from the server you would NOT do:
<?php
echo 'this is the message';
?>
You would do
<?php
$response = array('message' => 'this is my message');
return json_encode($response);
?>
However, you can't redirect AND return data.

Unable to return a value from jQuery.ajax success function

I want to use jQuery Validator to check against the server when a user is signing up for if their desired username is already taken. The PHP script untaken.php does this job, returning ok if the username is available, or taken if it is taken.
My entire source is below, however the line in question is this:
return data != "taken";
Currently the message "Username already taken" permanently appears. However if I change it to:
console.log( data != "taken" );
and type in the text box I see in the console true and false messages exactly when I expect them. That's how I know the design itself isn't to blame, it's just the fact that I can't return anything from the success clause in jQuery.ajax.
$.validator.addMethod("userCannotBeTaken", function(value, element){
var check;
check = $.ajax({
type: "GET",
url: "untaken.php",
data: ({ "user" : value }),
dataType: "text",
success: function(data){
return data != "taken"; //return false if taken or true if not, based on response
}
});
}, "Username already taken");
How can I return something from within jQuery.ajax?
Turns out I was overthinking the whole thing and it can be easily done with jQuery Validator's built-in remote method. Here's my code if it helps someone:
Rule in validator script:
remote: "untaken.php"
PHP:
<?php
//mysql info
[snip]
//connect to database
$sql = new mysqli($mysql_host, $mysql_user, $mysql_password, $mysql_database);
//Populate variable
$newun = $sql->real_escape_string( $_GET['newuser'] );
//Do the actual checks
$un_already_taken = $sql->query("
SELECT username FROM logins WHERE username = '$newun'
"); //check if UN already in DB
if($un_already_taken->num_rows > 0) //un taken already
print "false"; //tell jQuery to not submit form
else
print "true"; //tell jQuery all is good
As easy as printing "true" or "false". Note it uses GET (ie. URL paramaters) not POST, and the GET variable is the name of the field it is validating (in my case newuser)
To return data to the ajax function, you need to print or echo the result in your untaken.php page.
soemething like:
echo $result;exit;
Then Try to alert the data inside success function
and debug the result with
alert(data);return false;
The function you define for the success action is a callback.
When you make an ajax call, it is done asynchronously, (meaning the script continues executing while the browser connects to the server. You can't use return when dealing with callbacks because they are executed later, rather than immediately as a typical function.
This might make more sense: http://recurial.com/programming/understanding-callback-functions-in-javascript/
The success function should perform whatever actions that you want to happen after you get the data back to the server ie: alert the user that the username is taken.

Categories