Problem with Javascript about taken or available username - javascript

I have a problem, I did a taken/available username status that work correctly, but when I want to disable my submit button, this isn't working, I don't know why, please help me.
HTML input :
<input onkeyup="checkUsername()" id="username" name="username" type="text" class="form-control" value="<?php echo $row['username'] ?>" placeholder="Nom d'utilisateur" required autocomplete="off">
Javascript :
<script>
function checkUsername() {
const username = document.getElementById("username").value;
const xhr = new XMLHttpRequest();
xhr.open("POST", "check_username.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
const response = xhr.responseText;
const usernameMessage = document.getElementById("usernameMessage");
if (response === "Nom d'utilisateur disponible.") {
usernameMessage.innerHTML = "<span style='color:green;'>Nom d'utilisateur disponible.</span>";
usernameMessage.style.display = "flex";
document.getElementById('submit-button').disabled = false;
} else if (response === "Ce nom d'utilisateur est déjà pris.") {
usernameMessage.innerHTML = "<span style='color:red;'>Ce nom d'utilisateur est déjà pris.</span>";
usernameMessage.style.display = "flex";
document.getElementById('submit-button').disabled = true;
} else {
// gérer d'autres réponses ici
}
}
};
xhr.send("username=" + username);
}
</script>
PHP and MySQL :
<?php
session_start();
// Connexion à la base de données
include "./config.php";
// Vérification de la connexion
if ($mysqli->connect_errno) {
echo "Erreur de connexion à la base de données: " . $mysqli->connect_error;
exit();
}
// Récupération du nom d'utilisateur envoyé en POST
$username = $_GET['username'];
// Requête SQL pour vérifier si le nom d'utilisateur est déjà pris
$query = "SELECT COUNT(*) as count FROM users WHERE username = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->bind_result($count);
$stmt->fetch();
$stmt->close();
// Vérification du résultat
header('Content-Type: application/json');
if ($count > 0) {
echo "<div class='usernameMessage no'>Ce nom d'utilisateur est déjà pris.</div>";
echo "<script> document.getElementById('submit-button').disabled = true; </script>";
} else {
echo "<div class='usernameMessage yes'>Ce nom d'utilisateur est disponible.</div>";
echo "<script> document.getElementById('submit-button').disabled = false; </script>";
}
// Fermeture de la connexion à la base de données
$mysqli->close();
?>
<style>
.usernameMessage {
}
.yes{
color: green;
}
.no {
color: red;
}
</style>
I tried to put
document.getElementById('submit-button').disabled = false;
but it doesn't work, maybe because something is enabling my button ...

There are many flaws in your code.
You are using $_GET method in PHP code but $_POST method in Javascript code.
PHP code response does not seem to adapt to Javascript code
Here is the corrected code
HTML
<input onkeyup="checkUsername()" id="username" name="username" type="text" class="form-control" value="<?php echo $row['username'] ?>" placeholder="Nom d'utilisateur" required autocomplete="off">
<div id="usernameMessage"></div>
<button type="submit" id="submit-button" disabled>Submit</button>
JavaScript:
function checkUsername() {
const username = document.getElementById("username").value;
const xhr = new XMLHttpRequest();
xhr.open("POST", "check_username.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
const response = JSON.parse(xhr.responseText);
const usernameMessage = document.getElementById("usernameMessage");
if (response.available) {
usernameMessage.innerHTML = "<span style='color:green;'>Nom d'utilisateur disponible.</span>";
usernameMessage.style.display = "flex";
document.getElementById('submit-button').disabled = false;
} else {
usernameMessage.innerHTML = "<span style='color:red;'>Ce nom d'utilisateur est déjà pris.</span>";
usernameMessage.style.display = "flex";
document.getElementById('submit-button').disabled = true;
}
}
};
if (username.trim() !== '') {
xhr.send("username=" + username);
}
}
PHP:
session_start();
// Connexion à la base de données
include "./config.php";
// Vérification de la connexion
if ($mysqli->connect_errno) {
echo json_encode(['error' => "Erreur de connexion à la base de données: " . $mysqli->connect_error]);
exit();
}
// Récupération du nom d'utilisateur envoyé en POST
if (isset($_POST['username'])) {
$username = $_POST['username'];
// Requête SQL pour vérifier si le nom d'utilisateur est déjà pris
$query = "SELECT COUNT(*) as count FROM users WHERE username = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("s", $username);
if ($stmt->execute()) {
$stmt->bind_result($count);
$stmt->fetch();
$stmt->close();
// Vérification du résultat
if ($count > 0) {
echo json_encode(['available' => false]);
} else {
echo json_encode(['available' => true]);
}
} else {
echo json_encode(['error' => "Erreur lors de l'exécution de la requête SQL."]);
}
} else {
echo json_encode(['error' => "Le paramètre 'username' n'a pas été fourni."]);
}

