Insert PHP into div with Jquery (.html)

Asked

Viewed 7,029 times

4

I have a div that will receive the content, I have a vertical menu, which will define the content that the guy will see. The problem is that it does the .load() of the file, but it loads as far as appears

I tried for the .html(), and put a include .php, it even does, but gives the same problem. It does not read the information after PHP. I tried to write the page inside the .html(), but it also doesn’t work, I made double quote corrections with backslash ( ") and it didn’t work.

In the official libraries I could not get an answer if the case is with Database and PHP. but I can not understand, why does not work.

My code is a little big, because there are several links and the contents are extensive, I made a reduced example, because I think the problem is concept, not syntax.

  • The problem is not in PHP and Mysql, because if I open the page only, outside of jQuery, it works smoothly, takes all the data.

  • The jQuery database and Mysql connection are already being made and work, not put to fill with useless code.

jQuery:

<script type="text/javascript">
$(document).ready(function() {
$("#link1").click(function() {
$("#conteudo").html("Aqui vai o conteúdo do Link 1, via HTML mesmo, pois não tem PHP.. Esse aqui funciona normalmente!");
});
$("#link2").click(function() {
$("#conteudo").load('link2.php');
});
});
</script>

HTML

  <a href="#link1" id="link1">Link 1</a>
  <a href="#link2" id="link2">Link 2</a>

  <div id="conteudo">Este conteúdo é para ser alterado, conforme o usuário vá clicando no link... O link 1 funciona normal, pois não tem php, o link 2 funciona até aparecer o PHP...</div>

PHP (Link2.php)

  <?php
$query = @mysql_query("SELECT * FROM dados;");
while($linha = @mysql_fetch_array($query)) { ?>
<p><?php echo $linha['nome']. " - ". $linha['sobrenome']; ?> 
<a href="imagens/foto.jpg">Veja a foto</a>
</p>
<?php } ?>

  • 1

    In Link2.php you are not opening the database, can you connect?? , and don’t use @ to omit errors remove this, it is not loading anything because it has no active connection in the code snippets

  • I already made the connection in a require on the page that will include... I did not put in the code because I thought it would be bullshit... I really don’t even know why I put that @.. I’m going to pull it out to see what happens..

  • Please post the whole page we can watch what is really happening ... !!! @ means bug defaults ... gave error does not show !!! (use in well defined cases)

3 answers

3


TL;DR - Include the php files that define the connection in link2.php. The .load() jQuery will only work when you can make a direct request to link2.php and receive the desired html fragment.

You are confusing two things. PHP command interpretation server-side (include) with ajax features client-side.

The method loadjQuery hopes that the link2.php return a page or html fragment. In this case the link2.php alone produces nothing, only fails silently (@) due to lack of an active connection.

Request 1 -> Pagina 1 -> Request 2 -> link2.php (sem conexão) = Falha silenciosa

What you need to do is create a page link2.php that works on its own (i.e., returns results when a request is done directly by the browser). For this you must include code to connect to the bank and everything necessary to print the results.

Note that this functionality is very different from a require or include; these do everything on the server side:

Request 1 -> 
    Pagina 1, cria conexões etc
        include 'link2.php'
            usa conexão "definida" na página 1
<- Servidor interpreta o conjunto e navegador recebe uma resposta HTML unificada

In that case there is no second request, the content of link2.php is interpreted along with the content of the current page by the server as if it were another piece of PHP code in the body of the page. The browser is not aware that these are two separate files.

  • Interesting Anthony. I thought so I would be duplicating the connections, but what caught my attention is about a conceptual error myself that I’m making.. I’ll try it this way. I warn you here the result...

  • Anthony... you were absolutely right, I think you understood exactly what my doubt was and where I was going wrong. It was simply putting a require of the connection to the Database.. that everything went right... I was with the wrong concept.. I had not forgotten the connection, I thought I would be duplicating.. I learned a lot in this topic, I really appreciate the help.

  • 1

    No problem Luther, this is a classic confusion, the division between what is done on the server and what is done on the client will become clearer over time. Don’t forget to follow the tips of colleague Fulvio and replace the Mysql extension with Mysqli or PDO, it is much better to do this now than in the future when your code base is huge.

2

Try using an application like firebug to thresh the transaction and check whether it is receiving the data correctly during the request made with jQuery.

Try the following example:

<script type="text/javascript">
$(document).ready(function() {
   $("#link2").on('click', function(){
      $.get("link2.php", function( data ) {
        $('#conteudo').html(data);
      });
   });
});
</script>
  • 1

    Welcome to Stack Overflow. Thank you for your contribution. A point of attention is that this would be a comment and not an answer (although I understand the question of lack of reputation, I am contributing with a vote). Since you posted an answer it would not be interesting to expand it with possible reasons for the method load be failing? (For example data actually contains an html fragment that callback of load is discarding, or data is not returning anything due to the lack of any parameter, or data is returning the tags php without interpreting them).

  • He does the same thing as Include and that. load(), pull what is in HTML, but not what is in PHP... after it appears <?php in the code of the page Link2.php it no longer shows anything..

  • user, I’m suspicious that you have some server side error in generating lines. Try a console.log(data) within the callback. html is the same as navigating directly to link2.php?

  • No... Anthony, if I open Link2.php only, I can’t because it doesn’t have the connections.. but if I give a include, outside of Jquery, everything works in perfect harmony...

  • Here’s the problem, request ajax does exactly the same thing as if you made a direct request in the browser.

  • Yeah, but then why doesn’t it work in Jquery? and in Html, everything works?

  • Because include is different from ajax. The first is entirely server-side, it puts the contents of the file in the current context (with the connections) before doing the query, the other makes a request which hits the server; in that case it tries to execute the query and fails silently (because of the @) due to connection not configured.

  • Ah, I know what you mean.. I’ll run the tests here, now, I’ll let you know what happened..

  • With that system Hambolt sent, he gave that warning... When removing @... Warning: mysql_fetch_array() expects Parameter 1 to be Resource, null Given in /home/lutpad/rodadesamba.net/samba/profile/uploaded.php on line 4

  • Hamboldt, thanks for your help. I will learn how to use Firebug, thanks for the tip.

Show 5 more comments

2

    //menu.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>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
    <script src="jquery-1.11.0.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        function Load(View){
            $("#carregar").html('Carregando ...');
            $("#carregar").load(View);
        };
        $(document).ready(function(e) {
            $("#a1").click(function(e) {
               Load('page1.php'); 
            });
            $("#a2").click(function(e) {
                Load('page2.php'); 
            });
        });
    </script>
    </head>
    <body>
        <div>
            <a href="javascript:" id="a1">Abrir Tela 1</a>
            <a href="javascript:" id="a2">Abrir Tela 2</a>
        </div>
        <div id="carregar"></div>
    </body>
    </html>

    //page1.php
    <h1>Pagina Link 1</h1>

    //page2.php
    <h1>Pagina Link 2</h1>
