I am creating A login system using AJAX,PHP & SQL obviously.
Anyway I am trying to implement A real time login feature so it will log the user in without refreshing the page.
I have done that almost but the only issue when the user clicks remember me that uses cookies instead of sessions but the JQuery isn't proccessing that?
I want it to detect depending if it was checked ether remember the user or not it only starts a session, when it does register a cookie the logout page is not deleting the cookie which he did before i added the jquery code in so nothing on the php end and I am mainly A PHP Developer and still learning.
(I cannot post the server side code for privacy reasons as I be using this in A project
but it looks similar to any other normal php login script)
Here's the JQuery
function validLogin(){
var user_login=$('#user_login').val();
var user_pass=$('#user_pass').val();
var remember_me=$('#remember_me');
var dataString = 'user_login='+ user_login + '&user_pass='+ user_pass;
$("#flash").show();
$("#flash").fadeIn(100).html('Loading..');
$.ajax({
type: "POST",
url: "ajax/procces.php",
data: dataString,
cache: false,
success: function(result){
var result=trim(result);
$("#flash").hide();
if(result=='correct'){
window.location='index.php';
}else{
$("#errorMessage").html(result);
}
}
});
}
function trim(str){
var str=str.replace(/^\s+|\s+$/,'');
return str;
}
Thanks
You don't pass your variable 'remember me' to your ajax request. For instance :
data: {login: user_login, passwd: user_pass, rememberMe: remember_me}
Another point, be careful you treat information from client-side. Never trust the client. Test all your values in PHP.
Related
I have a strange (for me) behavior about use of PHP session_destroy(), used for logout, and JS localStorage used for avoid continuous DB ajax request.
So. My current (and working) scenario:
At login form, PHP do a session_start() -> browser writes cookies with PHPSESSID (no localStorage at moment);
After logon, IF localStorage.getItem('myDataItem') === null, data are requested once (ajax) and written with localStorage.setItem('myDataItem', 'Hi, I'm your ajax response'). If localStorage.getItem('myDataItem') !== null do noting;
Code:
if(localStorage.getItem('myDataItem') === null){
$.ajax({
url: 'ajax.php',
type:'post',
data:{request: 'dbInfo'}
}).done(function(jsonObjectResponse){
localStorage.setItem('myDataItem', JSON.stringify(jsonObjectResponse))
});
}
On logout click element, browser runs a function with an ajax request that do a PHP's session_destroy() and do a JS location.reload()
and restart from the login form;
Code:
$("#logout_element").on('click', function(){
$.ajax({
url: 'ajax.php',
type:'post',
data:{request: 'logout'} /*ajax PHP do a session_destroy()*/
})
.done(function(){
location.reload();
});
});
So far, everything (F5/refresh) is regular, if it were not for the logout/session_destroy (), the localStorage disappears
My Goal
keep localStorage even after the session_destroy ()
Best,
Oscar
I have an html page and I need to load some usual information(can be seen by all people) from DB.
so I put this code in the html:
<script type="text/javascript">
$(document).ready( function() {
setTimeout( "getRate()", 100 );
});
function getRate() {
$.ajax( {
type: "GET",
url: "api.php",
dataType: "json",
data: {call: 'getRate'},
success: function(result){
//set result to the DOM element....
},
error: function(){
}
});
}
</script>
and I have a api.php file like this:
<?php
if($_SERVER['REQUEST_METHOD']=="GET") {
$function = $_GET['call'];
if($function == "getRate") {
//get result from DB
echo json_encode(result);
}
}
but my code reviewer said that when put this url in the browser directly "https://****.com/api.php?call=getRate", it also returned the json result,is it safe??
well there is no secret information requested by the ajax call,so
it's I think it's OK , but I'm not sure.
Is there any security risk for doing like this?
If your question is whether or AJAX itself is secure, then yes, AJAX is used all the time to exchange information between a browser and a remote API.
As for your code specifically, there doesn't seem to be a vulnerability here provided:
The raw JSON response truly doesn't have any secret information
The SQL query (or equivalent) used to generate the JSON isn't vulnerable to injection attacks if someone tries to craft the call: getRate param to something malicious.
The AJAX call doesn't alter the state of the database
The AJAX call doesn't tie up resources for anything other than a very small amount of time. For instance someone spamming https://****.com/api.php?call=getRate shouldn't bring down the site.
I'm feeling scared about a solution i'm using in one of my app.
Basically, i use this snippet :
var username = ...;
$.ajax({
type: "POST",
url: "getFeed.php",
data: "username="+username,
success: function(html) {
// do the stuff
}
});
My question is : is this hackable ? If you use the chrome/firefox/... build-in code editor and replace var username = ... by var username = 'user1';, would it work ?
Thanks
Yes, anyone with a javascript debugger will be able to change the variable to whatever username they want. JavaScript is always open to the user and can be modified easily.
Typically you would have a login page to authenticate the user (often cookie based), and then on every subsequent request (Ajax or otherwise) you would be able authenticate the cookie and make sure the user is who he says he is. This will however require a server side solution to the authentication.
I want only execute my ajax post 1 time, i try to avoid to the user refresh the page and execute so much times the ajax post,
I thought in create a cookies, but i don't know, and i'm no sure, somebody know how?
This is my jquery.
var t = jQuery.noConflict();
t( document ).ready(function() {
t.cookie("example", "foo", { expires: 7 }); // Sample 2
console.log( "ready!" );
alert(t.cookie("example"));
var data = '<?php echo json_encode($json_full);?>';
t.ajax({
url: 'my api url',
type: 'POST',
success: function(r) { alert(JSON.stringify(r)) },
dataType: 'JSON',
data: { data: data, }
})
});
/I need run this AJAX only one time because is a checkout page to send the order, and if i refresh the page, send every time the same order, and this i don't want/
Thanks a lot!
Things like these can not be safely controlled on the client's browser. Any user with minimal knowledge in JavaScript will be able to open up the developers tools for their browser and manipulate the code or any values you might have stored (such as deleting the cookie you have set).
This limitation should be implemented on the server.
It really depends on the scope of your application. You might be able to limit the requests per IP address, but that might prevent multiple people from the same office for example loading the page at the same time.
Using user authentication and persistent server storage you'll be able to limit the effect of the request, but you probably won't be able to prevent the actual request from being sent as anyone can make that request even from outside the browser. You could store the user_id of the user that initiated the request and only allow the resulting action to occur if a certain time has passed since the last request.
A better solution to avoid double submits, is to use a POST query for the submit request and let the server respond with a redirect to a normal (harmless) receipt/thankyou page.
Then if the user refreshes the receipt page they will simply repeat the GET request to the receipt page and not the post.
You should still add some checks server side to avoid multiple POST requests somehow (using sessions, timestamps or something), in case a malicious user deliberately tries to resubmit.
This will only work on IE8 and above, but you can use localStorage:
var t = jQuery.noConflict();
t( document ).ready(function() {
t.cookie("example", "foo", { expires: 7 }); // Sample 2
console.log( "ready!" );
alert(t.cookie("example"));
if(localStorage['submitted'] === undefined){
var data = '<?php echo json_encode($json_full);?>';
t.ajax({
url: 'my api url',
type: 'POST',
success: function(r) {
localStorage['submitted'] = true;
alert(JSON.stringify(r));
},
dataType: 'JSON',
data: { data: data, }
})
}
});
This way the first time it will run the AJAX because you haven't set the localStorage variable, but upon success you do and it will not resubmit on page refresh.
If you wanted to have the ability to send again upon a future visit, just use sessionStorage instead of localStorage. Same syntax and everything.
i have a form that deletes the comment its in.
To only allow the page that carries out the php action to be viewed when the form is submitted i do a basic
if (isset($_POST['submit-delete'])) {
// carry out delete
}
this works fine, but i am using ajax to not reload the page.
The response is the same as i have used else where:
$(document).ready(function(){
$(".delrepcomment").submit(function(){
$.ajax({
type: "POST",
url: "process/deletecomment.php",
data: $(".delrepcomment").serialize(),
dataType: "json",
success: function(response){
if (response.commentDeleted === true) {
$('#successdisplay').fadeIn(1000),
$('#successdisplay').delay(2500).fadeOut(400);
}
else {
$('.delrepcomment').after('<div class="error">Something went wrong!</div>');
}
}
});
return false;
});
});
This however doesnt work, unless i remove the check to see if the form has been submitted.
Whats the best way around this? I want to keep the check for the form being submitted incase of js being turned off or any direct access attempts.
Thanks.
You should post the data you require for the script to work. In your case, you have to post a key-value-pair with "submit-delete" as the key and an arbitrary value (unless you check that value later in the code).
On the other hand, PHP stores the used HTTP method in $_SERVER['REQUEST_METHOD'], this would be "POST" in your case.