How to send data to the server via Ajax? - javascript

The registration form must be Ajax , to send data to the server via Ajax . When you click the submit appears a spinning gear . If the registration was successful then a message " You have successfully registered " If not occur with the error message " Invalid Email Address " or " username already exists " , etc.
We include the jQuery library page
JQuery add an event that no longer do submit the form
Added an event with jQuery , when making submit to execute ajax
Depending on the message came to Ajax , whether to show success or failure

This is all greatly simplified but on the javascript side, you could do this:
var params = {"email": $("input#email")
$.post(yourserver.php, params, validate, "json")
function validate(response) {
if (response.success) {
console.log("Allgood")
} else {
console.log(response.message)
}
}
and on the php server side, your server.php could look like this:
<?
if ( $_REQUEST["email"] ) {
$response = array("success" => true)
} else {
$response = array("success" => false, "message" => "Missing email");
}
echo json_encode($response);
?>

function success(answer) {
$(".loader").hide(); // Hide loader element
// Back-end side must return 3 numbers, where is
// 1 - success
// 2 - invalid email
// 3 - username already exists
if (answer === 1) { // if returned code "1" then output message of success
console.log("You have successfully registered");
} else if (answer === 2) { // if returned code "2" then output message of invalid email
console.log("Invalid Email Address");
} else if (answer === 3) { // if returned code "3" then output message of username already exists
console.log("Username already exists");
}
function loading() {
$(".loader").show(); // Show loader element
}
$("#submit").on("submit", function() {
$.ajax({
url: ("/handler"), // url address of your handler
type: "POST",
data: ({
email: $("input#email"),
login: $("input#login"),
password: $("input#password")})
beforeSend: loading, // should call loading() without arguments
success: success, // should call success(answer) where answer is result which returned your server
});
});

Related

How to redirect url after login successful via Ajax call in php?

I want to know that how to redirect url after login successful via Ajax call in php? Kindly check my code what I am doing wrong.
Below is the registration.php file on url http://localhost:8080//myproject/adminseller/registration.php:
<script>
function createLogin () {
//alert("Hello! I am an alert box!!");
var data = {
'email' : jQuery('#email').val(),
'password' : jQuery('#password').val(),
}; // data obect End
//Ajax call Start Here
jQuery.ajax({
url : '/myproject/adminseller/login.php',
method : 'POST',
data : data,
success : function(data){
//alert(data); // For checking Code in alert
if (data != 'passed') { // passed is else statement in
check_address.php when no errors are showing
jQuery('#modal_errors_1').html(data);
}
if (data == 'passed') {
//alert('passed!');
//clear the errors if any
jQuery('#modal_errors_1').html("");
location.reload();
}
},
error : function (){alert("Something went wrong.");},
});
}
</script>
Below is the Login.php File
<?php
if (isset($_POST['email'])) {
$email = sanitize($_POST['email']);
}
if (isset($_POST['password'])) {
$password = sanitize($_POST['password']);
}
// echo $email; // Output x2a0889#gmail.com
// echo $password; // 123456
// Email and password matched and no erros so I am removing validations code from here, So else condition will execute here
// Check for Errors
if (!empty($errors)) {
echo display_errors($errors);
}else{
// Assume here login is successful
echo 'passed';
**// Here is the problem via Ajax Call url is not redirecting after login successful, and always getting url is: http://localhost:8080//myproject/adminseller/registration.php **
header('Location:index.php');
}
?>
My problem is that after successful login the url is not changing it still
http://localhost:8080//myproject/adminseller/registration.php
And I want to redirect my page http://localhost:8080//myproject/adminseller/index.php
After successful login.
Any idea or suggestion would be welcome.
You need to use window.location.href not location.reload();
<script>
function createLogin () {
//alert("Hello! I am an alert box!!");
var data = {
'email' : jQuery('#email').val(),
'password' : jQuery('#password').val(),
}; // data obect End
//Ajax call Start Here
jQuery.ajax({
url : '/myproject/adminseller/login.php',
method : 'POST',
data : data,
success : function(data){
//alert(data); // For checking Code in alert
if (data != 'passed') { // passed is else statement in
check_address.php when no errors are showing
jQuery('#modal_errors_1').html(data);
}
if (data == 'passed') {
//alert('passed!');
//clear the errors if any
jQuery('#modal_errors_1').html("");
window.location.href = "http://localhost:8080//myproject/adminseller/index.php";
}
},
error : function (){alert("Something went wrong.");},
});
}
</script>
Below is the Login.php File
<?php
if (isset($_POST['email'])) {
$email = sanitize($_POST['email']);
}
if (isset($_POST['password'])) {
$password = sanitize($_POST['password']);
}
// echo $email; // Output x2a0889#gmail.com
// echo $password; // 123456
// Email and password matched and no erros so I am removing validations code from here, So else condition will execute here
// Check for Errors
if (!empty($errors)) {
echo display_errors($errors);
}else{
// Assume here login is successful
echo 'passed';
**// Here is the problem via Ajax Call url is not redirecting after login successful, and always getting url is: http://localhost:8080//myproject/adminseller/registration.php **
header('Location:index.php');
}
?>
You are currently redirecting the AJAX request.
You cannot redirect from the PHP side on a successful AJAX request.
You can catch the returned value from Javascript however and redirect from there.
Rather than calling the header location within your PHP script, put this within the if statement checking if the response was passd
window.location.href = 'index.php';
This will cause the browser to go to index.php.
You are redirecting in Ajax call, which should not be the case. Please remove this line from PHP code:
**// Here is the problem via Ajax Call url is not redirecting after login successful, and always getting url is:
http://localhost:8080//myproject/adminseller/registration.php **
header('Location:index.php');
And then replace your following JS code:n.
//clear the errors if any jQuery('#modal_errors_1').html("");
location.reload();
With Following code:
//clear the errors if any jQuery('#modal_errors_1').html("");
window.location.href = 'index.php';

jQuery won't reload this div or recognise it's new PHP $_SESSION value

I am using Ajax to submit a form using a nonce stored as a PHP session which, as the name suggests, unsets itself and generates a new nonce every time it is used successfully. This works perfectly the first time the Ajax is run.
If I view the source on the page after running it, the new nonce is being updated correctly in the actual code, but for some reason jQuery refuses to read the new value from the #nonce div or update the display on the page with the new $_SESSION value.
The div holding the nonce and the submit button (index.php)
echo '<input type="text" id="nonce" value="'.$_SESSION['nonce'].'">';
echo '<div id="form-test-ajax">
<input type="submit" name="submit" value="submit" id="btn">
</div>';
The jQuery functions in external file (functions.js)
$(document).ready(function() {
$('#btn').click(function() {
$.ajax({
url: 'adminapi.php',
dataType: 'json',
method: 'post',
cache: false,
data : {
"action": "testAction",
"nonce": $('#nonce').val()
},
success: function(data) {
reloadNonce();
},
error : function(xhr, status) {
alert(xhr.status);
console.log("something went wrong");
},
timeout: 30000,
});
});
function reloadNonce() {
$("#nonce").load(location.href + " #nonce");
}
});
The Ajax handler (adminapi.php)
require_once 'inc/globals.php';
header("Access-Control-Allow-Methods:POST");
header("Access-Control-Allow-Headers:Content-Type");
header("Access-Control-Allow-Credentials:true");
header("Content-Type:application/json");
// Check if the request is an AJAX request
function isAjax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
if (isAjax()) {
if (isset($_POST["action"]) && !empty($_POST["action"]) && isset($_POST["nonce"]) && !empty($_POST["nonce"])) {
$action = strip_tags($_POST["action"]);
$nonce = strip_tags($_POST["nonce"]);
// Validate nonce
$securityCheck = validateNonce($nonce);
// Nonce checked out
if ($securityCheck) {
admin_response(200, "Success");
exit();
} else {
// Invalid nonce, failed
admin_response(200, "Error : Security token was incorrect");
exit();
}
}
}
The other relevant PHP functions (globals.php)
// Generate nonce
function generateNonce()
{
$_SESSION['nonce'] = bin2hex(openssl_random_pseudo_bytes(16));
return;
}
// Validate nonce
function validateNonce($nonce)
{
if ($nonce == $_SESSION['nonce']) {
unset($_SESSION['nonce']);
generateNonce();
sessionTimeOut();
return true;
} else {
return false;
}
}
// Set session expiry
function sessionTimeOut()
{
$_SESSION['start'] = time();
$_SESSION['expire'] = $_SESSION['start'] + (15 * 60);
}
// Deliver admin function response
function admin_response($status, $status_message)
{
header("HTTP/1.1 $status $status_message");
$response['status'] = $status;
$response['response'] = $status_message;
$json_response = json_encode($response);
echo $json_response;
}
I've obviously left off chunks of irrelevant code PHP wise, session_start(); etc as the PHP side of this is running perfectly. It's only the jQuery I'm having an issue with.
The JQuery load() method internally uses the innerHTML function to populate the matched element with the ajax response. So I would say it's not appropriate for your use-case, as you need to set the value of an input field, instead of update the html contents of a div. I'd check out the JQuery docs for more info: http://api.jquery.com/load/
Just in case anybody else runs into a similar problem the answer was to return the new nonce in the ajax success response and then set the value to the nonce id.
Works now!
The jQuery
success: function(data) {
$("#nonce").val(data.nonce);
reloadNonce();
...
The PHP
admin_response(200, "Success", $_SESSION['nonce']);
...
and..
function admin_response($status, $status_message, $nonce)
{
header("HTTP/1.1 $status $status_message");
$response['status'] = $status;
$response['response'] = $status_message;
$response['nonce'] = $nonce;
$json_response = json_encode($response);
echo $json_response;
}

Ajax event only working once

when i enter the wrong details and run it. it pops up with the error message, but if i then enter the correct details and click run it again. the sign in button changes to "Connecting..." as it should but then nothing else happens
$(document).ready(function() {
var width = ( $(".main").width() - 5);
if (width < 300) {
$(".logo-img").css({"width":width});
};
$("#error").hide();
$(function() {
$('#login').on('click', function(e){
e.preventDefault();
var token = $('#token').val();
var username = $('#username').val();
var password = $('#password').val();
var remember = $('#remember:checked').val();
$.ajax({
url: 'core/functions/ajaxLogin.php',
method: 'POST',
data: { 'username' : username,
'password' : password,
'remember' : remember,
'token' : token },
dataType: 'html',
cache: false,
beforeSend: function() { $('#login').val('Connecting...') },
success: function( data ) {
if (data == 'success') {
setTimeout( "window.location.href='backorderbook';", 500 );
} else if( data == 'userorpass' ) {
$('#error').fadeIn();
$('#error_message')
.html('username or password were entered incorrectly');
$('#error').delay(3500).fadeOut();
$('#login').val('Sign In');
};
}
});
});
});
});
Reason behind working once.
when your ajax fired, first thing to do is show connecting.. then when you get response which is data your statement says
if data == success //redirects
elseif data == userpass //show you have invalid username/password and clear html
So what if your data is not succes / userpass
it will just run your ajax beforeSend() and not will remove connecting that seems to you running once.
I recommend that your data should be an object and check if there's an error with the message on it , in short have it on your backend and just jquery show that message
There is a token generated when the login page is loaded and sent with the Ajax. But my PHP token system doesn't like the same token being sent over and over and blocks the request.
run your function with Fiddler .. and/or add the error parameter to your ajax... odds are your web request isn't a success.

Using $.post to authenticate user to return custom error / success message

I am having this jQuery to authenticate users into site, how can I make two actions for success/error returned by login.php? Is it possible to refresh the page on success (for example) and post error message if the login info was not successful in login.php. I hope my question is clear. Here is the code. Right now it just paste the data output from login.php and I do not know how to seperate success/error returned server side.
$("#form-login").submit(function(event) {
event.preventDefault();
var $form = $( this ),
log = $form.find( 'input[name="log"]' ).val(),
pwd = $form.find( 'input[name="pwd"]' ).val(),
rememberme = $form.find( 'input[name="rememberme"]' ).val();
$.post( '/ajax/login.php', { log: log, pwd: pwd, rememberme: rememberme },
function(data) {
$(".form-login-status").html(data);
}
);
});
In your server side script, return the status as well as the message, like this:
$result = array();
if (login_is_successful()) {
$result['status'] = true;
$result['message'] = "Logged in";
} else {
$result['status'] = false;
$result['message'] = 'Incorrect password';
}
echo json_encode($result);
This gives you the flexibility to send any response message from the server side without needing to handle it specially in your client side code. Tomorrow, if you want to send messages 'Incorrect Username' and 'Incorrect Password' separately, you can do so without any change to your JS as long as $result['status'] remains false.
Then in the success handler of your $.post, do this:
success : function(resp) {
if (resp.status) {
//user logged in
//refresh page
window.location.reload();
} else {
//failed authentication
alert(resp.message);
}
}
Make sure you set dataType: 'json'
Important Note:
If authentication fails, the erorr handler in your $.post WILL NOT be called, therefore you have to check for failed authentication in your success handler.
The error handler is only called when there is an error in making the POST request.
Sure, it's in the documentation:
$.post("example.php", {}, function() {
alert("success");
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
In your 'success' handler, you'll need to process a flag returned by the requested URI that states whether or not the credentials authenticated the user or not. You'll want to branch your logic based on that logic.

Page redirect with successful Ajax request

I have a form that uses Ajax for client-side verification. The end of the form is the following:
$.ajax({
url: 'mail3.php',
type: 'POST',
data: 'contactName=' + name + '&contactEmail=' + email + '&spam=' + spam,
success: function(result) {
//console.log(result);
$('#results,#errors').remove();
$('#contactWrapper').append('<p id="results">' + result + '</p>');
$('#loading').fadeOut(500, function() {
$(this).remove();
});
}
});
EDIT: this is my mail3.php file dealing with errors:
$errors=null;
if ( ($name == "Name") ) {
$errors = $nameError; // no name entered
}
if ( ($email == "E-mail address") ) {
$errors .= $emailError; // no email address entered
}
if ( !(preg_match($match,$email)) ) {
$errors .= $invalidEmailError; // checks validity of email
}
if ( $spam != "10" ) {
$errors .= $spamError; // spam error
}
if ( !($errors) ) {
mail ($to, $subject, $message, $headers);
//header ("Location: thankyou.html");
echo "Your message was successfully sent!";
//instead of echoing this message, I want a page redirect to thankyou.html
} else {
echo "<p id='errors'>";
echo $errors;
echo "</p>";
}
I was wondering if it's possible to redirect the user to a Thank You page if the ajax request is successful and no errors are present. Is this possible?
Thanks!
Amit
Sure. Just put something at the the end of your success function like:
if(result === "no_errors") location.href = "http://www.example.com/ThankYou.html"
where your server returns the response no_errors when there are no errors present.
Just do some error checking, and if everything passes then set window.location to redirect the user to a different page.
$.ajax({
url: 'mail3.php',
type: 'POST',
data: 'contactName=' + name + '&contactEmail=' + email + '&spam=' + spam,
success: function(result) {
//console.log(result);
$('#results,#errors').remove();
$('#contactWrapper').append('<p id="results">' + result + '</p>');
$('#loading').fadeOut(500, function() {
$(this).remove();
});
if ( /*no errors*/ ) {
window.location='thank-you.html'
}
}
});
You can just redirect in your success handler, like this:
window.location.href = "thankyou.php";
Or since you're displaying results, wait a few seconds, for example this would wait 2 seconds:
setTimeout(function() {
window.location.href = "thankyou.php";
}, 2000);
$.ajax({
url: 'mail3.php',
type: 'POST',
data: 'contactName=' + name + '&contactEmail=' + email + '&spam=' + spam,
success: function(result) {
//console.log(result);
$('#results,#errors').remove();
$('#contactWrapper').append('<p id="results">' + result + '</p>');
$('#loading').fadeOut(500, function() {
$(this).remove();
});
if(result === "no_errors") location.href = "http://www.example.com/ThankYou.html"
}
});
In your mail3.php file you should trap errors in a try {} catch {}
try {
/*code here for email*/
} catch (Exception $e) {
header('HTTP/1.1 500 Internal Server Error');
}
Then in your success call you wont have to worry about your errors, because it will never return as a success.
and you can use: window.location.href = "thankyou.php"; inside your success function like Nick stated.
I posted the exact situation on a different thread. Re-post.
Excuse me, This is not an answer to the question posted above.
But brings an interesting topic --- WHEN to use AJAX and when NOT to use AJAX. In this case it's good not to use AJAX.
Let's take a simple example of login and password. If the login and/or password does not match it WOULD be nice to use AJAX to report back a simple message saying "Login Incorrect". But if the login and password IS correct, why would I have to callback an AJAX function to redirect to the user page?
In a case like, this I think it would be just nice to use a simple Form SUBMIT. And if the login fails, redirect to Relogin.php which looks same as the Login.php with a GET message in the url like Relogin.php?error=InvalidLogin... something like that...
Just my 2 cents. :)
I think you can do that with:
window.location = "your_url";
I suppose you could attack this in two ways;
1) insert window.location = 'http://www.yourdomain.com into the success function.
2) Use a further ajax call an inject this into an element on your page, further info on which you can find in the jQuery docs at http://api.jquery.com/jQuery.get/
Another option is:
window.location.replace("your_url")

Categories