Return a Javascript variable and the contents of PHP - AJAX

Asked

Viewed 125 times

0

I want a script on ajax that on the page return me the content to write in a div and a variable to use in the link tag "A".

<a href=" escrever a variável aqui Y ">volta</a>
<br>
<div> escrever a conteudo aqui x </div>

In php I put very basic

<?php
    $abrir = $_GET['dir'];

    //Y é a variavel que quero que escreva no link da tag A atualizando ele
    $Y =  $abrir . 'link_pasta/';

    //Conteudo que quero que escreva na div
    $X = '<p>conteúdo</p>';
?>

the script has to be triggered by sending variables, for example: <a href=index.php?dir=/pasta/">

  • You need to learn Ajax first (search that you have a lot of material on the site). As you want it to return 2 different values, you would have to return a JSON.

  • It might be more interesting to look for jQuery than by javascript for the kind of research you’re doing alone. Other than that, it would be simpler to get answers from other people if you explained what you want better. In particular which URL will be requested by AJAX, which event (click? page load? etc) that pulls data from the remote URL. And @sam’s tip to use JSON tends to be a good idea to do by default, even if it was just a variable, because it’s common for you later to end up needing other information (like giving an error answer if there is a fault)

1 answer

1


Good, there are n solutions. See an example (needs jQuery):

html file:

<a href="#" id="lin">voltar</a>
<br>
<div id="divcont"></div>


<br><br>
<button id="teste">get</button>

<script  type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script>
	$("#teste").click(
		function(){
			$.get( "meuphp.php?dir=exemplo", function( data ) {
			  var obj = JSON.parse(data);
			  $("#lin").attr("href",obj.link);
			  $("#divcont").html(obj.div);
			});
		}
	);
	
</script>

php file:

<?php
$abrir = $_GET['dir'];
$aux = array();
$aux['link'] =  $abrir . 'link_pasta/';
$aux['div'] = '<p>conteúdo</p>';
echo json_encode($aux);
?>

Browser other questions tagged

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