Situation :
My web application is password protected.For each http request we make to server, it is being checked against session existence. If session has been expired then the user is forwarded to login page.
This goes fine for http requests. But if it is an AJAX request, then just like http request, if session has been expired, it is also forwarded to login page.
Problem :
if we are directly showing AJAX response in browser, then in place of our expected response will show the login page content in your browser.And if you would be fetching data of any expected format, then it would throw JavaScript error.
My Code :
<script>
function details() {
var xyz = document.getElementById("name").value;
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'name=' + xyz;
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "user.php",
data: dataString,
cache: false,
success: function(html) {
document.getElementById("content").innerHTML=html;
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
if (XMLHttpRequest.status === 401) {
location.href = 'index.php';
}
}
});
return false;
}
</script>
on Session time out when i call Ajax request through my code. It loads the login.php content into the current page instead of forwarded the user to login Page.
Guide me where i am doing something wrong.
Thanks.
If your are working with multiple ajax request, then you can use jquery ajaxComplete function.
This function run every time after ajax call but before the success or failure function attached to that ajax event.
eg for this code is :
jQuery("body").ajaxComplete(
function(event, request, options) {
if (request.responseText == "login_required") {
window.location.href = "login.php";
}
}
);
And on your server side, you just have to check if the request is an ajax request and if user is not logged in, just print "login_required" and stop the execution of code(exit the code).
User will redirect to login.php page
Related
I have built a custom registration form which creates a new WordPress user account and redirects the user to the /my-account/ area on completion. The issue I have is that I am not displaying any information on the front-end when the form is not submitted correctly i.e. the account creation process failed.
I am trying to log the AJAX response to console so I can see what I'm working with but it appears I'm not getting a response at all.
The code that I currently have in place:
<script>
jQuery('form[name="form-new-customer"]').on('submit', function() {
let form_data = jQuery(this).serializeArray();
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: form_data,
success: function(response) {
console.log(response);
window.location.replace('<?php echo get_site_url(); ?>/my-account/');
},
fail: function(err) {
console.log(err);
}
});
return false;
});
</script>
As you can see, I have a redirection for 'success' but this redirection also happens when the account user process fails. I'm assuming it's always a success because the AJAX request was carried out correctly and it's not able to know whether or not the PHP function ran or not?
I need to somehow get the User ID (if an account is created) and then check if it exists. This would determine if the function was successful or not. If not, then I can display a message to the end user?
I am using Laravel as a PHP framework and I have Jquery set up so it prompts the user if they want to confirm redirecting away from the page or not.
The problem is that if the user confirms the redirect away from the page, I need to somehow perform some database operations to set various statues to closed on my tables.
How is this possible?
My Jquery code prompting the user
<script type="text/javascript">
$(window).bind('beforeunload', function(){
return 'Are you sure you want to leave?';
});
Just make an Ajax request to inform the server that the user will be redirectd.
$(window).bind('beforeunload', function(e){
if ( confirm("Are you sure you want to leave?") ) {
e.preventDefault();
// make ajax request to inform the server
$.ajax({
type: "POST",
url: reqUrl,
data: reqBody,
dataType: "json",
success: function(data, textStatus) {
// handle things
}
});
// Redirect.
window.location.href = someURL;
}
});
I am sending an email in jQuery and PHP, i need to tell the page to submit if the ajax was successful and don't submit if not.
I have tried to place the return values in the success and error attributes, but that did not work, so i want to see if i could set the form to not send by returning false but if it was successful letting it submit the page for some server side work.
In the example below i have tried to set a variable and used a conditional to read it. I get an error message because the value does not seem to get passed globally, so when the conditional reads sendMe, it says it is undefined.
Is there a way to do this correctly?
$.ajax({
type: "POST",
url: "send.php",
data: data,
success: function(){
var sendMe = 'true';
},
error: function(){
alert('Error: Message could not be sent');
}
});
if (sendMe == 'true'){
//Submit the page...
}
else {
return false;
}
just create a sendMe() function, and call that function from success:
That should do the trick.
The reason your code does not work is because the javascript is not waiting for the ajax call to come back, right after the ajax call it evaluates sendMe which at that point is still false.
You could consider doing this call synchronously of course to prevent that, but I am not sure that is the right way to go. ( async : false is deprecated as of jQuery 1.8 )
When is your conditional
if(sendMe == 'true') ...
ever getting called?
make a little function like this:
function sendMe(){
// whatever your form's id is, put it in place of myForm
$("#myForm").submit();
return true;
}
and in your ajax success block call the function
Try using this setup:
var form = this;
$.ajax({
type: "POST",
url: "send.php",
data: data,
success: function(){
form.submit(); // submit form, bypassing jQuery events
},
error: function(){
alert('Error: Message could not be sent');
}
});
return false; // prevent submit
By returning false after the ajax request, we prevent the submit, then we directly submit the form bypassing all of jQuery's submit handlers using form.submit();
Set the form to go through a validator method on submit event:
<form onSubmit='return checkForm();'>
</form>
In this method - checkForm() - perform your ajax post normally. If the ajax post returns as 'success' proceed with the submit else use return false; to cancel submit and notify the user accordingly.
I use CodeIgniter for my backend and ExtJS 4.1 for the frontend. In a controller in CI I check if an users session is over and if so I perform
redirect('login');
However what actually happen is - I stop to get response from the server but my ExtJS is still working and I don't get the loginpage. How can I redirect from ExtJS when I see on the server side that session is over?
Thanks
Leron
var runner = new Ext.util.TaskRunner();
// poll some page every 10 seconds
var task = runner.start({
run: function() {
Ext.Ajax.request({
url: 'is_logged_out.php',
success: function(response){
var json = Ext.JSON.decode(response.responseText);
// is we are logged out then redirect somewhere
if (json.isLoggedOut) {
task.destroy();
location.href = json.redirectToPage;
}
}
})
},
interval: 10000
})
You also can add special logic to handle 403 errors (presumably if your ExtJs session has expire on the backend, but client still have page opened - next request should get back Not Authorized message).
Check out singleton class Ext.Ajax for how to subscribe to global Ajax events.
When an user's session is over, typically is done by the user himself by performing a certain behaviour: for example, the user push the logout button. Well, at that time, the client (ExtJS) should be forward an AJAX request to the server as follows:
Ext.Ajax.request ({
url: serverUrl + 'logout' ,
success: function (response) {
location.href = serverUrl + 'login';
} ,
failure: function (response) {
// Something here to handle the failure
}
});
When an user logout, that request is reached by the server: your CI app will over the session and response to the client with '200 OK HTTP/1.1' and the client provide to redirect the user to the login page.
Ciao.
Wilk
I have an jquery ajax request that calls a PHP script that will send an email. This email is happening from the admin, so a user must be authenticated in order to be able to do this. I've got two questions:
How can I lock this PHP file down from somebody being able to go directly to the path in the browser and keep submitting it?
How do I only run the file if the user is authenticated?
PHP:
$emailer = new GiftCardEmailer();
$emailer->SendGiftCardEmail($gift_card);
jQuery:
$(document).ready(function() {
var status = $('p#status');
status.hide();
$('#sendemail').click(function() {
$.ajax({
url: 'mail-handler.php',
beforeSend: function() {
status.fadeIn();
status.html('<img src="images/ajax-loader.gif" />');
},
success: function( data ) {
if (console && console.log){
console.log( 'Sample of data:', data.slice(0,100) );
}
status.html('Email Sent Successfully.');
setTimeout(function() {
status.fadeOut();
}, 4000);
}
});
});
});
One approach would be to check for a valid session at the head of the file containing the actual mail code. If no session exists then simply terminate the script.
Check out ajax and security, might be helpful.
I do all of mine with session_start() at the top of a php page and then check for my specific session variables for authentication.
No session, no access.