Ir para conteúdo

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Rodrigo Razzyel

exibir resultado do $post entro do formulário "value=" &#

Recommended Posts

Ajuda Urgente. não estou conseguindo fazer com que o resultado "R$", obtido no "litResultado" pareça no campo

value=" " para ser enviado ao pagseguro

algum pode me ajudar ou pelo menos me da uma luz, de como fazer .. por vavor

 

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Calcular distancia entre cidades (mapas e rotas)</title>
    <script src="http://code.jquery.com/jquery-1.8.1.js" type="text/javascript"></script>
</head>
<body>
        <script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
            function CalculaDistancia() {
                $('#litResultado').html('Aguarde...');
                //Instanciar o DistanceMatrixService
                var service = new google.maps.DistanceMatrixService();
                //executar o DistanceMatrixService
                service.getDistanceMatrix(
                  {
                      //Origem
                      origins: [$("#txtOrigem").val()],
                      //Destino
                      destinations: [$("#txtDestino").val()],
                      //Modo (DRIVING | WALKING | BICYCLING)
                      travelMode: google.maps.TravelMode.DRIVING,
                      //Sistema de medida (METRIC | IMPERIAL)
                      unitSystem: google.maps.UnitSystem.METRIC
                      //Vai chamar o callback
                  }, callback);
            }
            //Tratar o retorno do DistanceMatrixService
            function callback(response, status) {
                //Verificar o Status
                if (status != google.maps.DistanceMatrixStatus.OK)
                    //Se o status não for "OK"
                    $('#litResultado').html(status);
                else {
                    //Se o status for OK
                    //Endereço de origem = response.originAddresses
                    //Endereço de destino = response.destinationAddresses
                    //Distância = response.rows[0].elements[0].distance.text
                    //Duração = response.rows[0].elements[0].duration.text
                   $('#litResultado').html("<strong>Origem</strong>: " + response.originAddresses +
      "<br /><strong>Destino:</strong> " + response.destinationAddresses +
      "<br /><strong>Distância</strong>: " + response.rows[0].elements[0].distance.text +
      " <br /><strong>Duração</strong>: " + response.rows[0].elements[0].duration.text +
      " <br /><strong>Preço</strong>: R$ " + (parseFloat(response.rows[0].elements[0].distance.text.substring(0, response.rows[0].elements[0].distance.text.length - 3).split(",").join(".")) * 1.5 + 30.00).toFixed(2).toString().split(".").join(",")
); 


                    //Atualizar o mapa
                    $("#map").attr("src", "https://maps.google.com/maps?saddr=" + response.originAddresses + "&daddr=" + response.destinationAddresses + "&output=embed");
                }
            }
        </script>
        <table width="68%" cellspacing="0" cellpadding="0" border="0">
            <tbody>
                <tr>
                  <td>
                        <label for="txtOrigem"><strong>Endereço de origem</strong></label>
                        <input type="text" id="txtOrigem" class="field" style="width: 400px" />
                        <br>
                        Quem vai receber     
                        <input type="text" id="txtOrigem2" class="field" style="width: 400px" />


                    </td>
                </tr>
                <tr>
                    <td>
                        <label for="txtDestino"><strong>Endereço de destino</strong></label>
                        <input type="text" style="width: 400px" class="field" id="txtDestino" />


                    </td>
                </tr>
                <tr>
                    <td>
                        <p>
                          <input type="button" value="Calcular distância" onclick="CalculaDistancia()" class="btnNew" />
                        </p>
                        <table width="409" border="0">
                          <tr>
                            <th width="403" scope="col"><form target="pagseguro" method="post" action="https://pagseguro.uol.com.br/checkout/checkout.jhtml">
  <input type="hidden" name="email_cobranca" value="suporte@lojamodelo.com.br">
  <input type="hidden" name="tipo" value="CP">
  <input type="hidden" name="moeda" value="BRL">


  <input type="hidden" name="item_id_1" value="12345">
  <input type="hidden" name="item_descr_1" value="Moto frete">
  <input type="hidden" name="item_quant_1" value="1">
  
  // Digite corretamente o valor calculado abaixo para confirmação
  <input type="hidden" name="item_valor_1" Value="litResultado" >
  
  
  <input type="image" src="https://p.simg.uol.com.br/out/pagseguro/i/botoes/pagamentos/99x61-pagar-assina.gif" name="submit" alt="Pague com PagSeguro - é rápido, grátis e seguro!">