Related

How to incorporate jquery datatables with PHP and external Javascript

I am new to programming and I don´t have much experience, recently i have been following this tutorial on how to create a server side search form with PHP and Javascript. The forms
works fine as is but I would like to displaying the using jquery datatables instead.
Can someone demostrate how I can incorporate the datatables into this code please.
Thanks
<!DOCTYPE html>
<html>
<head>
<title>Pesquisar com PHP e Javascript</title>
</head>
<body>
<h1>List Countries</h1>
<span id="msg"></span>
<!-- inicio do formulario -->
<form id="form-pesquisar">
<label>Pesquisar: </label>
<input type="text" name="texto_pesquisar" placeholder="Pesquisar pelo termo?"><br /><br />
<input type="submit" id="btn-pesquisar" value="pesquisar" name="Pesquisarpais"><br /><br />
</form>
<!-- inicio do formulario -->
<span id="listar-paises"></span>
<script src="js/custom.js"></script>
</body>
</html>
<?php
// Incluir a conexão com o banco de dados
include_once "./conexao.php";
// Receber os dados do javascript
$dados = filter_input_array(INPUT_POST, FILTER_DEFAULT);
// Acesso o IF quando o campo pesquisar usuario possuir valor
if(!empty($dados\['texto_pesquisar'\])){
// Criar a variavle com o caracter "%" indicando que pode ter letras antes e depois do valor pesquisado
$name = "%" . $dados['texto_pesquisar'] . "%";
// Criar query pesquisar paises
$query_paises = "SELECT Code, Name, Continent, Region, SurfaceArea, IndepYear,
Population, LifeExpectancy, GNP, GNPOld, LocalName, GovernmentForm, HeadOfState, Capital, Code2
FROM country
WHERE Name LIKE :nome";
// Preparar a QUERY
$result_paises = $conn->prepare($query_paises);
// Substitui o link pelo valor que vem do formulario
$result_paises->bindParam(':nome', $name);
// Execcutar a query
$result_paises->execute();
// Recebe os dados dos paises
$listar_paises = "";
if(($result_paises) and ($result_paises->rowCount() !=0)){
while($row_pais = $result_paises->fetch(PDO::FETCH_ASSOC)){
// Extrair o array para imprimir atraves da chave no array
extract($row_pais);
// Imprimir o valor de cada coluna retornada do banco de dados
$listar_paises .= "Code: $Code<br>";
$listar_paises .= "Name: $Name<br>";
$listar_paises .= "Continent: $Continent<br>";
$listar_paises .= "Region: $Region<br>";
$listar_paises .= "SurfaceArea: $SurfaceArea<br>";
$listar_paises .= "IndepYear: $IndepYear<br>";
$listar_paises .= "Population: $Population<br>";
$listar_paises .= "LifeExpectancy: $LifeExpectancy<br>";
$listar_paises .= "GNP: $GNP<br>";
$listar_paises .= "GNPOld: $GNPOld<br>";
$listar_paises .= "LocalName: $LocalName<br>";
$listar_paises .= "GovernmentForm: $GovernmentForm<br>";
$listar_paises .= "HeadOfState: $HeadOfState<br>";
$listar_paises .= "Capital: $Capital<br>";
$listar_paises .= "Code2: $Code2<br>";
$listar_paises .= "<hr>";
}
// Criar o array de informações que sera retornado para o javascript
$retorna = ['status' => true, 'dados' => $listar_paises];
}else{
// Criar o array de informações que será retornando para o javascript
$retorna = ['status' => false, 'msg' => "<p style='color: #f00;'>Erro: Nenhum pais encontrado!</p>"];
}
}else{
// Criar o array de informações que será retornando para o javascript
$retorna = \['status' =\> false, 'msg' =\> "\<p style='color: #f00;'\>Erro: Nenhum pais encontrado!\</p\>"\];
}
// Converter o array em objeto e retornar para o javascript
echo json_encode($retorna);
?>
// Reeceber o selector form-pesquisar
const formPesquisar = document.getElementById("form-pesquisar");
// Verificar se existe o form-pesquisar
if(formPesquisar){
//Aguardar o submit, quando o usuario clicar no botão executa a função
formPesquisar.addEventListener("submit", async (e) => {
// Bloquear para não recarregar a pagina
e.preventDefault();
// Substituir o texto do botão para pesquisando
document.getElementById("btn-pesquisar").value = "pesquisando...";
// Receber os dados do formulario
const dadosForm = new FormData(formPesquisar);
/*for(var dadosFormPesq of dadosForm.entries()){
console.log(dadosFormPesq[0] + " - " + dadosFormPesq[1]);
}*/
// Fazer a requisição para o arquivo pesquisar.php
const dados = await fetch("pesquisar.php", {
method: "POST",
body: dadosForm
});
// Ler os dados retornado do arquivo pesquisar.php
const resposta = await dados.json();
//console.log(resposta);
// Acessa o IF quando não retornar nenhum pais do banco de dados
if(!resposta['status']){
// Enviar a mensagem de erro do javascript para o HTML
document.getElementById("msg").innerHTML = resposta['msg'];
}else{
// Subsituir a mensagem de erro
document.getElementById("msg").innerHTML = "";
// Enviar a lista dos paises do javascript para o HTML
document.getElementById("listar-paises").innerHTML = resposta['dados'];
}
// Substituir o texto do botão para pesquisar
document.getElementById("btn-pesquisar").value = "Pesquisar";
});
}