<?php
    $conexao = new PDO("mysql:dbname=generics;host=localhost", "root", "senha");
    $tables  = $conexao->prepare("show tables");
    $tables->execute();
    print_r($tables->fetchAll());
?>

The menu page calls page1.php and page2.php and page2.php has a database connection to the PDO class, be careful to put @, because, omit errors and the mysql class is already obsolete in the new versions of PHP, soon will be removed, work with mysqli or PDO (PDO believe to be better for coding standardization, serving the same for amusement types of banks) ...

  • Fulvius, that way I wouldn’t be calling the connection twice? Because I have connection require up there.. And it works normal if it is not inside Jquery... Anyway I will try this format, as soon as I do I tell you the answer..

  • Even up on where? then, No ... are separate processes, or distinct calls ... jquery load is an Ajax process that runs at a different time from that ... then you must pass the connection to each page snippet that will be loaded in the jquery load event

  • I understood, and I couldn’t do it in a trivial way. Calling a new connection require, on this Link2.php page? When I said up there, I meant the first line of the page that gets Jquery. To be honest, this part of the PDO confused me, because I had never even seen it, I did not study about it at any time..

  • Next, forget the PDO, on your Link2.php page put the require or include of your connection and test and report to us what happened ... ????

  • Fulvius, it was very simple. It was a misconception.. I didn’t think about the possibility of making a connection.. Inexperienced of mine, I believed that with that connection would already be able to rescue data from Mysql. It was just putting a include of my connection, and ready! Now what really confused me, was this issue of PDO, I will seek more information to understand it.. Thank you Fulvius... Too bad I can’t make a name for myself!

  • The purpose is to grow not only points, rest assured, all PDO material has in its own php.net link: http://br2.php.net/manual/en/class.pdo.php or also Mysqli which is only for mysql in the link: http://br2.php.net/manualen/class.mysqli.php Good luck !!!

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.