</form>></th>
                          </tr>
                        </table>
                        <p>  </p>
                    </td>
                </tr>
            </tbody>
        </table>
        <div><span id="litResultado"> </span></div>
        <div style="padding: 10px 0 0; clear: both"></div>
</body>
</html>

Compartilhar este post


Link para o post
Compartilhar em outros sites

Apenas a porção de código relevante:

var valor = (parseFloat(response.rows[0].elements[0].distance.text.substring(0, response.rows[0].elements[0].distance.text.length - 3).split(",").join(".")) * 1.5 + 30.00).toFixed(2).toString().split(".").join(",");
$('#litResultado').html("<strong>Origem</strong>: " + response.originAddresses +
"<br /><strong>Destino:</strong> " + response.destinationAddresses +
"<br /><strong>Distância</strong>: " + response.rows[0].elements[0].distance.text +
" <br /><strong>Duração</strong>: " + response.rows[0].elements[0].duration.text +
" <br /><strong>Preço</strong>: R$ " + valor
);
$("input[name='item_valor_1']").val(valor);

Compartilhar este post


Link para o post
Compartilhar em outros sites

 

Apenas a porção de código relevante:

var valor = (parseFloat(response.rows[0].elements[0].distance.text.substring(0, response.rows[0].elements[0].distance.text.length - 3).split(",").join(".")) * 1.5 + 30.00).toFixed(2).toString().split(".").join(",");
$('#litResultado').html("<strong>Origem</strong>: " + response.originAddresses +
"<br /><strong>Destino:</strong> " + response.destinationAddresses +
"<br /><strong>Distância</strong>: " + response.rows[0].elements[0].distance.text +
" <br /><strong>Duração</strong>: " + response.rows[0].elements[0].duration.text +
" <br /><strong>Preço</strong>: R$ " + valor
);
$("input[name='item_valor_1']").val(valor);

Ola amigo, muito o brigado mesmo de certo , voce me ajudou muito agradeço de coração .. sucesso e tudo de bom para voce.

Compartilhar este post


