Best practice using php file with AJAX

I am starting web development with php and testing jQuery ajax calls to a php file to run functions. But I noticed that the php file is loaded into resources every time I call it using the AJAX POST method. What is the best solution to prevent this? Also, are there better coding methods used when making many function calls (which I use to call web services or web methods in the C # world) from a single file in php?

test.php

<?php
    if($_POST['action']=='test'){
        $arr = array(
            'stack'=>'overflow',
            'key'=>'value'
        );
        echo json_encode($arr);
   }
?>

scripts.js

function postTest(){
    var data = {
        action: 'test'
    };
    $.ajax({
        type: "POST",
        url: "test.php",
        dataType: 'json',
        data: data,
        success: function(result){
            console.log(result)
        }
    });
}

Update: I modified my code to use the data variable as an object in an ajax call. However, the original question remains. How to use a function inside a php file without loading it into the site resources in the browser for each ajax call?

Thank.

+4
2

, php , . :

function postTest(){
  var data = {
    'action': 'test'
  };
  $.ajax({
    type: "POST",
    url: "test.php",
    dataType: 'json',
    data: data,
    success: function(result){
      console.log(result)
    }
  });
}
0

JSON.stringify , .

, print_r($_POST) PHP , console.log(result).

, $.ajax():

function postTest(){
    $.ajax({
        type: "POST",
        url: "test.php",
        dataType: 'json',
        data: {
           action: 'test'
        },
        success: function(result){
            console.log(result)
        }
    });
}
0

All Articles