I can't figure out my JavaScript function is not working

I have to create a game where the user has to guess a number, for that I call a JavaScript function on an external file which is activated when the button is clicked.
My HTML:
`
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Devoir JavaScript</title>
</head>
<body>
<p>Vous devez trouver un nombre compris entre 1 et 100 !</p>
<form name="myForm" method="POST"></form>
Nombre : <input type="text" name="nombre" value="" />
<input type="button" onclick="return verif()" value="Jouer" />
</form>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
`
My JavaScript:
var numero = Math.floor(Math.random() * 100) + 1;
var essai = 0;
function verif() {
essai++;
var choix = document.forms["myForm"]["choix"].value;
if (choix == null || choix == "") {
alert("Indiquer un nombre !");
return false;
}
if (choix < numero) {
alert = "Le nombre indiquer est trop petit !";
return false;
}
if (choix > numero) {
alert = "Le nombre indiquer est trop grand !";
return false;
}
if (choix == numero) {
alert = "Bravo vous avez trouver en " + essai + "essais !";
return true;
}
}
I have checked the name of my files and their extentions so as not to make a mistake.
I don't understand or I made a mistake.
PS: I am new to JavaScript.
I have been looking since yesterday so thank you for your help.
I tried running your code and inside Console it says the value could not be read. I slightly changed your Javascript code and it worked.
//var choix = document.forms["myForm"]["choix"].value; code before
var choix = document.getElementsByName("nombre").value; //after changed
When using Javascript if your code is not running, you should press F12 and look at the Console to see what your code is failing.
This is the full code that I changed:
var numero = Math.floor(Math.random() * 100) + 1;
var essai = 0;
function verif() {
essai++;
var choix = document.getElementsByName("choix").value;
document.write(choix);
if (choix == null || choix == "") {
alert("Indiquer un nombre !");
return false;
}
if (choix < numero) {
alert = "Le nombre indiquer est trop petit !";
return false;
}
if (choix > numero) {
alert = "Le nombre indiquer est trop grand !";
return false;
}
if (choix == numero) {
alert = "Bravo vous avez trouver en " + essai + "essais !";
return true;
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Devoir JavaScript</title>
</head>
<body>
<p>Vous devez trouver un nombre compris entre 1 et 100 !</p>
<form name="myForm" method="POST"></form>
Nombre : <input type="number" name="choix" value=""/>
<input type="button" onclick="return verif()" value="Jouer" />
</form>
</body>
</html>
Your error says that you are accessing the property value from undefined.
There is no "choix" in your HTML.
You can use indices to get your particular element value:
var choix = document.forms[0].elements[0].value;
Or keeping the same approach as yours, I can use the correct field "nombre" :
var choix = document.forms["myForm"]["nombre"].value;

How to visit all URLs from a website without perfomances issues

I am actually trying to build a website similar to this one :
https://robhammond.co/tools/seo-crawler
The concept is simple, you enter an URL of a website, and it follows every link you have inside it, in order to see if there is dead links.
I tried to do it recursively: looking at one page, find links, and look for each link I found, finds links on each page, etc.
I made an array of already visited links, so I won't check pages I've already checked.
Here is my code, I'm using a recursive ajax call to a PHP file that uses cURL, to get the error code, and find all the links inside it. After that, I make another ajax call for each link that is found.
Here is my code:
My html/javascript file :
<?php
session_start();
$_SESSION['visitedLinks'] = [];
?>
<html lang="fr">
<header>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<title>Kaiman Crawler</title>
</header>
<body>
<form id="form" method="post" action="">
<label>
Veuillez saisir l'URL du site à scanner :
<input type="text" id='url' value="https://php.net/" required/>
</label>
<input type="submit" value="Scanner"/>
</form>
<p>Attention: Les pages avec plus de 200 liens ne seront pas traitées</p>
<table class="table" hidden>
<thead>
<tr>
<th scope="col"></th>
<th scope="col">URL</th>
<th scope="col">Titre de la page</th>
<th scope="col">Statut</th>
<th scope="col">Signification</th>
<th scope="col">Nombre de liens sur la page</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
var cpt =1;
var request = 0;
var baseURL;
function signification(code){
switch (code) {
// TODO: Continuer les codes d'erreur
case 200:
return "Accessible";
case 404:
return "Page introuvable";
}
}
function scanPage(url) {
$.ajax({
url: 'getURLs.php',
dataType:'json',
type:'POST',
data:{
URL: url
}
}).done(function (data) {
console.log(data);
if (data['success']) {
$('tbody').append('<tr id="' + cpt + '"></tr>');
$('#' + cpt).append("<td>" + cpt++ + "</td>")
.append("<td>" + data['page'].url + "</td>")
.append("<td>" + data['page'].titre + "</td>")
.append("<td>" + data['page'].code + "</td>")
.append("<td>" + signification(data['page'].code) + "</td>")
.append("<td>" + data['page']['pages'].length + "</td>");
for (let i = 0; i < data['page']['pages'].length; ++i) {
if (data['page']['pages'].length >= 200){
break;
}
if (!data['links'].includes(data['page']['pages'][i]) && data['links'].includes(baseURL)) {
console.log(++request);
scanPage(data['page']['pages'][i]);
}
}
}
});
}
$('#form').submit(function (){
$('table').attr('hidden',false);
baseURL = $('#url').val();
$('thead').empty();
scanPage($('#url').val());
return false;
});
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
</script>
</body>
</html>
My php file :
<?php
session_start();
require_once __DIR__ . '/Page.php';
$baseURL = $_POST['URL'];
$baseURL = explode('/',$baseURL,4);
$nomPage = $baseURL[3];
$baseURL = $baseURL[0] . "//". $baseURL[2] . '/';
$data = new stdClass();
$data->success = true;
$result = showLinks($baseURL,$nomPage);
if ($result === false){
$data->success = false;
}
else {
$data->page = $result;
$data->links = $_SESSION['visitedLinks'];
}
echo json_encode($data);
function showLinks($baseURL,$nomPage = "") {
if (!array_search($baseURL.$nomPage,$_SESSION['visitedLinks'])){
$result = fread_url($baseURL.$nomPage);
$var = $result[1];
$code = curl_getinfo($result[0], CURLINFO_HTTP_CODE);
$title = get_html_title($var);
array_push($_SESSION['visitedLinks'],$baseURL.$nomPage);
$page = new Page($baseURL . $nomPage, $title, $code);
preg_match_all("/a[\s]+[^>]*?href[\s]?=[\s\"\']+" .
"(.*?)[\"\']+.*?>" . "([^<]+|.*?)?<\/a>/",
$var, $matches);
$matches = $matches[1];
foreach ($matches as $var1) {
if (strlen($var1) >= 1) {
// si il ne s'agit pas d'une référence sur place ou à la racine
if ($var1[0] !== "#" && $var1 !== "/" && $var[0] !== "." && $var[0] !== "?" && $var[0] !== "%") {
// Si le dernier caractère n'est pas un /, l'ajouter
if ($var1[strlen($var1) - 1] !== "/") {
$var1[strlen($var1)] = "/";
}
// Si il s'agit d'un chemin absolu
if ($var1[0] === '/') {
$var1 = ltrim($var1, $var1[0]);
$page->addChild($baseURL . $var1);
} // Si il s'agit d'un chemin relatif
else if (strpos($var1, "http://") === false && strpos($var1, 'https://') === false && strpos($var1, 'www.') === false) {
$page->addChild($baseURL . $nomPage . $var1);
} // Sinon, si il s'agit d'une url
else {
$page->addChild($var1);
}
}
}
}
return $page;
}
else return false;
}
function fread_url($url,$ref="") {
$user_agent = "Mozilla/4.0 (compatible; MSIE 5.01; ".
"Windows NT 5.0)";
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
curl_setopt( $ch, CURLOPT_HTTPGET, 1 );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION , 1 );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION , 1 );
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_REFERER, $ref );
curl_setopt ($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
$html = curl_exec($ch);
return [$ch,$html];
}
function get_html_title($html){
preg_match("/\<title.*\>(.*)\<\/title\>/isU", $html, $matches);
return $matches[1];
}
And finally, my Page class
<?php
class Page implements JsonSerializable {
private $url;
private $titre;
private $code;
private $pages = array();
public function __construct($url,$titre,$code) {
$this->titre = $titre;
$this->url = $url;
$this->code = $code;
}
public function addChild ($child){
array_push($this->pages,$child);
}
/**
* Specify data which should be serialized to JSON
* #link https://php.net/manual/en/jsonserializable.jsonserialize.php
* #return mixed data which can be serialized by <b>json_encode</b>,
* which is a value of any type other than a resource.
* #since 5.4.0
*/
public function jsonSerialize(){
return [
'url' => $this->url,
'titre' => $this->titre,
'code' => $this->code,
'pages' => $this->pages
];
}
}
Actually, this does work on Firefox, but it's using many resources. Plus, on Chrome, I get an ERR_INSUFFICIENT_RESOURCES on the console after some time on big websites.
So I'm asking you, is there a better way to optimize my code?
Thanks for your help.