Link para o post
Compartilhar em outros sites

  • Conteúdo Similar

    • Por user32
      Boa noite a todos, 
      comprei um formulário de pagamento via pix através do mercadopago no qual a pessoa q me vendeu não me da suporte algum e to quase uma semana quebrando cabeça com isso.
      ao clicar em gerar pix não há efeito algum.
       
      <?php ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); /** * Automatic Mercadopago payment system gateway. * * @name pix-myaac-mercadopago * @author Rafhael Oliveira <rafhaelxd@gmail.com> * @website github.com/thetibiaking/ttk-myaac-plugins * @website github.com/underewarrr/ * @version 1.0.0 */ require_once('/var/www/html/classes/functions.php'); require_once('/var/www/html/system/load.init.php'); require_once('/var/www/html/mercadopago/pix/config.php'); if (isset($config['mercadopago']) && $config['mercadopago'] = true) { } else { echo "MercadoPago is disabled. If you're an admin please configure this script in config.local.php."; return; } if (empty($logged)) { header("Location: " . $noSessionUrl); exit; } if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Verifica se os dados foram enviados via POST // Caminho relativo para o arquivo config.php $quantidadeSelecionada = (int)$_POST['quantidade']; $cpf = $_POST['cpf']; // Validate CPF if (!validateCPF($cpf)) { echo '<p>CPF inválido. Por favor, verifique e tente novamente.</p>'; exit; } $totalValue = $quantidadeSelecionada * $priceByPoints; $pontosGanhos = $quantidadeSelecionada * $pointsByDonate; $curl = curl_init(); $dados["transaction_amount"] = $totalValue; $dados["description"] = $_POST['description'] ?: 'Value and Coins'; $dados["external_reference"] = "2"; $dados["payment_method_id"] = "pix"; $dados["notification_url"] = $notificationUrl; $dados["payer"]["email"] = $_POST['email_cob']; $dados["payer"]["first_name"] = "Nilza"; $dados["payer"]["last_name"] = "Guimaraes"; $dados["payer"]["identification"]["type"] = "CPF"; $dados["payer"]["identification"]["number"] = $cpf; $dados["payer"]["address"]["zip_code"] = "76240000"; $dados["payer"]["address"]["street_name"] = "Av. Carlos Gomes"; $dados["payer"]["address"]["street_number"] = "411"; $dados["payer"]["address"]["neighborhood"] = "Bela Vista"; $dados["payer"]["address"]["city"] = "Aragarcas"; $dados["payer"]["address"]["federal_unit"] = "GO"; curl_setopt_array($curl, array( CURLOPT_URL => 'https://api.mercadopago.com/v1/payments', CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS => json_encode($dados), CURLOPT_HTTPHEADER => array( 'accept: application/json', 'content-type: application/json', 'Authorization: Bearer ' . $authorizationToken, ), )); $response = curl_exec($curl); $resultado = json_decode($response); $collector_id = isset($resultado->id) ? $resultado->id : null; curl_close($curl); // Display full response for debugging if debug is enabled if ($debug) { echo '<pre>'; var_dump($resultado); echo '</pre>'; } // Check if collector_id is present if (!$collector_id) { echo '<p>Error: Collector ID not found in the response.</p>'; exit; } echo 'Collector ID: ' . $collector_id; // Verifica se a resposta foi bem-sucedida antes de exibir o QR Code if ($resultado->status === 'pending') { // Exibe o QR Code e o código apenas se o debug estiver desativado if (!$debug) { echo '<img style="display:block; width:300px;height:300px;" id="base64image" src="data:image/jpeg;base64, ' . $resultado->point_of_interaction->transaction_data->qr_code_base64 . '" />'; echo '<b>Copie:</b> ' . $resultado->point_of_interaction->transaction_data->qr_code; } // Exibe os pontos ganhos echo '<p>Você gerou um pix no valor de ' .$totalValue. 'R$ e ' . $pontosGanhos . ' pontos!</p>'; echo '<p>Ao Pagar você recebera seus pontos automaticamente</p>'; echo '<p>Status: ' . $resultado->status . '</p>'; echo '<button onclick="location.href=\'https://meusite.com/?subtopic=mpnotification&id=' . $collector_id . '&debug=' . ($debug ? 'true' : 'false') . '\'" type="button">Conferir Status do Pedido</button> <br>'; // Ação no banco de dados (se necessário) $logged = getSession('account'); $sql = "INSERT INTO status(status, codigo, account, points) VALUES(?, ?, ?, ?)"; $stmt = mysqli_prepare($conexao, $sql); // Check if the statement was prepared successfully if ($stmt) { // Assuming $logged and $pontosGanhos are defined elsewhere in your code // Bind parameters with data types mysqli_stmt_bind_param($stmt, "sssi", $resultado->status, $collector_id, $logged, $pontosGanhos); // Execute the statement mysqli_stmt_execute($stmt); // Check for successful execution if (mysqli_stmt_affected_rows($stmt) > 0) { echo "Record inserted successfully"; } else { echo "Error inserting record"; } // Close the statement mysqli_stmt_close($stmt); } else { echo "Error preparing statement: " . mysqli_error($conexao); } } else { echo '<p>Erro ao processar o pagamento. Tente novamente.</p>'; // Display error message, if available if (isset($resultado->message)) { echo '<p>Error Message: ' . $resultado->message . '</p>'; } // Display status for further analysis echo '<p>Status: ' . $resultado->status . '</p>'; } } else { // Formulário para preenchimento dos dados echo ' <form method="POST"> <label for="quantidade">Quantidade de Doações:</label> <select name="quantidade" id="quantidade" required> <option value="1">1 - R$25,00 (60 pontos)</option> <option value="2">2 - R$50,00 (120 pontos)</option> <option value="3">3 - R$75,00 (180 pontos)</option> <!-- Adicione mais opções conforme necessário --> </select> <br> <label for="description">Descrição:</label> <input type="text" name="description" id="description" placeholder="Write any description" required> <br> <label for="email_cob">Email do Pagador:</label> <input type="email" name="email_cob" id="email_cob" required> <br> <label for="cpf">CPF do Pagador:</label> <input type="text" name="cpf" id="cpf" required> <br> <button type="submit">Gerar Pix</button> </form> '; } // Simple CPF validation function function validateCPF($cpf) { // Remove any non-numeric characters $cpf = preg_replace('/[^0-9]/', '', $cpf); // Check if CPF has 11 digits if (strlen($cpf) != 11) { return false; } // Validate CPF using basic algorithm $sum = 0; for ($i = 0; $i < 9; $i++) { $sum += (int)$cpf[$i] * (10 - $i); } $remainder = $sum % 11; $digit = ($remainder < 2) ? 0 : 11 - $remainder; if ((int)$cpf[9] != $digit) { return false; } $sum = 0; for ($i = 0; $i < 10; $i++) { $sum += (int)$cpf[$i] * (11 - $i); } $remainder = $sum % 11; $digit = ($remainder < 2) ? 0 : 11 - $remainder; if ((int)$cpf[10] != $digit) { return false; } return true; } ?> <?php /** * Automatic Mercadopago payment system gateway. * * @name pix-myaac-mercadopago * @author Rafhael Oliveira <rafhaelxd@gmail.com> * @website github.com/thetibiaking/ttk-myaac-plugins * @website github.com/underewarrr/ * @version 1.0.0 */ require_once('/var/www/html/classes/functions.php'); require_once('/var/www/html/system/load.init.php'); require_once('/var/www/html/mercadopago/pix/config.php'); // Set debug mode based on the query parameter // use debug true in url to get more infos $debug = isset($_REQUEST['debug']) && $_REQUEST['debug'] === 'true'; // Verify if the collector_id is present in the request if (isset($_REQUEST['id'])) { $collector_id = $_REQUEST['id']; // Initialize cURL $curl = curl_init(); // Set cURL options curl_setopt_array($curl, array( CURLOPT_URL => 'https://api.mercadopago.com/v1/payments/' . $collector_id, CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => 'GET', CURLOPT_HTTPHEADER => array( 'accept: application/json', 'content-type: application/json', 'Authorization: Bearer ' . $authorizationToken, ), )); // Execute cURL request $response = curl_exec($curl); // Check if cURL request was successful if ($response === false) { // Handle cURL error echo 'Error fetching payment details from Mercado Pago API.'; if ($debug) { echo '<br>Debug Mode: ON'; echo '<br>Status from Mercado Pago API: ' . $resultado->status; echo 'Total Paid Amount or Transaction Amount: ' . $resultado->transaction_amount * $conversionRate; echo '<br>Status from Mercado Pago API: <pre>' . print_r($resultado, true) . '</pre>'; echo '<br>CURL Error: ' . curl_error($curl); } } else { // Decode the JSON response $resultado = json_decode($response); // Check if the payment status is 'approved' or 'paid' // Check if the payment status is approved or paid // Check if the payment status is approved or paid if ($resultado->status === 'approved' || $resultado->status === 'paid') { // Check if the payment has already been processed $check_processed = "SELECT processed FROM status WHERE codigo = ?"; $stmt_check = mysqli_prepare($conexao, $check_processed); mysqli_stmt_bind_param($stmt_check, "i", $collector_id); mysqli_stmt_execute($stmt_check); mysqli_stmt_bind_result($stmt_check, $processed); mysqli_stmt_fetch($stmt_check); mysqli_stmt_close($stmt_check); if ($processed === 0 || $processed === null) { // Payment not processed yet // Mark the payment as processed $update_processed = "UPDATE status SET processed = 1 WHERE codigo = ?"; $stmt_processed = mysqli_prepare($conexao, $update_processed); mysqli_stmt_bind_param($stmt_processed, "i", $collector_id); mysqli_stmt_execute($stmt_processed); mysqli_stmt_close($stmt_processed); $new_status_value = 'delivered'; // Here's the additional update query for the status column in the status table $update_status = "UPDATE status SET status = ? WHERE codigo = ?"; $stmt_status = mysqli_prepare($conexao, $update_status); mysqli_stmt_bind_param($stmt_status, "si", $new_status_value, $collector_id); // Replace $new_status_value with the appropriate value mysqli_stmt_execute($stmt_status); mysqli_stmt_close($stmt_status); // Calculate premium points based on total_paid_amount and conversion rate $conversionValue = $resultado->transaction_amount * $conversionRate; // Get the current session account $logged = getSession('account'); // Update the accounts table with premium points using prepared statement $update_accounts = "UPDATE accounts SET $donationType = $donationType + ? WHERE id = ?"; $stmt_accounts = mysqli_prepare($conexao, $update_accounts); // Check if the statement for accounts table was prepared successfully if ($stmt_accounts) { // Bind parameters with data types for accounts table mysqli_stmt_bind_param($stmt_accounts, "di", $conversionValue, $logged); // Execute the statement for accounts table mysqli_stmt_execute($stmt_accounts); // Check for successful execution for accounts table if (mysqli_stmt_affected_rows($stmt_accounts) > 0) { echo "Premium points updated successfully in accounts table"; } else { echo "Error updating premium points in accounts table"; } // Close the statement for accounts table mysqli_stmt_close($stmt_accounts); } else { echo "Error preparing statement for accounts table: " . mysqli_error($conexao); } } else { echo 'Payment already processed.'; } } else { echo 'Payment status is not "approved" or "paid". No database update performed.'; } if ($debug) { echo '<br>Debug Mode: ON'; echo '<br>Status from Mercado Pago API: ' . $resultado->status; echo 'Total Paid Amount or Transaction Amount: ' . $resultado->transaction_amount * $conversionRate; echo '<br>Status from Mercado Pago API: <pre>' . print_r($resultado, true) . '</pre>'; echo '<br>CURL Error: ' . curl_error($curl); } } // Close cURL curl_close($curl); } else { echo 'Invalid or missing collector_id in the request.'; if ($debug) { echo '<br>Debug Mode: ON'; // Add more debug information as needed } } ?> <?php $pointsByDonate = 60; // coins $priceByPoints = 25.00; // value $conversionRate = $pointsByDonate / $priceByPoints; $debug = true; $notificationUrl = 'https://meusite.com/?subtopic=mpnotification'; $noSessionUrl = 'https://meusite.com/?subtopic=accountmanagement'; $donationType = 'premium_points'; // coins or premium_points $doublePoints = false; // not added yet $authorizationToken = 'APP_USR-4182410924225948-0415***************557-1249281564'; $servername = "localhost"; $username = "usuario"; $password = "senha"; $db_name = "bancodedados"; $conexao = mysqli_connect($servername, $username, $password, $db_name); if (!$conexao) { die("Connection failed: " . mysqli_connect_error()); } echo "Connected successfully"; ?>  
    • Por ILR master
      Pessoal, pergunta bem simples. Abaixo tenho o seguinte código:
       
      <script>
      function alerta()
      {
        if (window.confirm("Você realmente quer sair?")) {
          window.open("sair.html");
      }
      }
      </script>
       
      Funciona perfeitamente, só que está abrindo em outra janela e quero que abra na mesma janela.
       
      Alguém pode me ajudar?
    • Por Giovanird
      Olá a todos!
      Tenho uma pagina que possui uma DIV onde coloquei uma pagina PHP.
      Uso a função setInterval para atualizar a pagina inclusa dentro da DIV.
      O problema é que ao acessar o site , a DIV só me mostra a pagina inclusa somente quando completo o primeiro minuto.
      Preciso que a pagina inclusa já inicie carregada
       
      Meu código JavaScript e a DIV com a pagina PHP
       
      <script> function atualiza(){ var url = 'direita.php'; $.get(url, function(dataReturn) { $('#direita').html(dataReturn); }); } setInterval("atualiza()",60000); </script> <div> <span id="direita"></span> </div>  
    • Por Thiago Duarte
      Oi, gostaria de arrastar imagem e ao soltar formar bloco html, meu bloco de html ficaria com nome, content-1.html, content-2.html, etc
       
      Alguem pode me ajudar?
    • Por belann
      Olá!
       
      Estou fazendo o upload de arquivos com fetch dessa forma
      fetch(url, {
              method: 'POST',
              headers: {'Content-Type': 'multipart/form-data',},
              body: formData 
          }).catch((error) => (console.log("Problemas com o Upload"), error));
       
      estou usando input type=file
      e criando uma const formData = new FormData(); 
      mas não faz e não dá nenhum erro.
      estou fazendo o upload com a url="http://localhost/dashboard/dados".
×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.