Im trying to build an api where the user has to be logged in to post reviews.
Ive hidden the reviews button and set it to show once the user logs in.
var loggeduser;
function Login(){
$.ajax({
url: 'http://creative.coventry.ac.uk/~4089797/Games/V2.0/Client4/index.php/users/account/'+$("#loginusername").val(),
headers: {Authorization:window.btoa($("#loginusername").val()+':'+$("#loginpassword").val())},
contentType: "get",
dataType: 'json',
success: function(data) {
Authorisation = window.btoa($("#loginusername").val()+':'+$("#loginpassword").val()); //create a variable to pass to the cookie
createCookie('auth',Authorisation,0); //create our authorisation cookie for the client
alert("Details correct. Please continue.");
loggeduser=username;
$("#login").hide(); //hide the login button
$("#create").hide(); //hide the create an account buttons
$("#logout").show(); //show the logout button
$("#addreview").show(); //show the add a review button
$("#adminpanel").show();//show the admin panel page
$("#loginusername").val(''); //clear the name box
$.mobile.changePage("#home"); //show the menu
},
error: function (response) {
var r = jQuery.parseJSON(response.responseText);
console.log(r);
alert("Error:" + r.error.text);
}
});
}
ive used the above ajax call to log the user in and have tried to pass the username from this get to loggeduser.
function Postreview(){ //Add a review to the site
$.ajax({
type:'post',
url: 'http://creative.coventry.ac.uk/~4089797/Games/V2.0/Client4/index.php/games/review/',
data: {ean:reviewean,
review_title:$("#ReviewTitle").val(),
review:$("#Review").val(),
rating:$("#rating").val(),
username:loggeduser},
dataType: 'json',
success: function(data) {
alert("Review Added. Please continue.");
$("#reviewtitle").val(''); //clear the text boxes
$("#review").val('');
$("#rating").val('');
Getreviews(ean);
},
error: function (response) {
var r = jQuery.parseJSON(response.responseText);
console.log(r);
alert("Error:" + r.error.text);
}
});
}
this is where the user posts the review however when the user submits review the username field is null and therefore hasnt been passed on
In your login ajax response, loggeduser is set to username
loggeduser=username;
... but username does not seem to exist? Perhaps you meant data.username?
Whatever the case, you should probably return from the server the username that has been authenticated, and use data.username to set loggeduser.
Also, storing the password in a cookie is a terrible idea. Are you using PHP sessions?
this is not how AJAX work where A stands for asynchronous
you have two option
1) in your Login() AJAX success do Postreview(username)
2) not recommended : async:false for login ajax
Related
I have different cards displayed on an app, the information is coming from the database in a loop. I have the option to put a 'redeem button' on cards if it's something a user can use just once. When the user clicks the redeem button, I get in the database the information (card name, clientID). Then, I made another AJAX call to get the information from the database and what I want is to check if the clientID and the carndame are already in the database then delete it just for that user. I don't wanna use localStorage or cookies because if the user delete the cookies they would see the card again and I don't want this to happen.
-- AJAX CALL TO POST --
$(`#promotion-container .promo${i} .redddButt`).click(function(e){
e.stopPropagation();
var esc = $.Event("keyup", { keyCode: 27 });
$(document).trigger(esc);
$('#deletePromo').on('click', function(){
if (eventName && customerID)
$(`#promotion-container .promo${i}`).remove() // this removes it but if you reload the page it appears again.
})
$('#just-claimed-popup2').addClass('reveal');
var theDiv = document.getElementById("card-just-claimed");
var content = document.createTextNode(eventName);
theDiv.appendChild(content);
$.ajax({
type: 'POST',
url: '/api/promotions_redemption',
crossDomain: true,
dataType: 'json',
data: {
eventName : eventName,
dateReedem : dateReedem,
}
});
})
--AJAX CALL TO GET INFO FROM DATABASE --
let success = function(res, eventName) {
let cardData = res['cardData'] //cardData is the info from database
for(i=0; i<cardData.length; i++){
let nameEvent = cardData[i]['event_name']
let customerID = cardData[i]['customer_id']
let clicked_button = cardData[i]['clicked_button']
let eventName1 = promotions['event_name'] // getting the names of all cards displayed
if(customerID && nameEvent == eventName1){
$(`#promotion-container .promo${i}`).remove(); // HERES THE PROBLEM
}
}
}
$.ajax({
type: 'GET',
url: '/api/promotions-check',
crossDomain: true,
dataType: 'json',
success: success,
});
The problem is that my conditional on my GET call is successful but it forgets the id of the card, meaning that when I try to console.log the id of the promo it comes as 0, instead of the actual number, so it's forgetting the information of the cards rendered and don't know what to delete.
What would be the best way to achieve the card to be deleted? Do I need to do it in the click event too? and if yes, can I have 2 Ajax calls in the same function?
If you change the approach you would be able to achieve this more easily. When you send a post request to delete the item or redeem the code in your case, upon success return same data and upon some condition just delete the item from DOM. On page load it shouldn't load whichever was redeemed.
I personally don't see a point of doing another GET to delete the code which was redeemed.
$.ajax({
type: 'POST',
url: '/api/promotions_redemption',
crossDomain: true,
dataType: 'json',
data: {
eventName : eventName,
dateReedem : dateReedem,
},
success: function(result){
//on success, ie when the item is deleted -> delete from the DOM.
}
});
I have an AJAX post method that works in two places both on "Ladder" page, but not another, a "matches" page. This method sets posts the "player ID" which php picks up and sets a session variable
$("form .singles-player-name").click(function (evt) {
evt.preventDefault();
var viewPlayer = $(this).val();
console.log(viewPlayer);
$.ajax({
url: '',
type: 'POST',
data: {
viewPlayerID: viewPlayer
}
}).done(function (data) {
console.log("Success");
//console.log(data);
window.location.href = "Player";
});
});
Working page form:
<form><button type='submit' id='playerInfo' class='singles-player-name' name='viewPlayer' value='",$sglsPlayerID,"'>", $curSGLSRankLName, ", ", $curSGLSRankFName, "</button></form>
Sets session variable
if (!empty($_POST['viewPlayerID'])){
$viewPlayer = isset($_POST['viewPlayerID']) ? $_POST['viewPlayerID'] : 'No data found';
$viewPlayerSql = "SELECT * FROM `PLAYERS` WHERE `ID` LIKE '".$viewPlayer."'";
$viewPlayerQuery = #$conn->query($viewPlayerSql);
$viewPlayerRow=mysqli_fetch_assoc($viewPlayerQuery);
$_SESSION['playerID'] = $viewPlayerRow["ID"];
echo "", $_SESSION['playerID'],"";}
Second working version that lives on the same page as the first but is for doubles players:
$("form .doubles-player-name").click(function (evt) {
evt.preventDefault();
var viewPlayer = $(this).val();
console.log(viewPlayer);
$.ajax({
url: '',
type: 'POST',
data: {
viewPlayerID: viewPlayer
}
}).done(function (data) {
console.log("Success");
//console.log(data);
window.location.href = "Player";
});
});
Form for that ajax method:
<form><button type='submit' id='playerInfo' class='doubles-player-name' name='viewPlayer' value='",$dblsPlayerID,"'>", $curDBLSRankLName, ", ", $curDBLSRankFName, "</button></form>
Then on complete, the ajax methods redirect to the player page and pulls up that players info on that page (ex. https://urlexample.com/Player). This part, from this point-up, works! However, I have another page, the "Matches" page, where I want it to do the same exact thing, and set that session variable, then redirect to the player page, so I have this method below. But for some reason, this one does not work:
$("form .singlesMatch-player1-name").click(function (evt) {
evt.preventDefault();
var viewPlayer = $(this).val();
console.log(viewPlayer);
$.ajax({
url: '',
type: 'POST',
data: {
viewPlayerID: viewPlayer
}
}).done(function (data) {
console.log("Success");
console.log(data);
window.location.href = "Player";
});
});
Not working form:
<form><button type='submit' id='playerInfo' class='singlesMatch-player1-name' name='viewPlayer' value='",$sglsPlayer1ID,"'>", $P1LN, ", ", $P1FN, "</button></form>
For some reason, all this second method does is post it to the URL (ex. https://urlexample.com/WeeklyMatchUps?viewPlayer=1) instead of setting the session variable and redirecting to the player page (ex. https://urlexample.com/Player). All thats different between the 2 is the class name of the button.
$sglsPlayer1ID should probably be $sglsPlayerID.
Also, try adding a success and error condition to your AJAX conditions instead of just using a done operator. This will allow you to dump helpful error codes on a failure to better resolve these kinds of issues in the future.
I had a function being called on the page that was commented out causing an error before jQuery was added in a script at the bottom of the page. removing that function from being called fixed the issue.
S/O to #line88 for the assistance!
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.
I've script two script that i want to merge as one . Script 1 is for checking if email and password is right it brings out a success message "Correct" and it logs you in. Script 2 is what i use to store the email and password in a localstorge
Script 1
$(document).ready(function(){
$("#form1").on('submit',function(event){
event.preventDefault();
data = $(this).serialize();
$.ajax({
type: "POST",
url: "log.asp",
data: data,
success: function(data) {
$('#log_msg').html(data);
var result = $.trim(data);
if(result==="Correct"){
window.location = 'source.asp';
}
}
});
});
});
Script 2
$(function() {
var
$email = $('#email'),
$password = $('#password'),
localEmail = localStorage.getItem("eaddress"),
localPwd = localStorage.getItem("pwd");
// SAVE VARIABLES TO LOCAL STORAGE
$('#form1').on('submit', function() {
localStorage.setItem("eaddress", $email.val());
localStorage.setItem("pwd", $password.val());
});
});
Now i want to merge the two together that it should only save the email and password in the localstorge if the success message is equal
to "Correct" and also logs you in
Never ever store passwords on the client!
Never store passwords unencrypted!
To store the email address in the localStorage you can use this snippet:
$(document).ready(function(){
$("#form1").on('submit',function(event){
event.preventDefault();
var data = $(this).serialize();
$.ajax({
type: "POST",
url: "log.asp",
data: data,
success: function(data) {
$('#log_msg').html(data);
var result = $.trim(data);
if(result==="Correct"){
localStorage.setItem('eaddress', $('#email').val());
}
}
});
});
});
Note: You have to cleanup the localStorage yourself. If you want to store the data for further identification use a sessionId in a cookie or use the sessionStorage for saving temporary data.
Edit: To submit the form after page load you can try something like this:
$(function(){
var eAddr = localStorage.getItem('eaddress');
if (eAddr !== null) {
$('#email').val(eAddr);
$('#form1').trigger('submit');
}
});
Note: If you store the password encrypted on the client and submit it trough the form, the authentication process is quiet insecure.
I think your authentication design is wrong. You should use an authentication cookie (like a session cookie) and validate it on the server side. Without submitting a form every time a page loads nor storing credentials on the client side.
I inherited an MVC app with jQuery and Kendo. Most of the controller actions have the [Authorize] attribute and it handles the redirection to the Login page nicely if the user is not already authenticated.
However, there's one feature that requires some additional information before the action is invoked. So, when the button for that feature is clicked, a Kendo window is displayed asking the user for a DateTime input. Then the action is called with that extra piece of input data, and the user is sent to another page after the action completes with the result of that action.
Here's the simplified code flow:
btnClicked_Listener{
// Pop-up Kendo window for DateTime input
// Get URL for action (#Url.Action("MyAction1", "MyController", new { date = [DateTime input] })
$.ajax({
datatype: 'json',
url: finalUrl,
cache: false,
success: function (result) {
window.location.href = window.location.origin + '/MyController/MyAction2?planId=' + result;
},
error: function (xhr, error, message) {
handleError(xhr, error, message);
}
});
This works fine if the user is already logged in. But if the user is not already logged in, here's what happens:
Kendo window popups for DateTime input.
Login page is displayed (since MyAction1 has the [Authorize] attribute).
User logs in.
Page '/MyController/MyAction2?planId=' is invalid, since MyAction1 never gets hit, and so result=null.
How can I fix this where the Javascript code can detect whether the user is logged in or not, and direct him to the Login page instead?
I do not want to hide the button if the user is not authenticated. I want to let the user be able to click on the button, but get redirected instead.
Thanks for any help!
You can mix server side code and javascript code to checking weather user is logged in or not.
<script>
btnClicked_Listener
{
#if (User.Identity.IsAuthenticated)
{
<text>
// Pop-up Kendo window for DateTime input
// Get URL for action (#Url.Action("MyAction1", "MyController", new {date = [DateTime input]})
$.ajax({
datatype: 'json',
url: finalUrl,
cache: false,
success: function (result) {
window.location.href = window.location.origin + '/MyController/MyAction2?planId=' + result;
},
error: function (xhr, error, message) {
handleError(xhr, error, message);
}
});
</text>
}
else
{
<text> window.location.href = 'Login page url' </text>
}
}
</script>
Edit: If you want pus your JS code in external file you have to put your code inside a function then pass a bool value to the function which indicate whether user is authenticated or not.
External JS
function handleButtonClick(isAuthenticated) {
btnClicked_Listener
{
if (isAuthenticated) {
// Pop-up Kendo window for DateTime input
// Get URL for action (#Url.Action("MyAction1", "MyController", new {date = [DateTime input]})
$.ajax({
datatype: 'json',
url: finalUrl,
cache: false,
success: function(result) {
window.location.href = window.location.origin + '/MyController/MyAction2?planId=' + result;
},
error: function(xhr, error, message) {
handleError(xhr, error, message);
}
});
} else {
window.location.href = 'Login page url';
}
}
}
and inside your html page call that function:
<script>
$(function() {
handleButtonClick(#User.Identity.IsAuthenticated);
});
</script>