user3281766
user3281766

Reputation: 33

How to pass a php value with AJAX GET

I would like to send a php value with this function

$k = $_GET['k'];

function getData() {
    $.post('page.php', {
    action  : 'loader',
    number : $settings.nop,
    offset : offset,

    //I LIKE TO SEND $k
}

Upvotes: 0

Views: 100

Answers (3)

Sachin Jain
Sachin Jain

Reputation: 21842

PHP is a server side language and JS is a client side language So this variable is not directly accessible in javascript which can be sent in an ajax request.

So from php side you can expose this variable $k using a global variable and then send it in the ajax call from Js like this

PHP

<script type="text/javascript">
  window.myGlobalVariable = "<?php echo $_GET['k'] ?>"
</script>

Now you can send it in JS like this.

JS

function getData() {
    $.post('page.php', {
    action  : 'loader',
    number : $settings.nop,
    offset : offset,
    variable : myGlobalVariable //Value of myGlobalVariable will be set by PHP code
}

Upvotes: 1

Andrew Mackrodt
Andrew Mackrodt

Reputation: 1826

You need to echo $_GET['k']; using PHP. For security reasons ensure you use json_encode.

function getData() {
    $.post('page.php', {
    action  : 'loader',
    number : $settings.nop,
    offset : offset,
    k: <?php echo json_encode($_GET['k']); ?>
}

Upvotes: 0

user3274165
user3274165

Reputation: 138

function getData(k) {
       return $.ajax({
            type: "POST",
            url: "page.php",
            data: {k : k}, 
            cache: false,

            success: function(data){
                alert(data);
            }
        });
}

In PHP file:

$k = $_POST['k'];

Upvotes: 0

Related Questions