Ir para conteúdo
Fórum Script Brasil

Edu Valente

Membros
  • Total de itens

    31
  • Registro em

  • Última visita

Tudo que Edu Valente postou

  1. Tudo funciona corretamente ao executar a aplicação porém, uma mensagem de erro pedindo para inserir a data no formato mm/dd/yyyy aparece quando o usuário clica no botão "retornar" no browser e não sei o porquê que isso acontece. Já tentei algumas alterações no cód. mas a mensagem de erro continua aparecendo quando clico no botão de "retornar".
  2. Boa noite a todos. Eu gostaria de pedir uma solução para o problema da mensagem de validação que aparece quando se retorna uma página mesmo que os dados inseridos estejam corretos. O que acontece quando o usuário aperta no botão para retornar uma página no que diz respeito ao PHP e essas mensagens de validação que aparecem indevidamente. Existe uma solução definitiva pra isso? por exemplo: "faz isso que quando você pedir para retornar, a mensagem de validação não vai mais aparecer." Muito obrigado pelo esclarecimento. Segue abaixo o cód. bugado: index.php <?php if (empty($_POST['action'])) { $action = 'start_app'; } else { $action = $_POST['action']; } switch ($action) { case 'start_app': // set default invoice date 1 month prior to current date $interval = new DateInterval('P1M'); $default_date = new DateTime(); $default_date->sub($interval); $invoice_date_s = $default_date->format('m/d/Y'); // set default due date 2 months after current date $interval = new DateInterval('P2M'); $default_date = new DateTime(); $default_date->add($interval); $due_date_s = $default_date->format('m/d/Y'); $message = 'Enter two dates and click on the Submit button.'; break; case 'process_data': $message = ''; $invoice_date_s = $_POST['invoice_date']; $due_date_s = $_POST['due_date']; $invoice_date_ex = explode('/', $invoice_date_s); $invoice_date_im = implode('', $invoice_date_ex); $due_date_ex = explode('/', $due_date_s); $due_date_im = implode('', $due_date_ex); // make sure the user enters both dates if(empty($invoice_date_s)) { $message = 'Please fill in the first field'; } else if(empty($due_date_s)) { $message = 'Please fill in the second field'; } else if(strpos($invoice_date_s, '/', 1) != 2 || strpos($invoice_date_s, '/', 4) != 5 || strpos($due_date_s, '/', 1) != 2 || strpos($due_date_s, '/', 4) != 5 || strlen($invoice_date_im) != 8 || strlen($due_date_im) != 8) { $message = 'Please enter the dates with the format mm/dd/yyyy'; } // the year limit is 2012 else if($invoice_date_ex[2] > 2020 || $invoice_date_ex[2] < 2011 || $due_date_ex[2] > 2020 || $due_date_ex[2] < 2011) { $message = 'Enter a year with the format yyyy between 2011 and 2020'; } // convert date strings to DateTime objects // and use a try/catch to make sure the dates are valid else{ try{ $invoice_date = new DateTime($invoice_date_s); $due_date = new DateTime($due_date_s); } catch(Exception $e) { ?> <p style = "font-weight: bold; font-size: 16px;"><?php echo 'Error: Enter valid dates inside the fields.'; ?></p> <?php exit(1); } // make sure the due date is after the invoice date if($invoice_date > $due_date) { $message = 'The due date must be later the invoice date'; } // format both dates $invoice_date_f = $invoice_date->format('M d, Y'); $due_date_f = $due_date->format('M d, Y'); // get the current date and time and format it $now = new DateTime(); $current_date_f = $now->format('M d, Y'); $current_time_f = $now->format('H:i:s a'); // get the amount of time between the current date and the due date // and format the due date message if($due_date > $now) { $dateInterval = $now->diff($due_date); $due_date_message = 'this invoice is due in ' . $dateInterval->format('%y years, %m months and %d days') . '.'; } else if($due_date <= $now) { $dateInterval = $due_date->diff($invoice_date); $due_date_message = 'this invoice is ' . $dateInterval->format('%y years, %m months and %d days') . ' overdue.'; } } break; } include 'date_tester.php'; ?> date_tester.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Date Tester</title> <link rel="stylesheet" type="text/css" href="main.css"/> </head> <body> <div id="content"> <h1>Date Tester</h1> <form action="." method="post"> <input type="hidden" name="action" value="process_data"/> <label>Invoice Date:</label> <input type="text" name="invoice_date" value="<?php echo htmlspecialchars($invoice_date_s); ?>"/> <br /> <label>Due Date:</label> <input type="text" name="due_date" value="<?php echo htmlspecialchars($due_date_s); ?>"/> <br /> <label> </label> <input type="submit" value="Submit" /> <br /> </form> <h2>Message:</h2> <?php if ($message != '') : ?> <p><?php echo $message; ?></p> <?php else : ?> <table cellspacing="5px"> <tr> <td>Invoice date:</td> <td><?php echo $invoice_date_f; ?></td> </tr> <tr> <td>Due date:</td> <td><?php echo $due_date_f; ?></td> </tr> <tr> <td>Current date:</td> <td><?php echo $current_date_f; ?></td> </tr> <tr> <td>Current time:</td> <td><?php echo $current_time_f; ?></td> </tr> <tr> <td>Due date message:</td> <td><?php echo $due_date_message; ?></td> </tr> </table> <?php endif; ?> </div> </body> </html> main.css body { font-family: Arial, Helvetica, sans-serif; } #content { width: 450px; margin: 0 auto; padding: 20px 20px 30px; background: white; border: 2px solid navy; } h1 { color: navy; } h2 { margin: 0; padding: .25em 0; } p { margin: 0; } label { width: 8em; float: left; margin-right: 1em; margin-bottom: .25em; } input { float: left; margin-bottom: .2em; } br { clear: both; }
  3. Com a sua ajuda percebi que eu estava me contradizendo. O que estava ocorrendo era um erro de lógica. Eu fiz uma verificação com empty no código do display_results e empty retorna true se o valor for zero, '', false ou nul então a mensagem de erro sempre aparecerá se eu atribuir 0 a $years. Conclusão: inicializar a variável com 0 e testá-la com empty nunca vai dar certo :P Obrigado.
  4. Boa tarde. Eu tenho um arquivo php que valida a entrada do usuário quando este insere a quant. de anos de investimento. Quando o usuário não insere a quant. de anos correta, é impressa a mensagem "years is a required field". Esta mensagem aparece quando eu insiro um número para "years", clico para enviar e volto a esta página. Gostaria de fazer com que a mensagem desaparecesse ao retornar à página inicial. Já tentei fazer isso inicializando novamente o valor de $error_message mas não deu certo. <?php // variables initialization if(empty($_POST['years'])) { $years = 0; } else { $years = $_POST['years']; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Future Value Calculator</title> <link rel="stylesheet" type="text/css" href="main.css"/> </head> <body> <div id="content"> <h1>Future Value Calculator</h1> <?php if (!empty($error_message)) { ?> <p class="error"><?php echo $error_message; ?></p> <?php } // end if ?> <form action="display_results.php" method="post"> <div id="data"> <label>Investment Amount:</label> <select name = "investment" id = "investment"> <?php for($i = 10000; $i <= 50000; $i += 10000) { ?> <option value = "<?php echo $i; ?>">$<?php echo $i; ?></option> <?php } ?> </select> <label>Interest Rate:</label> <select name = "interest_rate" id = "interest_rate"> <?php for($i = 4; $i <= 12; $i += .5) { ?> <option value = "<?php echo $i; ?>"><?php echo $i; ?>%</option> <?php } ?> </select> <label>Number of Years:</label> <input type="text" name="years" value="<?php echo $years; ?>"/><br /> <!-- <label>Investment Amount:</label> <input type="text" name="investment" value=" "/><br /> <label>Yearly Interest Rate:</label> <input type="text" name="interest_rate" value=" "/><br /> --> </div> <div id="buttons"> <label> </label> <input type="submit" value="Calculate"/><br /> </div> </form> </div> </body> </html> <?php // get the data from the form $investment = $_POST['investment']; $interest_rate = $_POST['interest_rate']; $years = $_POST['years']; // validate investment entry // these statements work incorrectly with a drop-list /* if ( empty($investment) ) { $error_message = 'Investment is a required field.'; } else if ( !is_numeric($investment) ) { $error_message = 'Investment must be a valid number.'; } else if ( $investment <= 0 ) { $error_message = 'Investment must be greater than zero.'; // validate interest rate entry } else if ( empty($interest_rate) ) { $error_message = 'Interest rate is a required field.'; } else if ( !is_numeric($interest_rate) ) { $error_message = 'Interest rate must be a valid number.'; } else if ( $interest_rate <= 0 ) { $error_message = 'Interest rate must be greater than zero.'; // set error message to empty string if no invalid entries */ if(!is_numeric($years)) { $error_message = 'Years must be a valid number'; } else if(empty($years)) { $error_message = 'Years is a required field'; } else { $error_message = ''; } // if an error message exists, go to the index page if ($error_message != '') { include('index.php'); exit(); } // calculate the future value $future_value = $investment; for ($i = 1; $i <= $years; $i++) { $future_value = ($future_value + ($future_value * $interest_rate *.01)); } // apply currency and percent formatting $investment_f = '$'.number_format($investment, 2); $yearly_rate_f = $interest_rate.'%'; $future_value_f = '$'.number_format($future_value, 2); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Future Value Calculator</title> <link rel="stylesheet" type="text/css" href="main.css"/> </head> <body> <div id="content"> <h1>Future Value Calculator</h1> <label>Investment Amount:</label> <span><?php echo $investment_f; ?></span><br /> <label>Yearly Interest Rate:</label> <span><?php echo $yearly_rate_f; ?></span><br /> <label>Number of Years:</label> <span><?php echo $years; ?></span><br /> <label>Future Value:</label> <span><?php echo $future_value_f; ?></span><br /> </div> </body> </html>
  5. Ótima observação Romerito, eu não consegui enxergar isso. Além do mais, eu não sabia que o documento deixava de existir quando o método write era chamado. Muito obrigado :) .
  6. Boa tarde gente. A dúvida é a seguinte: Por que elem2.nodeName está retornando null quando o script é executado? eu achei que o elemento <select> que tem como id "magazines" seria retornado. Eu tenho um select com um id = "magazines" e digitei: var elem2 = $("magazines"); quando chamei nodeName como elem2.nodeName , me foi retornado null. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <link href = "magazine.css" rel = "stylesheet" type = "text/css" /> &lt;script src = "magazine.js" type = "text/javascript"></script> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Magazines</title> </head> <body> <div id = "content"> <h1>Magazine Subscribing</h1> <form> <p><label for = "name">Name:</label> <input type = "text" id = "name" /> <span class = "error" id = "nameError"></span> </p> <p><label for = "email">Email:</label> <input type = "email" id = "email" /> <span class = "error" id = "emailError"></span> </p> <p> <label for = "age">Age:</label> <input type = "text" id = "age" size = "2" maxlength = "2" /> <span class = "error" id = "ageError"></span> </p> <input type = "radio" name = "gender" id = "male" value = "male" /> Male <span class = "error" id = "genderError"></span><br /> <input type = "radio" name = "gender" id = "female" value = "female" /> Female <p> <select name = "magazines" id = "magazines" multiple = "multiple"> <optgroup label = "Science"> <option value = "sciam">Scientific American</option> <option value = "nature">Nature</option> <option value = "science">Science</option> </optgroup> <optgroup label = "Technology"> <option value = "wired">Wired</option> <option value = "arstechnica">Ars Technica</option> <option value = "javabox">Java Box</option> </optgroup> </select> <span class = "error" id = "magazineError"></span> </p> <p><input type = "checkbox" name = "newsletter" id = "newsletter" /> Check if you want to subscribe for our newsletter</p> <p><textarea name = "signatures" id = "signatures" rows = "7" cols = "40"></textarea></p> <label> </label> <input type = "button" id = "subscribe" value = "subscribe" /> </form> </div> </body> </html> // JavaScript Document var $ = function(id) { return document.getElementById(id); } var DOMTest = function() { var node; var elem1 = $("name"); document.write("Node name: " + elem1.nodeName + "<br>"); // INPUT document.write("Node type: " + elem1.nodeType + "<br>"); // 1 document.write("Node value: " + elem1.nodeValue + "<br>"); // null document.write("Parent node: " + elem1.parentNode + "<br>"); // <p> document.write("Child nodes of " + elem1.nodeName + ":<br>"); for(var i = 0; i < elem1.childNodes.length; i++) { node = elem1.childNodes[i]; document.write(node.nodeName + "<br>"); } document.write("<br>"); var elem2 = $("magazines"); document.write("Child nodes of " + elem2.nodeName + ":<br>"); // dá erro nessa linha dizendo que elem2 é null. Mas porquê? for(var i = 0; i < elem2.childNodes.length; i++) { node = elem2.childNodes[i]; document.write(node.nodeName + "<br>"); } } window.onload = DOMTest;
  7. Boa tarde gente. Eu criei um padrão em regex para telefone só que eu gostaria que o test de p7 retorna-se false. Eu não sei escrever um padrão para invalidar p7 mantendo os outros (de p1 a p6) válidos . Obrigado pela ajuda. var patternMatch = function() { var p1 = "11111111"; var p2 = "1111-1111"; var p3 = "1111 1111"; var p4 = "(21)11111111"; var p5 = "(21)1111 1111"; var p6 = "(21)1111-1111"; var p7 = "(21)1111 -1111"; document.write(/^(\d{4})|(\(\d{2}\)\d{4})(-{1}\d{4})|( ?\d{4})$/.test(p1) + "<br>"); document.write(/^(\d{4})|(\(\d{2}\)\d{4})(-{1}\d{4})|( ?\d{4})$/.test(p2) + "<br>"); document.write(/^(\d{4})|(\(\d{2}\)\d{4})(-{1}\d{4})|( ?\d{4})$/.test(p3) + "<br>"); document.write(/^(\d{4})|(\(\d{2}\)\d{4})(-{1}\d{4})|( ?\d{4})$/.test(p4) + "<br>"); document.write(/^(\d{4})|(\(\d{2}\)\d{4})(-{1}\d{4})|( ?\d{4})$/.test(p5) + "<br>"); document.write(/^(\d{4})|(\(\d{2}\)\d{4})(-{1}\d{4})|( ?\d{4})$/.test(p6) + "<br>"); document.write(/^(\d{4})|(\(\d{2}\)\d{4})(-{1}\d{4})|( ?\d{4})$/.test(p7) + "<br>"); } window.onload = patternMatch;
  8. Boa tarde gente. Eu estou tentando desenvolver uma árvore binária que tenha números complexos inseridos nela. Num certo trecho do código, tentei comparar a representação string de dois complexos sem êxito e agora não sei como fazer para comparar as duas strings propriamente ditas a fim de que eu possa localizar um complexo previamente inserido na árvore. Irei colocar os headers, os .c do código e um comentário em bintree.c indicando o problema. Obrigado pela ajuda proporcionada. complex.h typedef struct Complex { double r; double i; } complex; // cria um número complexo complex set(double x, double y); // retorna a parte real de um número complexo double getR(complex x); // retorna a parte imaginária de um número complexo double getI(complex x); // Retorna uma string que representa // o número complexo char* notation(complex x); bintree.h #include "complex.h" typedef struct Tree { complex info; struct Tree* left; struct Tree* right; } tree; // inicializa a árvore tree* initialize(void); // cria uma árvore com duas folhas (uma à esquerda e outra à direita) tree* create(complex c, tree* sae, tree* sad); // verifica se a árvore se encontra vazia int emptyTree(tree* a); // imprime os dados da árvore binária void printTreeData(tree* a); // libera a memória alocada à árvore binária tree* freeTree(tree* a); // obtém a altura da árvore int getTreeHeight(tree* t); // obtém o maior nodo da árvore int highestNode(int a, int b); // faz uma busca pelos elementos da árvore int searchElem(tree* t, complex c); complex.c #include <string.h> #include "complex.h" complex set(double x, double y) { complex z; z.r = x; z.i= y; return z; } double getR(complex x) { return x.r; } double getI(complex x) { return x.i; } char* notation(complex x) { static char s[30]; // printf é uma função que insere os caracteres formatados // na variável de destino (neste caso, s) sprintf(s, "%g + %gi", getR(x), getI(x)); return s; } bintree.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include "bintree.h" #include "complex.h" tree* initialize(void) { return NULL; } tree* create(complex c, tree* sae, tree* sad){ tree* p=(tree*)malloc(sizeof(tree)); p->info = c; p->left = sae; p->right = sad; return p; } int empty(tree* t) { return t == NULL; } void printTreeData(tree* t) { if (!emptyTree(t)){ printf("%s", t->info); /* mostra raiz */ printTreeData(t->left); /* mostra sae */ printTreeData(t->right); /* mostra sad */ } } tree* freeTree(tree* t){ if (!emptyTree(t)){ freeTree(t->left); /* libera sae */ freeTree(t->right); /* libera sad */ free(t); /* libera raiz */ } return NULL; } int getTreeHeight(tree* t) { if((t == NULL) || (t->left == NULL && t->right == NULL)) { return 0; } else { return 1 + highestLeaf(getTreeHeight(t->left), getTreeHeight(t->right)); } } int highestNode(int a, int b) { if(a > b) return a; else return b; } int searchElem(tree* t, complex c){ char* s1; // primeira variável para guardar a notação String de t->info char* s2; // segunda variável para guardar a notação String do complexo c if (emptyTree(t)) return 0; /* árvore vazia: não encontrou */ else s1 = notation(t->info); s2 = notation(c); return s1 == s2 || searchElem(t->left,c) || searchElem(t->right,c); /* ****************************************** * O problema se encontra nesse return: o compilador * retorna os seguintes erros para complex.h: * Linha 2 - redefinition of 'struct Complex' * Linha 6 - redefinition of 'typedef Complex' * Linha 6 - previous declaration of 'complex' was here * quando eu tento comparar essas duas representações * de string. * *******************************************/ } main.c #include <stdio.h> #include <stdlib.h> #include "complex.h" #include "bintree.h" int main(void) { complex a = set(4, 3); complex b = set(1, 2); complex c = set(5, 6); complex d = set(7, 8); complex e = set(9, 10); complex f = set(11, 12); complex g = set(13, 14); puts(notation(a)); int height, search; tree* t = create(a, create(b, initialize(), create(d, initialize(), initialize())), create(c, create(e, initialize(), initialize()), create(f, create(g,initialize(),initialize()), initialize()) ) ); height = getTreeHeight(t); search = searchElem(t, g); printf("Altura da arvore: %d\n", height); if(search == 1) printf("o elemento procurado se encontra na arvore.\n"); else printf("o elemento procurado não se encontra na arvore.\n"); system("PAUSE"); return 0; }
  9. Boa tarde gente. Eu estou tentando gerar miniaturas de uma imagem num PDF usando a biblioteca libPDF mas não estou conseguindo. Ambos o .php e a imagem estão na mesma pasta. Será que isso tem a ver com o fato de eu estar usando a versão não paga dessa lib ? Obrigado pela ajuda! <?php $p = new PDFlib(); if ($p->begin_document("", "") == 0) { die("Erro: " . $p->get_errmsg()); } $p->begin_page_ext(595, 842, ""); $im = $p->load_image("jpeg", "postgresql.jpg",""); if(!$im) { die("Erro: ".$p->get_errmsg()); } $p->fit_image($im, 20, 500, "scale 1"); $p->fit_image($im, 170, 500, "scale 0.75"); $p->fit_image($im, 280, 500, "scale 0.50"); $p->fit_image($im, 355, 500, "scale 0.25"); $p->fit_image($im, 395, 500, "scale 0.10"); $p->close_image ($im); $p->end_page_ext(""); $p->end_document(""); $buf = $p->get_buffer(); $tamanho = strlen($buf); header("Content-type:application/pdf"); header("Content-Length:$tamanho"); header("Content-Disposition:inline; filename=imagens.pdf"); echo $buf; ?> O seguinte erro está sendo retornado: Erro: Couldn't open image file 'postgresql.jpg' for reading (file not found) a lib está ativada e funciona para outros programas.
  10. eu uso o Dreamweaver e ele também configura a codificação como UTF-8 por padrão. :huh:
  11. Sim e o pior Stoma é que já estava como tu disseste: ambos os gds já tinham vindo habilitados. Não tem mais algum lugar que seja necessário habilitar o gd ? Tentarei continuar o estudo de gráficos e espero conseguir gerar o próximo. :unsure: haha consegui! eu deletei os dois arquivos e criei tudo do zero copiando os códigos do Stoma. E então o gráfico foi gerado usando o XAMPP! (eu eim?) O curioso que antes eu apenas deletei os códigos (sem apagar os arquivos propriamente ditos) e coloquei os códigos do Stoma. Fiquei perplexo com isso: deu certo só depois que apaguei os arquivos. Pessoal, eu não teria conseguido sem vocês! muito obrigado!
  12. No XAMPP eu estou tendo o mesmo problema que eu tive no EasyPHP. Para habilitar o GD é só habilitar essa linha não é ? extension=php_gd2.dll
  13. Eu tava tentando configurar o WAMP através do tutorial que o david me passou; Eu até consegui configurar configurar o Apache (num outro port sem ser o 80) mas quando eu instalei o .msi do PHP 5, o servidor do Apache deu erro dizendo "The requested operation has failed" e se eu tentar executá-lo pelo prompt, não aparece nenhuma mensagem de erro. Eu coloquei apontei o PHP para o diretório conf do Apache e também selecionei Apache 2.2 como o módulo a ser executado. Por favor David, você tem idéia de como resolver esse problema ? se nada der certo, eu vou tentar usar o XAMPP.
  14. Vou tentar instalar o WAMP segundo o tutorial que você me passou. ^_^
  15. Sim e mesmo assim não adiantou. : \ vou tentar usar outro aplicativo WAMP sem ser o EasyPHP. Vocês poderiam me indicar alguns ? obrigado gente por toda a força!
  16. Obrigado pela dica Romero. Já coloquei o link nos favoritos. Eu estou tentando gerar esse gráfico com o auxílio do EasyPHP porque eu transcrevi ele de um livro e estou achando muito estranho que ele não está sendo gerado mesmo com o extension do GD habilitado.
  17. No php.ini, eu já tinha esta instrução habilitada: extension=php_gd2.dll que é a instrução que habilita o GD né ? no Firefox aparece: " A imagem (caminho da imagem) contém erros e não pode ser exibida. " no Chrome aparece aquele símbolo de quando a imagem não aparece. o meu php.ini não tem a instrução "GD support" porém se eu consigo criar outras imagens (como a da estrela que citei no começo do tópico) é porque eu tenho o GD habilitado né ?
  18. Stoma eu tentei aqui mas não funcionou. Fiz todas as alterações que tu disseste: tirei todas as tags e renomeei o inc como config.inc.php . O que mais pode ser ? estou começando a achar que é algum problema de configuração num dos arquivos internos - como o php.ini - existe alguma variável que deve ser habilitada num desses arquivos ? eu estou usando o EasyPHP.
  19. Boa tarde pessoal. Estou tentando gerar um gráfico de pizza com um código mas a imagem não me é retornada. Já verifiquei duas vezes o código .inc e o .php e não achei nenhum erro de sintaxe. Eu tenho a biblioteca gd ativada e consigo gerar imagens de outros tipos (como a de uma estrela, por exemplo). Seguem abaixo os códigos e mais uma vez, obrigado. O arquivo .inc <?php // configurações do gráfico $largura = 600; $altura = 400; // configurações do círculo $centrox = 200; $centroy = 200; $diametro = 280; $angulo = 0; // configurações da legenda $exibir_legenda = "sim"; $fonte = 3; $largura_fonte = 8; $altura_fonte = 10; $espaco_entre_linhas = 10; $margem_vertical = 5; // canto superior direito da legenda $lx = 540; $ly = 30; ?> O arquivo .php de geração do gráfico <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Gráfico de Pizza</title> </head> <body> <?php header("Content-type: image/png"); // inclui o arquivo com as configurações include 'config_grafico.inc'; // cria a imagem e define as cores $imagem = imagecreate($largura, $altura); $fundo = imagecolorallocate($imagem, 236, 226, 226); $preto = imagecolorallocate($imagem, 0, 0, 0); $azul = imagecolorallocate($imagem, 0, 0, 255); $verde = imagecolorallocate($imagem, 0, 255, 0); $vermelho = imagecolorallocate($imagem, 255, 0, 0); $amarelo = imagecolorallocate($imagem, 255, 255, 0); // definição dos dados $dados = array("Leoes", "Antilopes", "Elefantes", "Girafas"); $valores = array(180, 540, 330, 110); $cores = array($azul, $verde, $vermelho, $amarelo); // cálculo do total $total = 0; $num_linhas = sizeof($dados); for($i = 0; $i < $num_linhas; $i++) $total += $valores[$i]; // desenha o gráfico imageellipse($imagem, $centrox, $centroy, $diametro, $diametro, $preto); imagestring($imagem, 3, 3, 3, "Total: $total animais", $preto); $raio = $diametro / 2; for($i = 0; $i < $num_linhas; $i++) { $percentual = ($valores[$i]/$total) * 100; $percentual = number_format($percentual, 2); $percentual .= "%"; $val = 360 * ($valores[$i]/$total); $angulo += $val; $angulo_meio = $angulo - ($val / 2); $x_final = $centrox + $raio * cos(deg2rad($angulo)); $y_final = $centroy + (- $raio * sin(deg2rad($angulo))); $x_meio = $centrox + ($raio / 2 * cos(deg2rad($angulo_meio))); $y_meio = $centroy + (- $raio / 2 * sin(deg2rad($angulo_meio))); $x_texto = $centrox + ($raio * cos(deg2rad($angulo_meio))) * 1.2; $y_texto = $centroy + (- $raio * sin(deg2rad($angulo_meio))) * 1.2; imageline($imagem, $centrox, $centroy, $x_final, $y_final, $preto); imagefilltoborder($imagem, $x_meio, $y_meio, $preto, $cores[$i]); imagestring($imagem, 2, $x_texto, $y_texto, $percentual, $preto); } // ------ CRIAÇÃO DA LEGENDA ------ if($exibir_legenda == "sim") { // acha a maior string $maior_tamanho = 0; for($i = 0; $i < $num_linhas; $i++) if(strlen($dados[$i]) > $maior_tamanho) $maior_tamanho = strlen($dados[$i]); // calcula os pontos de início e fim do quadrado $x_inicio_legenda = $lx - $largura_fonte * ($maior_tamanho + 4); $y_inicio_legenda = $ly; $x_fim_legenda = $lx; $y_fim_legenda = $ly + $num_linhas * ($altura_fonte + $espaco_entre_linhas) + 2 * $margem_vertical; imagerectangle($imagem, $x_inicio_legenda, $y_inicio_legenda, $x_fim_legenda, $y_fim_legenda, $preto); // começa a desenhar os dados for($i = 0; $i < $num_linhas; $i++) { $x_pos = $x_inicio_legenda + $largura_fonte * 3; $y_pos = $y_inicio_legenda + $i * ($altura_fonte + $espaco_entre_linhas) + $margem_vertical; imagestring($imagem, $fonte, $x_pos, $y_pos, $dados[$i], $preto); imagefilledrectangle($imagem, $x_pos - 2 * $largura_fonte, $y_pos, $x_pos - $largura_fonte, $y_pos + $altura_fonte, $cores[$i]); imagerectangle($imagem, $x_pos - 2 * $largura_fonte, $y_pos, $x_pos - $largura_fonte, $y_pos + $altura_fonte, $preto); } } imagepng($imagem); imagedestroy($imagem); ?> </body> </html>
  20. Obrigado gente! Eu não tinha enxergado esses erros. Problema resolvido. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script type = "text/javascript"> // script para criar um relógio digital com indicação de AM/PM e uma saudação de acordo com a hora do dia. function tempo() { var d1 = new Date() var h = d1.getHours() var m = d1.getMinutes() var s = d1.getSeconds() var ampm = h var saudacao ampm >= 0 && ampm < 12? ampm = "AM" : ampm = "PM" if(h >= 0 && h < 12) saudacao = "Bom dia!" else if(h >= 12 && h < 18) saudacao = "Boa tarde!" else if(h >= 18 && h <= 23) saudacao = "Boa noite!" // if aninhado necessário para ajustar a hora adequadamente. // sem este if, 11 PM e 10 PM ficariam formatados como 011 e 010 respectivamente if(h > 12) { h -= 12 if(h >= 1 && h <= 9) { h = '0' + h } } if(h == 0) h = 12 if(s < 10) s = '0' + s if(m < 10) m = '0' + m var horario = h + ':' + m + ':' + s + ' ' + ampm + ' ' + saudacao window.status = horario setTimeout("tempo()", "1000") } </script> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Relógio AM/PM</title> </head> <body onload ="tempo()"> </body> </html>
  21. Boa noite gente. Estou tentando criar um script que faça aparecer um horário com AM ou PM na barra de status do IE mas não estou conseguindo: estou tendo o erro "Objeto não encontrado." Poderiam dizer aonde estou errando? obrigado pela ajuda e tenham um ótimo ano novo. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> &lt;script type = "type/javascript"> function tempo() { var d1 = new Date() var h = d1.getHours() var m = d1.getMinutes() var s = d1.getSeconds() var hora, minutos, segundos, cond var ampm = h ampm >= 12? cond = "PM" : cond = "AM" if(h > 12) { hora = h - 12 hora = '0' + hora } if(s < 10) segundos = '0' + s if(m < 10) minutos = '0' + m var horario = hora + ':' + minutos + ':' + segundos + '' + cond window.status = horario setTimeout("tempo()", "1000") } </script> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Relógio AM/PM</title> </head> <body onload ="tempo()"> </body> </html>
  22. Como não adicionei id ao input, eu fiz da seguinte forma: document.fm2.recebe.style.fontWeight = 'bold'; document.fm2.recebe.value = 'Este é um exemplo em negrito'; e deu certo graças à hierarquia. Muito obrigado vini_loock. Caso encerrado ^_^ .
  23. Interessante mas não era bem isso que eu queria fazer vini_loock. A minha intenção é que apareça um texto com o efeito desejado e o código do texto no textarea ou text quando o usuário clicar no botão Visualizar Código. Com a instrução: document.fm2.recebe.value = "<b>Este é um exemplo em negrito</b>"; não dá para fazer isso porque o <b> é interpretado como texto : \ .
  24. Bom dia a todos! eu criei um HTML simples com JS que funciona da seguinte maneira: a pessoa seleciona uma das opções de uma lista de seleção e, se for negrito, itálico ou sublinhado, aparece uma linha de código correspondente ao efeito. Agora eu gostaria que o texto aparecesse com o efeito dentro do text (ex.: texto). Tem como fazer isso dentro de uma função? Obrigado pela ajuda. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> &lt;script type="text/javascript"> <!-- function mostrarTexto() { var escolha = document.fm1.sel.value; if(escolha == "op1") document.fm2.recebe.value = "Por favor escolha uma opção."; else if(escolha == "op2") { document.fm2.recebe.value = "<b>Este é um exemplo em negrito</b>"; } else if(escolha == "op3") { document.fm2.recebe.value = "<i>Este é um exemplo em itálico</i>"; } else if(escolha == "op4") { document.fm2.recebe.value = "<u>Este é um exemplo sublinhado</u>"; } } --> </script> <style type="text/css"> table{ border-spacing: 5pt 5pt; } </style> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Trechos de Código</title> </head> <body> <table> <tr> <td> <form name="fm1"> <select name= "sel"> <option value = "op1">Qual é o efeito do código?</option> <option value = "op2">Negrito</option> <option value = "op3">Itálico</option> <option value = "op4">Sublinhado</option> </select> <input type="button" onclick="mostrarTexto()" name = "bt1" value="Visualizar Código" /> </form> </td> <td> <form name="fm2"> <input type= "text" name="recebe" size= "40"/> </form> </td> </tr> </table> </div> </body> </html>
×
×
  • Criar Novo...