Reject sites with alexa rank smaller than x in input field - javascript

PHP - alexa.php
<?
$url = filter_var($_GET['url'], FILTER_SANITIZE_URL);
$xml = simplexml_load_file('http://data.alexa.com/data?cli=10&dat=snbamz&url='.$url);
$rank=isset($xml->SD[1]->POPULARITY)?$xml->SD[1]->POPULARITY->attributes()->TEXT:0;
web == (string)$xml->SD[0]->attributes()->HOST;
echo $rank;
?>
Javascript - alexa.js
function alexa() {
var $btn = $('#buttonreg');
var $input = $('#domain');
var url = $.trim($input.val());
$.get('alexarank.php?url='+url, function(data){
var alexa = parseInt(data);
if ($.trim(data) == '' || alexa < 500000)
{
alert('We don't accept sites with alexa rank higher than 500.000.');
$btn.attr('disabled', 'disabled');
}
else
{
$btn.removeAttr('disabled');
}
}, 'text');
}
HTML - page.html
<input id="domain" class="txt" type="text" name="domain" size="25" value="" maxlength="255" onblur="alexa()"></input>
I need to echo the error alert('We don't accept sites with alexa rank higher than 500.000.'); when the user is adding his website on the registration form if his site alexa rank is smaller than 500.000. I have tested it and it doesn't work, it doesn't do anything.
Started testing it from php, the php works when i go in the browser http://www.testingsite.com?url=http://www.google.com it returns the right value so i am thinking that i have done something bad with the javascript or HTML.

I'll make things clear what I mentioned in the comment.
alert('We don't accept sites with alexa rank higher than 500.000.');
should be replaced with
alert("We don't accept sites with alexa rank higher than 500.000.");
The first one (which you have in your code) has mismatching quotes, and obviously breaks the rest of the code. The single quote you used in " don't " is what broke everything.
EDIT:
Change your code to this and try. If still doesn't work, check js console.
function alexa() {
var $btn = $('#buttonreg');
var $input = $('#domain');
var url = $.trim($input.val());
$.get('alexarank.php?url='+url, function(data){
if( typeof(data) == "undefined" ) return false;
var alexa = parseInt(data);
if ($.trim(data) == '' || alexa < 500000)
{
alert('We do not accept sites with alexa rank higher than 500.000.');
$btn.attr('disabled', 'disabled');
}
else
{
$btn.removeAttr('disabled');
}
});
}

Related

Ajax dependent text field and dropdown menu (Php and Javascript)

I'm a student and still new with Javascript and php, i need to make a login page for my website that can check user input in the database using ajax.
Example: When the user enter their username and password into the field given,the system will automatically check in database either the user exist or not and return the data needed such as user responsibilty from the response table to the dropdown menu below, then they can login into the system.
Below is my basic coding:
Config.php:
e$host = "localhost";
$User = "root"
$Pass = "passw";
$db = "skm_spm";
Login.php:
<?
require ("config.php");
$conn=mysqli_connect($host,$user,$pass,$db);
$duser="select * from tab_user where user_name = '".$_POST["Lname"]."'";
$uresult=myqli_query($conn,$duser);
if(!$uresult)
die("Invalid query: ".mysqli_error());
else
if(mysqli_num_rows($uresult)== 0){
echo "User does not exist";
}
else
{
$row=mysqli_fetch_array($result,MYSQL_BOTH);
if($row["User_Password"] == $_POST["Lpass"])
{
$dresp="select resp_id,resp_name from tab_resp";
$result2 = mysqli_query($conn,$dresp);
}
else
{
}
}
?>
<html>
<b>Login</b><br>
Name : <input type = "text" name="Lname" id="Lname" placeholder="Username"/><br>
Password: <input type = "password" name="Lpass" id="Lpass" placeholder="password"/><br><br>
<div class = "optresp">
<select name="sresp" id="sresp">
<option>--Responsibility--</option>
<?
while (mysqli_fetch_array($result2)){
echo "<option value='$row[1]'>$row[1]</option>";
?>
</select>
</div>
</html>
I have learn on internet and try to code with my understanding,but still failed. I need a php ajax coding that can work with code above.
Thank you.
I will provide you with some code from my recent project and hopefully you will be able to understand it and adapt it to your needs.
Firstly, you should have the login form in a separate file to the PHP login code. Then have button on the page or an enter events that run a Javascript function, in my case Login(). In this Javascript function the text within the input fields are saved to two variables and some basic checks are done on them to ensure that they have been filled in. Next, the PHP login function file (it has no visible content in just processes some data in PHP) using the $.post line. This also passed the two input variables (under the same name) to the PHP file. You can also see that depending on what is returned/echoed from the PHP file as "data" several possible outcomes may occur (Login Success, Account Banned or Invalid Login). I personally call these outcomes error messages or success messages, for example error message 6 for incorrect password/username.
//FUNCTIONS
function Login(){
var StrUsername = $("#txtUsername" ).val();
var StrPassword = $("#txtPassword").val();
if (StrUsername == "" && StrPassword == ""){
$('#pError').text('Enter your Username and Password!');
}
else if(StrUsername == ""){
$('#pError').text('Enter your Username!');
}
else if(StrPassword == ""){
$('#pError').text('Enter your Password!');
}
else{
$.post('https://thomas-smyth.co.uk/functions/php/fnclogin.php', {StrUsername: StrUsername, StrPassword: StrPassword}, function(data) {
if (data == 0){
window.location.href = "https://thomas-smyth.co.uk/home";
}
else if (data == 1){
window.location.href = "https://thomas-smyth.co.uk/banned";
}
else if (data == 6){
$('#pError').text('Username & Password combination does not exist!');
}
});
}
}
Next the PHP function file. Firstly, the variables passed by the Javascript are collected using $_POST. My SQL class is then pulled into the file, this does all my SQL DB connections. I then have my SQL statement that will search to see if the account exists. Notice the ? in it. This prevents SQL injections as the variables is bound into the statement through the SQL server meaning it won't allow people to put SQL code within my input fields to break my database. I then check whether the account exists, if it doesn't I save data to 6, which will cause the error message 6 in the Javascript to run when data is returned. I have a field in my database that contains a rank. If the login is correct then I create a SESSION variable to store their username and rank in. This is later used on pages to check whether they are logged in before displaying a page (this speeds up navigation as it means that the DB doesn't need to be searched everytime the user switches page, however does bring some issues like if you ban a user while they are logged in they will stay logged in until their session dies). You could use this on your dropdown menu to ensure the user is logged in and/or get their username. Finally, I return 0 or 1, so that the Javascript then re-directs them to the correct page.
<?php
//Retrieves variables from Javascript.
$StrUsername = $_POST["StrUsername"];
$StrPassword = $_POST["StrPassword"];
require "sqlclass.php";
$TF = new TF_Core ();
$StrQuery = "
SELECT Username, Rank FROM tblUsers
WHERE Username = ? AND Password = ?";
if ($statement = TF_Core::$MySQLi->DB->prepare($StrQuery)) {
$statement->bind_param('ss',$StrUsername,$StrPassword);
$statement->execute ();
$results = $statement->get_result ();
if($results->num_rows == 0){
$data = 6;
}
else {
while ($row = $results->fetch_assoc()) {
//Other groups
if ($row["Rank"] == "Developer" || $row["Rank"] == "Staff" || $row["Rank"] == "Cadet"){
session_start();
$_SESSION["LoginDetails"] = array($StrUsername, $row["Rank"]);
$data = 0;
}
//Banned
else if ($row["Rank"] == "Banned"){
session_start();
$_SESSION["LoginDetails"] = array($StrUsername, "Banned");
$data = 1;
}
}
}
}
echo $data;
?>
Hopefully this helps you. Please say if you need more help!
You need to make ajax call on blur of username to check if user exists in database and on success of that you can make one more ajax to check for password match of that particular user. This will give you both cases whether a user exixts or not if exixts then does the password match or not only after that user will be logged in and then you can show the responsibilities of that particular user.
For username:
$('#Lname').blur(function(){
$.ajax({
url:'url where query for matching username from database',
data:'username collected from input on blur',
type:'POST',
success:function(data){
//Code to execute do on successful of ajax
}
})
})
For Password:
The ajax call remains the same only url, data and response changes

How to limit asynchronously showed results while searching?

I'm doing a personal blog and recently have stopped because of this little problem... is being a challenge to me to figure it out so... I hope you could help me guys
What I want to do is; put some kind of limit to the results I obtain while searching, and that's because these results are loaded asynchronously while typing, so... if I search for something that has over 100 results (for example) the scroll will be just too long, so what I'd like to do is make appear some kind of 'load more button' that allows the user to load more results if he wants to.. how could I do that?
Here's the code I have done so far...
HTML:
<input type="text" id="busqueda" name="busqueda" value="" required autocomplete="off" onKeyUp="search();">
<div id="result"></div>
<button id="loadmore"> load more</button>
PHP:
<?php
//connect to db
require('db_conexion.php');
$consultaBusqueda = $_POST['valorBusqueda'];
if (isset($consultaBusqueda)) {
//sanitize post value
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
//throw HTTP error if page number is not valid
if(!is_numeric($page_number)){
header('HTTP/1.1 500 Invalid page number!');
exit();
}
//capacity
$item_per_page = 5;
//get current starting point of records
$position = (($page_number-1) * $item_per_page);
//query
$buscar= $conexion->query("SELECT info from table ORDER BY id DESC LIMIT $position,$item_per_page");
//conditionals
if (!$query_execute->num_rows) {
$mensaje = "no results";
}else{
$filas= $query_execute->num_rows;
echo $filas.' Results for <mark>'.$consultaBusqueda.'</mark>';
//show results
while($row = $buscar->fetch_array()) {
$variable="something";
echo $variable;
}
}
}else{
echo "Error";
}
?>
JS:
function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && (node.type=="text")) {return false;}
}
document.onkeypress = stopRKey;
function search() {
var textoBusqueda = $("input#busqueda").val();
if (textoBusqueda != "") {
$("#resultadoBusqueda").show();
$.post("actions/search.php", {valorBusqueda: textoBusqueda}, function(menssage) {
$("#resultadoBusqueda").html(menssage);
});
} else {
$("#resultadoBusqueda").html("");
};
};
Here you have the page so you can see how is working right know
http://www.subeuna.com/blog/
all you have to do y search something, anything... and you'll see... i really need your help guys I hope your answers :(
You might look into having your backend api only return a max number of results and if it exceeds that number provide a property to fetch more. If that extra property exists present the load more button otherwise do not.
API pagination best practices

How do I create a method that allows 2 players to fight each other in Php/Ajax?

I am working on a turn based multiplayer game using php and ajax. The features allow players to log into the game using user info, and select game modes which allows them to either play against AI or opponents. Each user can select a character from a list, and this function has already been completed. I would like to create a search function so that a player could search and battle another player, something similar to chess. However, at the moment I would like for the player to enter another users username in order for the search to take place. I have searched open source to find a method to creating a search function, but the current function I found breaks my code. Here is my current mode codes:
// Define Mode
if (isset($_GET['mode'])) {
$mode = $secure->clean($_GET['mode']);
} else {
$mode = '';
}
if ($mode == 'selection') {
$page_title .=' > Character Selection';
$page_titles .= ' Character Selection - Power Bond';
}
else if ($mode == 'search') {
if (isset($_GET['type'])) {
$type = $secure->clean($_GET['type']);
} else {
$type = '';
}
if ($type == 'private') {
if (isset($_POST['pbsubmit'])) {
$name = $secure->clean($_POST['name']);
}
}
}
Now here is my ajax. The function I found was for checking the match in order to find the username. That function breaks my game.
//Check the match.
if (isset($_POST['f']) && $_POST['f'] == 'checkMatch') {
$checkMatch = $db->query("SELECT * FROM accounts WHERE `id` = '".$account['id']."'");
while ($info = mysql_fetch_array($checkMatch)) {
$status = $info['status'];
$gameid = $info['gameid'];
}
$getGame = $db->fetch("SELECT * FROM Games WHERE `gameid` = '$gameid'");
$status = $info['status'];
$gameid = $info['gameid'];
if(!$getGame = 'NULL') {
$data = 'testaeta';
} else {
$data = '<h1> Who do you want to battle against? </h1>
<br />
<form action="" method="post" id="form-pb" name="pb" target="_self">
USERNAME:<input name="name" type="text" size="40" maxlength="40" />
<input name="pbsubmit" type="submit" value="Search"/>
</form>
<a class="goback" href="#">Cancel</a>';
}
echo $data;
}`
Here is my Javascripit:
`var match = null;
function popUp(what){
if(!what) errorMessage('Error: params', 'params', 'none');
switch(what){
case 'search':
preLoad('Loading please wait . . .');
$('#main_container').prepend('<div id="popup"><div class="opacity"></div><div class="search"></div></div>');
$('.search').load('./?page=game&mode=search&type=private', function(){
$('#preloader').fadeOut('slow',function(){
$('#preloader').remove();
});
});
break;
case 'match':
$.ajax({
url : _path + "/core/ajax.php",
type : 'POST',
data : { f: 'checkMatch'},
dataType : 'text',
success : function(data) {
if(data){
$('#main_container').prepend(data);
match = setInterval(function(){
if(!$('.search').length){
$('#main_container').prepend('<div id="popup"><div class="opacity"></div><div class="search"></div></div>');
}
$('.search').load('./?page=game&mode=search&type=private', function(){
var meta = $('#stopMe').attr('content');
if(meta){
meta = meta.split("URL="), meta = meta[1];
window.location = meta;
}
});
},1000);
}
}
});
break;
case 'submit':
$.post('./?page=game&mode=search&type=private', $("#form-pb").serialize(), function(data){
var $response=$(data);
var error = $response.filter('h3').text();
$('.search').html(data);
if(!error){
match = setInterval(function(){
if(!$('.search').length){
$('#main_container').prepend('<div id="popup"><div class="opacity"></div><div class="search"></div></div>');
}
$('.search').load('./?page=game&mode=search&type=private', function(){
var meta = $('#stopMe').attr('content'); var meta = $('#stopMe').attr('content');
if(meta){
meta = meta.split("URL="), meta = meta[1];
window.location = meta;
}
});
},1000);
}
});
break;
}
}
`
Aside from mysql, those are my main focuses on allowing this to work. Does anyone have a solution on how I could fix this problem? Also, I would like an open source example if possible.
There is no need to search an already coded search solution, generally this is very specific to your application and not complicated.
Look for an autocompletion tool (jQuery provide it), a way to get secure data (GET or POST but check it) and a search method: LIKE %...% (simple) or MATCH(...) AGAINST(...) (More complete)
Seems like a match making system. You could create a table in mysql and name it something like active battles. It then takes user A's info and matches it with user B, putting them inside a battle. I think you could also make a table for the battles actions. That table shows what the users do while in a battle.

How does Google Script send an email when it detects changes in the background, like cron?

I have a Google spreadsheet with a script that checks a local library catalog to see if an ISBN-searched book has shown up or not. There's no API or RSS feature so I'm using UrlFetchApp to screen scrape for certain unique phrases that appear in the HTML source for a given book status.
Right now my spreadsheet only updates the "Status" column (which invokes the script based on an ISBN field) when I open the spreadsheet. Is there a way I can have Google Script run my main function and then trigger for changes? The documentation I've read has only mentioned user edits, which is not what I'm looking for.
function ISBNsearch(ISBN){
var consortURL = "http://LIBRARYURL/search~S6/?searchtype=i&searcharg=" + ISBN + "&searchscope=4";
var retrieveURL = UrlFetchApp.fetch(consortURL).getContentText();
var searchURLno = retrieveURL.search("BROWSE SCREEN TABLE");
var searchURLyes = retrieveURL.search("Item Location");
var searchURLordered = retrieveURL.search("copy ordered for");
if (searchURLno > -1){
var answer = "Not found"
} else if (searchURLyes > "-1") {
answer = "in Consort"
} else if (searchURLordered > "-1") {
answer = "on order"
} else if ((searchURLno == "-1") && (searchURLyes == "-1") && (searchURLordered == "-1")) {
answer = "no input"; }
return answer;
}
function testScript(){
var response = ISBNsearch("9782711802036");
Logger.log("The answer is " + response);
return response;
}
You can use Time Driven triggers to schedule function executions.
You can also programmatically manage these triggers.

How To Allow Some Urls, and Block Others based on a few conditions

Basically I have a variable to work with that provides the url of a certain image $member_profile_image. I'm trying to check for that url, and then find the word "Default" in it. I've done that, the indexOf comes up as 22. That lets me know that someone has not uploaded a photo to their profile. If they haven't uploaded a profile photo I'd like them to only be able to access the links I have stored in the array myurls. So if the upload indexOf is indeed 22, and they are on one of those pages stored in myurls, I want nothing at all to happen, but if they try to go to any other page, I want the to be redirected to the page to upload a photo. I'm pretty new to all of this, so I'm probably way off here. The only thing I've managed to do so far is be redirected to the page where the photo gets uploaded, but it keeps reloading the page over and over again. Code Below:
<script>
var image = "$member_profile_image"
var upload = image.indexOf("Default");
var myurls = new Array(3);
myurls[0] = "http://websiteforyou.spruz.com/?page=login&cmd=c&id=7394750B-F821-48B6-B6AC-1508D1932390&c=eb3hb4el98";
myurls[1] = "http://www.websiteforyou.spruz.com/?page=login&cmd=confirm";
myurls[2] = "http://www.websiteforyou.spruz.com";
myurls[3] = "http://www.websiteforyou.spruz.com/member/?page=settings&cmd=personal";
if(myurls[0,1,2] = window.location && upload == "22")
alert("have a great day");
else
alert("You have to upload a profile image to participate on this site");
window.location.replace("http://www.websiteforyou.spruz.com/member/?page=settings&cmd=personal");
</script>
I don't fully understand what you're doing, so I made a lot of assumptions!
In general your biggest mistake is myurls[0,1,2,3] = window.location both because myurls[0,1,2,3] is invalid javascript and = doesn't compare but assigns.
I've made an example of what I believe the code should have been and I just hope I'm right.
var image = <?php echo json_encode($member_profile_image) ?>,
upload = image.indexOf('Default') === 22,
myurls = [
'http://websiteforyou.spruz.com/?page=login&cmd=c&id=7394750B-F821-48B6-B6AC-1508D1932390&c=eb3hb4el98',
'http://www.websiteforyou.spruz.com/?page=login&cmd=confirm',
'http://www.websiteforyou.spruz.com',
'http://www.websiteforyou.spruz.com/member/?page=settings&cmd=personal'
];
if (myurls.indexOf(window.location) > -1 && upload) {
alert('have a great day');
}
else {
alert('You have to upload a profile image to participate on this site');
window.location.replace('http://www.websiteforyou.spruz.com/member/?page=settings&cmd=personal');
}
If using IE8- you'll have to implement indexOf for the Array yourself (or use a polyfill)
Also assuming it's your domain and it doesn't change, you could just check the url path, like so:
var image = <?php echo json_encode($member_profile_image) ?>,
upload = image.indexOf('Default') === 22,
myurls = [
'/?page=login&cmd=c&id=7394750B-F821-48B6-B6AC-1508D1932390&c=eb3hb4el98',
'/?page=settings&cmd=personal',
'/?page=login&cmd=confirm',
''
];
if (myurls.indexOf(window.location.pathname) > -1 && upload) {
alert('have a great day');
}
else {
alert('You have to upload a profile image to participate on this site');
window.location.replace('/member/?page=settings&cmd=personal');
}
after the else statement, you need to wrap the alert and the location replace with { } - As it stands, the window.location line will be run regardless of the result of the if check.
That is to say, change
if(myurls[0,1,2,3] = window.location && upload == "22")
alert("have a great day");
else
alert("You have to upload a profile image to participate on this site");
window.location.replace("http://www.websiteforyou.spruz.com/member/?page=settings&cmd=personal");
to this:
if(myurls[0,1,2,3] = window.location && upload == "22")
alert("have a great day");
else
{
alert("You have to upload a profile image to participate on this site");
window.location.replace("http://www.websiteforyou.spruz.com/member/?page=settings&cmd=personal");
}

Categories

Resources