Im working on a simple app, that allow the user to login. Im using an ajax function pass the values to a PHP file(on a different domain). If the user and the password are correct the page display echo"success" and im using that word to validate and create a random key to allow the user access to a private page.
I was reading that you can also add a header token, it is possible to add that to my current code..
Iam new in developing "app", hope some one can point in the right direction on what is the best way to do this.
var username = $("#username").val();
var password = $("#pass").val();
var dataString = "username="+username+"&pass="+password+"&insert=";
$.ajax({
type: "POST",
url: "url",
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function() {$('#loginButton').val('Connecting...');},
success: function(data)
{
if(data == " success")
{
alert("Success");
returnHash();
}
if(data == " Login failed")
{
alert("There's a problem with username/password!");
$('#loginButton').val('Submit');
}
}
});
function returnHash()
{
letters = "abcdefghijklmnopqrstuvwxyz1234567890".split("");
window.token="";
for(i=0;i<64;i++){
window.token += letters[Math.floor(Math.random()*letters.length)];
}
success();
}
To create a real unique hash, use the current time with an random generated number like in the code below:
var dateForHash = (new Date()).valueOf().toString();
var createRandomNum = Math.random().toString();
crypto.createHash('sha1').update(dateForHash + createRandomNum).digest('hex');
You can also use crypto.randomBytes()- this hash is practical unique but not theoretical.
var hash = crypto.randomBytes(20).toString('hex');
I would recommend the second way for this type of use.
Related
I have created a WebView for macOS app and it contains one AJAX call. The same WebView is working fine when the app calls my local URL, but when it calls the live URL, the AJAX call is not working.
$(document).ready(function () {
$('#pripolcheck').click(function () {
var pripolcheck = $('#pripolcheck').val();
var app = $('#app').val();
var user_id = $('#user_id').val();
var contact = $('#contact').val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'pripolcheck1=' + pripolcheck + '&app1=' + app + '&user_id1=' + user_id;
if (pripolcheck == '') {
alert('Please Fill All Fields');
} else {
// AJAX Code To Submit Form.
$.ajax({
type: 'POST',
url: 'http://mywebsite.com/ajaxformsubmit.php',
data: dataString,
cache: false,
success: function (result) {
// alert(result);
// $(".pripol").hide();
$('.pripolcheck').prop('checked', true);
$('input.pripolcheck').attr('disabled', true);
}
});
}
return false;
});
});
My local PHP version is 7.1.8 and my live server PHP version is 5.4.
Change your function to onclick of checkbox directly,put this code in your checkbox onclick="MyFuncion",why I'm telling this is for web view we need to give exact command in exact position it's not a browser
And your AJAX call will be like below,
function myFunction()
{
var pripolcheck = $("#pripolcheck").val();
var app = $("#app").val();
var user_id = $("#user_id").val();
var contact = $("#contact").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'pripolcheck1='+ pripolcheck + '&app1='+ app + '&user_id1='+ user_id;
if(pripolcheck=='')
{
alert("Please Fill All Fields");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "ajaxformsubmit.php",
data: dataString,
cache: false,
success: function(result){
// alert(result);
// $(".pripol").hide();
$('.pripolcheck').prop('checked', true);
$("input.pripolcheck").attr("disabled", true);
}
});
}
return false;
}
"My local PHP version is 7.1.8 and my live server PHP version is 5.4."
I think this explains everything.
However, try setting an absolute URL in your call:
url: 'ajaxformsubmit.php',
to
url: '/ajaxformsubmit.php',
Or whatever the actual path would be. Just a single slash will give you
http://wherever.com/ajaxformsubmit.php
if u use same site url plz use relative path not absolute path then its ok.
if use defrant site url plz comment me so give me new solution
PLZ try
$(document).ready(function () {
$('#pripolcheck').click(function () {
var pripolcheck = $('#pripolcheck').val();
var app = $('#app').val();
var user_id = $('#user_id').val();
var contact = $('#contact').val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'pripolcheck1=' + pripolcheck + '&app1=' + app + '&user_id1=' + user_id;
if (pripolcheck == '') {
alert('Please Fill All Fields');
} else {
// AJAX Code To Submit Form.
$.ajax({
type: 'POST',
url: '/ajaxformsubmit.php',
data: dataString,
cache: false,
success: function (result) {
// alert(result);
// $(".pripol").hide();
$('.pripolcheck').prop('checked', true);
$('input.pripolcheck').attr('disabled', true);
}
});
}
return false;
});
});
I have made a booking system that utilizes FullCalendar; though that part should be irrelevant. My problem is that upon saving an appointment, a 'notes' field I have created very occasionally has this strange string inserted into it, generally at a random point in the string. Here is the latest example:
Has this been changedjQuery1112010047650896012783_1444929292744 with Rich- finishing sleeve off.bringing deposit in on saturday. told him space isnt secure.
As you can see, there is a totally out of place "jQuery1112010047650896012783_1444929292744" placed in the middle of the note. I can't find anything about this online (mainly because I have no idea what terms I'd use to find it). It must be related to jQuery, considering the string.
I am using jQuery v1.11.2 - obviously the string looks like a long version number.
Why is my ajax request seemingly succeeding, but placing this message in the middle of the sent string? I cannot replicate this issue at all, especially this time since it was another user who managed to cause it.
The function that fetches/prepares/sends data looks like this:
function postForm(content, action, update) {
loader('show');
var popup = content.parent();
var children = content.find(".input");
var data = {}
var elements = [];
data['elements'];
$( children ).each(function() {
var child = {};
child['name'] = $(this).attr('data-name');
if ($(this).is(':checkbox')) {
child['value'] = $(this).is(":checked");
} else {
child['value'] = $(this).val();
}
elements.push(child);
});
data.elements = elements;
data.request = action;
dataPost = JSON.stringify(data);
console.log(dataPost);
ajaxRequest = $.ajax({
type: "POST",
url: "/?page=ajax",
data: dataPost,
dataType: 'json',
success: function(response) {
loader('hide');
console.log(response);
if (update) {
$(update.element).load(update.url+" "+update.element+" > *");
checkError = doExtra(response, update.extra);
}
if (checkError == false) {
popup.fadeOut();
}
}
});
return false;
}
The note section is just a textarea with the class 'input' (which is looped through and fetched).
I don't think there will be a solution for the exact problem, however, I'm looking for an explanation for the modification of the string. The application works perfectly, except for this very rare case.
Question marks (??) are replaced with a jQuery time stamp. To fix, I had to add jsonp: false to the parameters. Final ajax:
ajaxRequest = $.ajax({
type: "POST",
url: "/?page=ajax",
data: dataPost,
dataType: 'json',
jsonp: false,
success: function(response) {
loader('hide');
console.log(response);
if (update) {
$(update.element).load(update.url+" "+update.element+" > *");
checkError = doExtra(response, update.extra);
}
if (checkError == false) {
popup.fadeOut();
}
}
});
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'm working on project that simulates Twitter and I'm using HTML + JS on client and WCF services on server side (ajax calls), and Neo4J as database.
For example:
in $(document).ready(function ()
there is DisplayTweets service call -> DisplayTweets(username)
function DisplayTweets(userName) {
$.ajax(
{
type: "GET", //GET or POST or PUT or DELETE verb
url: "Service.svc/DisplayTweets", // Location of the service
data: { userName: userName },
contentType: "application/json; charset=utf-8", // content type sent to server
dataType: "json",
processdata: true, //True or False
success: function (msg) //On Successfull service call
{
DisplayTweetsSucceeded(msg);
},
error: function () // When Service call fails
{
alert("DISPLAY TWEETS ERROR");
}
}
);
}
and then DisplayTweetsSucceeded(msg) where msg would be json array of users tweets
function DisplayTweetsSucceeded(result)
{
for (var i = 0; i < result.length; i++)
{
var tweet = JSON.parse(result[i]);
var id_tweet = tweet.id;
var content_tweet = tweet.content;
var r_count_tweet = tweet.r_count;
NewTweet(null, id_tweet, content_tweet, r_count_tweet);
}
}
Function NewTweet is used for dynamic generating of tweets.
Problem is when I first load html page, nothing shows up, neither when I load it multiple times again. It only shows when I go through Firebug, line by line.
I'm presuming that maybe getting data from database is slower, but I'm not sure and also have no idea how to solve this. Any help will be very much appreciated, thank you in advance!
To keep it simple, I'm just wanting to know how I'd go about and if else statement against my ajax to print new data out once if it finds it and not the same data over and over again. Amd how can I possibly store the last id as a variable to reuse it when searching for more new records?
Someone mentioned to me also I could save the new notification idea as a return so when the ajax restarts it uses this to find the next new set of results.
Has anybody got any ideas how to achieve these?
<script type="text/javascript">
setInterval(function(){
var time = new Date().getTime();
var notification_id="<?php echo $notification_id['notification_id'] ;?>"
$.ajax({
type: "GET",
url: "viewajax.php?notification_id="+notification_id+"&time="+time ,
dataType:"json",
cache: false,
success: function(response){
if(response.num){
$("#notif_actual_text-"+notification_id).prepend('<div id="notif_actual_text-'+response['notification_id']+'" class="notif_actual_text">'+response['notification_content']+' <br />'+response['notification_time']+'</div></nr>');
$("#mes").html(''+ response.num + '');
}
}
});
},20000);
</script>
Regarding to store the last id, you could use:
window.localStorage.setItem('key', 'value');
Then when you want to get it again you'll should use:
var lastId = window.localStorage.getItem ('key');
And regarding the duplicates issue, well, you should have a internal storage in order to handle the recieved data. May be an array can help as storage, also you can also store this array in local storage.
Once you handle this data storage, you could apply something like this to verify that your data has no duplicates:
var dataHandler = function (response){
var isDuplicate = false, storedData = window.localStorage.getItem ('key');
for (var i = 0; i < storedData.length; i++) {
if(storedData[i].indexOf(response) > -1){
isDuplicate = true;
}
}
if(!isDuplicate){
storedData.push(response);
}
};
var printer = function(response){
if(response.num){
$("#notif_actual_text-"+notification_id).prepend('<div id="notif_actual_text-'+response['notification_id']+'" class="notif_actual_text">'+response['notification_content']+' <br />'+response['notification_time']+'</div></nr>');
$("#mes").html(''+ response.num + '');
}
};
UPDATE
var notification_id = window.localStorage.getItem ('lastId');
$.ajax({
type: "GET",
url: "viewajax.php?notification_id="+notification_id+"&time="+time ,
dataType:"json",
cache: false,
success: function(response){
if(response){
dataHandler(response);
if(response.num){
window.localStorage.setItem('lastId', response.num);
}
});
},20000);