'Access php variables of a template with ajax

I know that this question has already been answered in other topics but for some reason it doesn't work for me and I don't understand why.

I call a template with ajax and inside it there are set some php variables and i need to get those values.

first-template.php

<?php
$advert = array(
        'ajax' => 'Hello world!',
        'advert' => 'Bye',
     );
    echo json_encode($advert);
?>

second-template.php

?>
<script>
jQuery(document).ready(function($){
          
 $.ajax({
        beforeSend: function(){
        alert('Requesting...');
        },
        url : 'first-template.php',
        type : 'GET',
        dataType : 'json',
        success : function (result) {
           alert(result['ajax']); // "Hello world!" alerted
           alert(result['advert']) // "Bye" alerted
        },
         error : function(xhr, status, error) {
  alert(error);
}
    });

      });


</script>

This is how it is shown here but the function returns error.



Solution 1:[1]

First, maybe, you can change the request type to GET, because you don't post anything, but tried to get the information.

<script>
jQuery(document).ready(function($){
          
 $.ajax({
        beforeSend: function(){
        alert('Requesting...');
        },
        url : 'first-template.php',
        type : 'GET',
        dataType : 'json',
        success : function (result) {
           alert(result['ajax']); // "Hello world!" alerted
           alert(result['advert']) // "Bye" alerted
        },
        error : function () {
           alert("error");
        }
    });

      });


</script>

EDIT:

Here is a functional script:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(function() {
                
        $.ajax({
                beforeSend: function(){
                alert('Requesting...');
                },
                url : 'first-template.php',
                type : 'GET',
                dataType : 'json',
                success : function (result) {
                    console.log(result);
                },
                error : function(xhr, status, error) {
        alert(error);
        }
            });

        });
    </script>

See the modifications:

  • GET instead of POST
  • console.log(result) to see the result

In my browser console:

Object { ajax: "Hello world!", advert: "Bye" }

Just to be sure, do you load your JQuery properly and do you work on a WAMP/LAMP server?

Can you post the entire files code?

EDIT2:

Check error in console and post it here, this is more easy to find the problem in the future with it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1