JavaScript setInterval() and setTimeout() freezing browser

I'm woking in a mobile friendly monitoring tool based on rrdtool.
All working fine but when I have the webpage opened for more that 1 hour freezes my computer.
I use this snippet for refresh the images.
<?php
if(!isset($includeCheck))
{
exit ("No tienes permisos para ver directamente el archivo");
}
//echo "
//<script language='JavaScript'>
// function refreshIt(element) {
// setTimeout(function() {
// element.src = element.src.split('?')[0] + '?' + new Date().getTime();
// refreshIt(element);
// }, 50000);
// }
//</script>";
echo "
<script language='JavaScript'>
function refreshIt(element){
setInterval(function() {
element.src = element.src.split('?')[0] + '?' + new Date().getTime();
}, 50000);
}
</script>";
?>
I include this php file in the pages what I have images and I want to refresh.
I tried the 2 options but as I said, freezes my browser.
Anyone have idea what can I do? Because I need refresh the images only, I don't want to refres the whole page.
EDIT
Here is the PHP script for print all images in database.
<?php
if(!isset($includeCheck))
{
exit ("No tienes permisos para ver directamente el archivo");
}
if(isset($_GET['freq'])){
$freq = $_GET['freq'];
$title = 'Gráficas';
} else {
exit ("No has especificado la frecuencia");
}
if($freq == "hourly"){
$title = 'Tráfico última hora';
}
if($freq == "daily"){
$title = 'Tráfico último dia';
}
if($freq == "weekly"){
$title = 'Tráfico última semana';
}
if($freq == "monthly"){
$title = 'Tráfico último mes';
}
if($freq == "yearly"){
$title = 'Tráfico último año';
}
if(isset($_GET['limit'])){
$limit = $_GET['limit'];
} else {
$limit="10";
}
if(isset($_GET['inicio'])){
$inicio = $_GET['inicio'];
}
if(isset($_GET['subpage'])){
$subpage = $_GET['subpage'];
if ($subpage==1) {
$inicio=0;
}
} else {
$subpage = "1";
$inicio="0";
}
$total_records = $conn->query("SELECT graph_id FROM graph_".$freq)->num_rows;
$total_pages = ceil($total_records / $limit);
$sql = "SELECT graph_desc,graph_id,graph_name FROM graph_".$freq." ORDER BY graph_desc ASC LIMIT ".$limit." OFFSET ".$inicio.";";
$result = $conn->query($sql);
include_once 'adm/includes/pagination.php';
echo "<h1 id='titulo' class=\"page-header\">".$title."</h1>";
include_once 'adm/includes/refresh.php';
if ($total_pages != '1') {
echo "<div id='pager1' class='col-md-12'>";
echo $pagLink;
echo "</div>";
}
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "
<div class='graphSize' style='float:left; position:relative; z-index: 10;'>
<a href='?page=GraphDetail&graph_id=".$row['graph_id']."&graph_desc=".$row['graph_desc']."'>
<img style='width:100%' src='/graficas/".$freq."/".$row['graph_name']."' onload='refreshIt(this)'></img>
</a>
</div>
";
}
}
else {
echo "<p>No hay ninguna gráfica para mostrar</p>"; }
if ($total_pages != '1') {
echo "<div id='pager2' class='col-md-12'>";
echo $pagLink;
echo "</div>";
}
echo "</body>";
if(isset($_GET['fullscreen'])){
echo "<style>";
echo ".graphSize {";
echo "width:500px;";
echo "}";
echo "</style>";
}
$conn->close();
You have this onload handler for your image:
refreshIt(this)
...and that sets an interval (meaning it will repeat) every 50 seconds. The callback for that interval sets the src for the image, which means that onload will once again trigger, and you'll again do a set interval. So each time a new version of the image loads, you add another interval, so eventually you'll have tons of duplicating callbacks occurring.
You probably want to use setTimeout, or call refreshIt(this) once, not on every onload.

