Is it possible to link to php include with jquery?

Asked

Viewed 566 times

0

I have a php page that makes require header, sidebar, and footer, but the content of body would like to pay dynamically by passing the link to require via jquery, do not want to work with framework since it will be a small project.

This is my scenario:

I have several links in the menu and would like to call them dynamically to load the body.

JS and HTML code

$(function(){
     $('.main-link').on('click', function(e){
       var lnk = $(this).attr('data-link');
       console.log(lnk);
       $.ajax({
          type:'post',          
          data: {link : lnk},
          url: 'paginas.php',
          dataType: 'html',
          error: function(xhr) {
            $("div#error").html('Erro ao passar variavel: ' + xhr.responseText);
        }
       });
     }) 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li><a class="main-link" data-link="pagina.php" href="#">Página</a></li>
</ul>

php file that loads the body of the page

<?php
$lnk = $_POST['link'];
include $lnk; //o include só está funcionando se colocar o link direto
?>

The.php file only loads in the load and when you already have a link defined like this: include "pagina.php" otherwise it doesn’t work.

I accept different suggestions to what I am thinking, maybe I have to make a $_GET url, but did not want to pass the link by url, the arquivo.php will be the page container and will receive many buttons and links and sometimes bank content as tables.

1 answer

1


I will try to be as clear as possible not to confuse, because the question there is in logic, I will not go into details of security or use of charset, but these issues should be addressed, come on...

Html: marking (front-end);

Javascript & Jquery: action, events and others (using as front-end);

PHP: data management, database connections, among others (back-end).

just a basic summary to understand how we’re going to put together this puzzle...

Step 1

Initially you will have to create the html file with the basic structure and with the elements of use for running the js and jquery script, example (index.html):

HOME - BASIC HTML STRUCTURE

INICIO - BODY

<div id="error">

</div>

<div id="mostra-pagina">

</div>

<ul>
  <li><a class="main-link" data-link="pagina_1.php" href="#">Página 1</a></li>
  <li><a class="main-link" data-link="pagina_2.php" href="#">Página 2</a></li>
  <li><a class="main-link" data-link="pagina_3.php" href="#">Página 3 não existe</a></li>
</ul>

<!-- javascript
================================================== -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script>
  console.log('teste');

  $(function() {

   $('.main-link').on('click', function(e) {

     e.preventDefault();

     var lnk = $(this).attr('data-link'),
         opcao2 = 'Meu teste';

     console.log(lnk);

     $.ajax({
        type:'post',
        data: {link : lnk, 'opcao2': opcao2},
        url: 'indice.php',
        dataType: 'html',
        error: function(xhr) {
          $("div#error").html('Erro ao passar variavel: ' + xhr.responseText);
        },
        success: function(retornoBackend) {
          $("div#mostra-pagina").html(retornoBackend);
        }
     });
   })

  });
</script>

END - BODY

END - BASIC HTML STRUCTURE

OBS: Remember to put the html structure, because Stackoverflow does not allow me to put it here.

Step 2

We will create the page’s index, example (Indice.php):

switch ($_POST['link']) {

case 'pagina_1.php':
  include($_POST['link']);
break;

case 'pagina_2.php':
  include($_POST['link']);
break;

default:
  print_r('não existe');
break;}

OBS: Remember to put the php structure.

Step 3

Include pages, (pagina_1.php or pagina_2.php):

print_r ('link: '. $_POST['link'] .' | opcao2: '. $_POST['opcao2']);

OBS: Remember to put the php structure.

UNDERSTANDING THE LOGIC:

1 - enters system, index.html file:

1.0 - load CLICK event;

1.0.0 - communicates back-end, Ajax xhr function.

2 - trigger click:

2.0 - preventDefault(), cancels the event if it is cancellable, without stopping the spread of it;

2.0 - creates two variables:

2.0.0 - lnk recovers data-link attribute with page value to load;

2.0.1 - option 2, any other value, just to understand the proposal;

2.1 - send to the back-end (Indice.php).

3 - Indice.php receives the array via post:

3.0 - I receive and step to a condition switch to check which page was requested;

3.0.0 - according to the value, the condition includes (include) or returns message to the front-end;

4 - Successful Ajax function (Success) receives the return value and prints in the div element with id shows page.

OBS:

There are several ways to make a request like this, try to understand the concept and how communication works XHR;

I don’t know your purpose other than to include the pages... to build a website or system there is infinite logic;

That’s it, I hope I’ve helped, good practice and study.

  • Perfect @Robertcezar was exactly what I needed to understand.

Browser other questions tagged

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