"Continue" a PHP redirect with AJAX? - javascript

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.

Related

Pass javascript string variable to another page and get the variable in PHP with AJAX

I basically don't seem to understand sending a variable to another page.
I've tried PHP sessions, javascript cookies and ajax POST and GET.
I'm trying to send the innerHTML of a div, with the data created by a jQuery call,
a variable called savedartists. It displays correctly in the console.log on the sending page but the $_POST['savedArtists']
is undefined in the receiving page. I have spent hours looking at different posts on this site but I haven't been able to get it to work.
Any help is appreciated.
<input class="et_pb_button et_pb_button_0 et_pb_bg_layout_light" onClick="savequote();" type="button" id="savedchoices" value="Commander la prestation" >
<script>
function savequote() {
var savedartists = document.getElementById('selectedList').innerHTML;
console.log(savedartists);
$.ajax({
type: "POST",
url: 'example.com/artiste/mise-en-relation/',
data: { savedArtists : savedartists },
success: function(data) {
console.log("success!");
location.href = "example.com/artiste/mise-en-relation/";
}
});
}
</script>
On the receiving page (example.com/artiste/mise-en-relation/)
<?php
if(isset($_POST['savedArtists']))
{
$uid = $_POST['savedArtists'];
echo $uid;
} else {
echo 'zit!';
}
?>
Thanks for your time
Capturing as an answer for future readers...
Fundamentally what's happening here is that two requests are being made to the target page. The first one is the AJAX request:
$.ajax({
type: "POST",
url: 'example.com/artiste/mise-en-relation/',
data: { savedArtists : savedartists },
success: function(data) {
//...
}
});
This is a POST request which contains the data you expect, and works just fine. However, the result of this request is being ignored. That result is available in the success callback, but the code doesn't do anything with it:
console.log("success!");
location.href = "example.com/artiste/mise-en-relation/";
Instead, what the code is doing is performing a redirect. This creates a second request to that same page (though it's essentially irrelevant that it's the same page). This is a GET request and contains no data to send to the server.
At its simplest, you should either use AJAX or redirect the user. Currently you're mixing both.
I want to redirect to the other page.
In that case AJAX is the wrong tool for the job. You may not even need JavaScript at all, unless you want to modify the elements/values of a form before submitting that form. But if all you want is to POST data to another page while directing the user to that page, a plain old HTML form does exactly that. For example:
<form method="POST" action="example.com/artiste/mise-en-relation/">
<input type="text" name="savedArtists">
<button type="submit">Submit</button>
</form>
In this case whatever value the user enters into the <input> will be included in the POST request to example.com/artiste/mise-en-relation/ when the user submits the form.

Ajax call redirects to php file instead of calling another php file

so on submit of my form class .login this triggers an ajax call to login.php Inside of login.php there is a call to welcome.php to ensure that the encrypted password matches that in the database and that the user name entered exists in the database. It would also be helpful to mention my ajax call is succeeding in it's attempts to run, but no redirection to my welcome.php occurs. So, my question to you all, is am I going about this in the correct manor?
$('.login').on('submit', function(){
// serialize the form
var formData = $(this).serialize();
$.ajax({
type : 'POST',
url : 'login.php',
data : formData,
success: function() {
alert("Success");
},
error: function(xhr) {
alert("fail");
}
})
.done(function (data) {
})
.fail(function (error) {
console.log(data);
});
return false;
});
<html>
<body>
<?php
require 'connect.php';
if((isset($_POST['user-login']) && !empty($_POST['user-login']))||
(isset($_POST['pass-login']) && !empty($_POST['pass-login']))){
$sth = $dbh->prepare('SELECT name FROM test_table WHERE name=?;');
$passLogin = $_POST['pass-login'];
$nameLogin = $_POST['user-login'];
$sth->execute(Array($nameLogin));
if(password_verify($passLogin, $hashed_password) && $sth->rowCount() > 0) {
header("Location:welcome.php");
exit;
}
}
else{
echo 'error';
}
?>
</body>
</html>
*****************************************************************
<html>
<body>
<?php
echo 'welcome';
?>
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript">
<form class = "login">
<label for="user-login">Username</label>
<input id="user-login" name="user-login"></br>
<label for="pass-login">Password</label>
<input id="pass-login" name="pass-login"></br>
<input type="submit" name= "submit" value="submit" id = "submit">
<a id = "register-a">Register Now</a>
</form>
You will need to redirect your page using javascript. An Ajax request cannot redirect the users browser from server side. I recommend if your login is successful, pass back a success flag for your ajax success() function to handle then have THAT do the redirect using window.location.href.
Just a heads up in case you weren't aware, your script will always return successful. Even if you echo 'error';. You'd need to actually form a failing HTTP status code for the error function to execute, or alternatively have an error in your code!
The point of Ajax is to make an HTTP request without leaving the current page. The browser doesn't appear to redirect because the results are returned to the Ajax handler which does nothing with them (your done function is empty).
Your goal appears to be to make an HTTP request and then display the Welcome page.
You should not use Ajax. Just use a regular form submission.
If there is a problem with the submitted data (and most of the time there will not be, so it isn't worth applying Ajax for that case) then redisplay the form.
This is possible, however you are never reaching the redirect call because
$hashed_password in the if statement is not defined.
This will throw an error message but you will need to use a tool like chrome inspector > network > login.php to see the response.
Hope this helps debug in the future :)

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.