bug using session and jquery

In login and register php functions I'm using this line:
$_SESSION['username'] = $username;
If in jquery function I use username as var the session changes and Im not using sessions on jquery functions
For example I have a feed burner so I have 2 records for the feed number and email.
Im using as:
var nombre = $('#nombre').val();
var email = $('#email').val();
$.post(global_data.url + 'files/assets/php/ajax/feed.php', 'nombre=' + nombre + '&email=' + email, function(a){
I'm not having problemas with the session but if I change nombre for username like this:
var username = $('#username').val();
var email = $('#email').val();
$.post(global_data.url + 'files/assets/php/ajax/feed.php', 'username=' + username + '&email=' + email, function(a){
The session changes
This is my feed.php code:
require('../../../inc/config.php');
require('../../../libs/Plantilla.class.php');
$plantilla = new plantilla($serv,$user,$pass,$base,$url,$sitio);
$conexion = mysqli_connect($serv,$user,$pass,$base);
if ($_POST) {
$nombre = $Main->limpiar($_POST['nombre']);
$email= $Main->limpiar($_POST['email']);
if(isset($nombre) && !empty($nombre) && isset($email) && !empty($email)){
$hash = md5($nombre.$email);
$mysqli = $conexion;
$porter = $mysqli->query("SELECT * FROM feed where username = '$nombre' or email = '$email'");
if($porter->num_rows ==0){
if($mysqli->query('INSERT INTO `feed` (username, email, hash) VALUES (\''.$nombre.'\', \''.$email.'\', \''.$hash.'\')')){
die('1: <div class="dialog_box">Gracias por suscribirse a nuestro boletin</div>');
}else{
die('0: <div class="dialog_box">Ocurrió un error.</div>');
}
}else{
die('0: <div class="dialog_box">Ya estas Sucrito.</div>');
}
}else{
die('0: <div class="dialog_box">Por favor completa todos los campos</div>');
}
}else{
echo "<h1>404</h1>";
}
config.php
//Inicio de sesión
#session_start();
//Mostramos errores
error_reporting(E_ALL ^ E_WARNING ^ E_NOTICE ^ E_DEPRECATED);
ini_set('display_errors', TRUE);
//Definimos timezone
setlocale(LC_ALL,"es_ES");
date_default_timezone_set('America/Mexico_City');
define('ROOT_DIRECTORY', dirname(dirname(__FILE__)).'/');
//Datos MYSQL
$serv = "localhost";
$user = "angela";
$pass = "1q2w3e";
$base = "angela";
//conectamos..
$conexion_temporal = mysqli_connect($serv,$user,$pass,$base);
mysqli_set_charset("utf8");
if(!$conexion_temporal){
exit('<title>Error</title><body style="clear: both;background: #F6F6F6;padding: 2em 2em 1em;border: 1px solid #E7E7E7;-moz-border-radius: 5px;-webkit-border-radius: 5px;-o-border-radius: 5px;border-radius: 5px;"><h2 align="center" style="color:#222; font-size:25px; font-family:Century Gothic;">Error <br /><br />No se pudo establecer la conexión a la base de datos </h2></body>');
}
//Datos del sitio
$mysqli = $conexion_temporal;
$query = $mysqli->query('select * from config');
while ($row = $query->fetch_assoc()){$url = $row['url'];
$title = $row['title'];
$sitio = $row['sitio'];
$max_size = $row['max_size'];
$paypal = $row['email'];
}
//configuraciones extras
$PermitirImprecion = TRUE;
require(ROOT_DIRECTORY . '/libs/Main.class.php');
$Main = new Main($serv,$user,$pass,$base,$url,$sitio);
//json
function setJSON($data, $type = 'encode'){
require_once('JSON.php'); // INCLUIMOS LA CLASE
$json = new Services_JSON; // CREAMOS EL SERVICIO
if($type == 'encode') return $json->encode($data);
elseif($type == 'decode') return $json->decode($data);
}
$pfooter='fCBEZXZlbG9wZWQgYnkgPGEgaHJlZj0iaHR0cHM6Ly93d3cuZGF0dGFzb2x1dGlvbnMuY29tLm14
Lz9yZWY9c2l0ZV9hbmdlbGFtZWRpbmFfbXgiIHRhcmdldD0iYmxhbmsiPkRhdHRhIFNvbHV0aW9u
czwvYT4=';
$footer = base64_decode($pfooter);

Categories