简体   繁体   中英

How to load a page into a div after using header

I would like to know how do I load a html page into a div, after using the header into a php code.

For example:

I have the main page. When I click the menu on the left side, it loads a page inside the div named "content". Inside the div named content, I have a form, after filling the form, I click the "Send" button.

By clicking the send button, I get redirected to my php code, which is insert_produto.php

Inside the page insert_produto.php I have the following code:

 <?php include '../logado.php'; $tipo =$_POST["tipo"]; $marca =$_POST["marca"]; $comprimento =$_POST["comprimento"]; $externo =$_POST["externo"]; $interno =$_POST["interno"]; $quantidade =$_POST["quantidade"]; //$conen tem que ser o nome da conexão, depois disso monta a query //mysqli_query($conec,"INSERT INTO produtos (tipo) VALUES ('$tipo')"); if ($quantidade == "") { $quantidade = 1; } for ($i = 1; $i <= $quantidade; $i++) { if ($externo == '' or $interno == '') { echo "Os seguintes valores são obrigatórios:</p>"; echo "• Diâmetro Externo;</p>"; echo "• Diâmetro Interno."; echo "</br></br>"; echo '<form id="erro" action="../main.php" method="post">'; echo '<input type="submit" class="botao" value="Voltar">'; echo '</form>'; die; } // se INTEIRO = primeira query, ELSE segunda query if ($comprimento == '' and $tipo == 'Inteiro'){ mysqli_query($conec,"INSERT INTO produtos (tipo, marca, comprimento, diaexterno, diainterno) VALUES ('$tipo', '$marca', '1000', '$externo', '$interno')"); } elseif ($comprimento == '' and $tipo == 'Pedaço') { echo "Os seguintes valores são obrigatórios:</p>"; echo "• Comprimento;</p>"; echo "</br></br>"; echo '<form id="erro" action="../main.php" method="post">'; echo '<input type="submit" class="botao" value="Voltar">'; echo '</form>'; die; } else { mysqli_query($conec,"INSERT INTO produtos (tipo, marca, comprimento, diaexterno, diainterno) VALUES ('$tipo', '$marca', '$comprimento', '$externo', '$interno')"); } } // ENCERRA O LAÇO DE REPETIÇÃO "FOR" //header("Location: " . $_SERVER["HTTP_REFERER"]); header("location: /main.php"); echo '<div class="content"> <?php include("/cadastro/produto.php"); ?> </div> ' ?> 

After the FOR , I use Header to return to the main page. However, when I get to the main page, I would like to reload the previous html page inside the div called "content".

I don't mind too if I have to specify manually which page I want to load inside the div, I actually prefer this way.

In your case, you're using Location header, which change the HTTP result code to 302 Redirect , with the content you echoed after (in this case, the <div> and include of /cadastro/produto.php . All modern browsers will ignore the content received and will redirect user to Location URL. The only way to do what you want is to submit the form using AJAX and process the response.

For example, you could do it like this (using jQuery), considering you have id=form at your <form> tag:

<script type="text/javascript">
$('#form').on ( 'submit', function ( e)
{
  e && e.preventDefault;
  $.ajax (
  {
    url: 'insert_produto.php',
    error: function ( jqXHR, textStatus, errorThrown)
    {
      alert ( 'Error sending form: ' + jqXHR.status + ' ' + jqXHR.statusText);
    },
    success: function ( data, textStatus, jqXHR)
    {
      if ( typeof ( data) == 'object' && 'result' in data)
      {
        if ( data.result == 'ok')
        {
          alert ( 'Added!');
          $('#content').load ( data.location);
        } else {
          alert ( data.message);
        }
      } else {
        alert ( 'Unknown data received.');
      }
    }
  });
});
</script>

At your PHP script, you'll need to return a JSON object with the structure:

{
  "result": "ok",
  "location": "\/cadastro\/produto.php"
}

And on error, with the structure:

{
  "result": "error",
  "message": "My error message"
}

You could do it using:

 <?php include '../logado.php'; $tipo =$_POST["tipo"]; $marca =$_POST["marca"]; $comprimento =$_POST["comprimento"]; $externo =$_POST["externo"]; $interno =$_POST["interno"]; $quantidade =$_POST["quantidade"]; $return = array (); header ( "Content-Type: text/json"); //$conen tem que ser o nome da conexão, depois disso monta a query //mysqli_query($conec,"INSERT INTO produtos (tipo) VALUES ('$tipo')"); if ($quantidade == "") { $quantidade = 1; } for ($i = 1; $i <= $quantidade; $i++) { if ($externo == '' or $interno == ''){ $return["result"] = "error"; $return["message"] = "Os seguintes valores são obrigatórios:\\n• Diâmetro Externo;\\nDiâmetro Interno."; die ( json_encode ( $return); } // se INTEIRO = primeira query, ELSE segunda query if ($comprimento == '' and $tipo == 'Inteiro'){ mysqli_query($conec,"INSERT INTO produtos (tipo, marca, comprimento, diaexterno, diainterno) VALUES ('$tipo', '$marca', '1000', '$externo', '$interno')"); } elseif ($comprimento == '' and $tipo == 'Pedaço') { $return["result"] = "error"; $return["message"] = "Os seguintes valores são obrigatórios:\\n• Comprimento."; die ( json_encode ( $return); } else { mysqli_query($conec,"INSERT INTO produtos (tipo, marca, comprimento, diaexterno, diainterno) VALUES ('$tipo', '$marca', '$comprimento', '$externo', '$interno')"); } } // ENCERRA O LAÇO DE REPETIÇÃO "FOR" $return["result"] = "ok"; $return["location"] = "/cadastro/produto.php"; die ( json_encode ( $return); ?> 

I could not figure how to solve this issue, so i made an work-around

i'll explain how i made that work-around, so anyone facing the same issue may find it helpful

First, at the end of the php code, i simple added the following line: $_SESSION["pagina"] ="cadastro_produto";

before the: header("location: /main.php");

then, at my main.php i did this: $teste =$_SESSION["pagina"];

and inside the div "content", i made this

 <?php if ($teste == 'cadastro_produto'){ echo '<div id="caixa"> Cadastrado com sucesso.</p> voltar </div>'; //header("location: /cadastro/produto.php") } $_SESSION["pagina"] = ""; ?> 
i put $_SESSION["pagina"] = ""; at end, so i can set the variable teste to blank, this way an refresh of the page would not make this appear again

i know this isnt the best way to fix the problem, but it worked for me and its enough for what i need

plus i would need to figure out how to make a return message if the "insert into" was successful or not, that way i can make the return msg and echo a back button to the form

this solution solves my problem, but i thank everyone who tried to help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM