oliverfoxx
oliverfoxx

Reputation: 105

Retrieving a specific php variable using AJAX

I started venturing on ajax and its coolness.

I managed to GET all the data from the ajax request but I wonder if you can request for a specific php variable to be retrieved.

I have the following code on HTML:

<script
              src="https://code.jquery.com/jquery-3.1.1.min.js"
              integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
              crossorigin="anonymous"></script>

<div id="textdiv">
<div id="counter"></div>
</div>
<script>
$("#textdiv").hover(function(){
    $.get('ajax.php', function(data){
            document.getElementById('counter').innerHTML = data;
            });
});
</script>

And on the ajax.php I have the following:

<?php
$kate = "Kate is here";
echo $kate;
$jack = "Jack is here";
echo $jack;
?>

Of course hovering on textdiv now I get both data however I have the following questions: 1) Is it possible to request only $jack and how would the function look like? 2) Is my code a true ajax request vs $.ajax({...

Thank you, Oliver

Upvotes: 0

Views: 1449

Answers (1)

Yoshi
Yoshi

Reputation: 54659

You could do the following:

<?php

header('Content-Type: application/json; charset="utf-8"');

echo json_encode([
  'kate' => "Kate is here",
  'jack' => "Jack is here",
]);

And then use:

$("#textdiv").hover(function(){
    $.get('ajax.php', function(data){
        document.getElementById('counter').innerHTML = data.jack;
    });
});

To answer your question in the comment: You can't.

Javascript has no notion of the variables that exist in your php-script. Your tool of communication is a simple http request which ultimately is a simple exchange of text.

As such the server (php script) needs to prepare that text in a way that is readable by the client (javascript).

Upvotes: 4

Related Questions