0

I have this PHP function:

function _test($pram)
{
    return echo 'aaaf';
}

How can I insert AJAX data into that PHP function, as far as i can search on google, AJAX will load only on single PHP pages.

My JavaScript code:

$("button").click(function(){
    $.ajax({url: "function.php", success: function(result){
        //
    }});
});

function.php contains multiple functions with parameters

redelschaap
  • 2,774
  • 2
  • 19
  • 32
  • Can you show us the JavaScript code where you call your PHP file with Ajax? – redelschaap Aug 06 '16 at 09:34
  • $("button").click(function(){ $.ajax({url: "funtion.php", success: function(result){ alert('testd'); }}); }); inside the function.php are series of php functions – Dan Dela Torre Aug 06 '16 at 09:43

3 Answers3

1

Based on your code, you either can add GET parameters to the URL you are requesting, or make it a POST request with POST data.

A GET request:

$("button").click(function(){
    $.ajax({
        url     : "function.php?key=value",
        success : function(result) { }
    });
});

And in PHP:

function _test($pram)
{
    return echo isset($_GET['key']) ? $_GET['key'] : '';
}

A POST request:

$("button").click(function(){
    $.ajax({
        data    : { key: "value" },
        method  : "POST",
        url     : "function.php",
        success : function(result) { }
    });
});

And in PHP:

function _test($pram)
{
    return echo isset($_POST['key']) ? $_POST['key'] : '';
}
redelschaap
  • 2,774
  • 2
  • 19
  • 32
0

PHP is server-side, Ajax is client side.

You should create a file containing that function. That way, Apache will create a link to that file using the path URL. For example:

You create that file called function.php

You insert your PHP function:

function _test($pram)
{
    return echo 'aaaf';
}

You call that file with Ajax, from your HTML page on the client side:

$.ajax({
  method: "POST",
  url: "function.php",
  data: { name: "John" }
})
  .done(function( msg ) {
    alert( "Data Saved: " + msg );
  });

The only thing you need to do, is tell PHP to call that function with the proper parameter. They explain how you can read JSON data from PHP in this answer.

It comes down to this for you basically:

$data = json_decode(file_get_contents('php://input'), true);
_test($data["name"]);
Community
  • 1
  • 1
Randy
  • 9,419
  • 5
  • 39
  • 56
0

If that is what you want:

function _test($pram)
{
    return echo 'aaaf';
}

if(isset($_POST['parameter'])) return _test($_POST['parameter']);

$.post({
    url:'function.php',
    data:{parameter:"test"},
    success:function(data)
    {
        console.log("Server returned:",data);
    }
});

Send POST request to the php file and then read it with $_POST['variable'];

Randy
  • 9,419
  • 5
  • 39
  • 56
Ned
  • 361
  • 3
  • 16