How to execute a php file into jquery without post and get method?

I'm trying to program a custom contact content manager in HTML/CSS with PHP/mySQL/Jquery to make it dynamic.
I have my login form which send the $_REQUEST to my connection.php, when the auth is correct, I return json to my Jquery and when it is good, I use window.location.replace to redirect the user to the control panel.
When I'm on the index.php of the control panel, I want to check if the user's session_id is into my sql database and if it exceeded the expiration time.
I have my functions which check this and return the good value but I want to execute it and send the result to my jquery without using GET or POST method.
If I remember, you have
$.ajax({
type: "POST", //or GET method
dataType: "json",
url: $(this).attr('action'),
data: $(this).serialize(),
success: function({
}),
error: function({
})
});
But you must specify the element "data" no? can I use it without data and put "file.php" as url without POST or GET method?
I want to get into my success method the result of my php functions :
if the json return false, the user can access the page.
if the json return true, I will logout the user and redirect him to the login.php
I'm doing this system because I don't want anybody can access the control panel by writing the correct url or after 4 days.. I put an expiration time to one hour (for the moment) for anybody who login into the control panel and I check on all page that the expiration time isn't exceeded.
I saw that using 'window.location.replace' doesn't allow to return to the previous page.. has anyone a solution? I don't want to have an event to redirect the user, only redirect him to another url (my file.php) after a condition.
Currently, I use it to execute php without POST, GET method with $.ajax..
$(document).ready(function(){
$(function(){
var ticket = '<? echo $tickets; ?>';
console.log(ticket);
if ( ticket === '' )
$(".new_ticket h2").after('<p>Aucun nouveau ticket.</p>');
else
{
console.log('else');
$(".new_ticket h2").after('<p>Il y a un ticket.</p>');
}
});
});
I have a last question, when I write :
$(document).ready(function(){
$(function(){
}
Is it directly executed by jquery when the DOM is ready? can I write mutliple '$(function(){}' in a file ?
Thanks for the help!
What is the problem with using POST or GET? It works perfectly fine.
Here foobar.php returns a json object with status in it. Change it to whatever your script return.
$.post('foobar.php', function(data) {
if( data.status === false) {
//All good
}else {
//Redirect
window.location.href = "http://newpagehere.com/file.php";
}
});
With window.location.href you will be able to use the back and forward buttons.
And yes, when using $(document).ready(function() { }); it runs when the DOM is ready.
http://api.jquery.com/ready/
One last thing is that I would not rely on Javascript here, I would do all checking with PHP instead when the user changes page. I would also handle the redirection there.

message box in PHP and navigation to another page

I am creating a login page in PHP. On entering wrong username/password I am showing a javascript alert box. I now want to navigate user back to login page on clicking "OK" button of alert box . Am using "header(location:url)", but then javascript code is not working.
Is there any other way to do this.
You can try this
echo "<script language='javascript' type='text/javascript'>alert('error');
</script>";
echo "<meta http-equiv='refresh' content='1; URL=login.php'>";
For JS redirect, try;
window.location.href="http://url";
Hope this helps :)
Put this code in the login error page ..
<script>
alert('Wrong Username/Password');
window.location = "http://www.google.com";
</script>
But if you are familiar with jquery i advice you to do the login process with ajax request and show the notifications in the same page instead of navigating back and forth.
If you need i can create a simple one in plnkr
For the js redirect, u can use
window.location.href='http://whereEver';
Note: Username/ password validations are server side. Assuming its an ajax call, after you get the validation results, instead of triggering an alert, have a div in the page itself where you can inject the server response. Alerting looks unprofessional.
Better approach would be something like
HTML
<div class="response"></div>
CSS
.response {
display:none;
}
.error {
color: red; // find a better color
}
PHP
On validation failure, have a variable, lets call it status and make it false.
The validation response can be something like,
$response = ['status' => false, 'message' => 'Username / password mismatch'];
Then send back the results
die(json_encode($response));
Note: If you are using PHP < 5.4, use
$response = array('status' => false, 'message' => 'Username / password mismatch');
JS
$.ajax({
url: 'url-to-post',
type: 'POST',
data: $('form[name="your-form-name"]').serialize(),
dataType: 'json',
success: function(data) {
if (!data.status) {
// inject into response
$('.response').addClass('error').html(data.message).show();
}
else
{
// redirect them to home page, i assume
window.location.href = '/home';
}
}
});

Categories