Lenonskie
Lenonskie

Reputation: 203

Passing of javascript variable data to php variable in the same php file

I have a javascript that needs to pass data to a php variable. I already searched on how to implement this but I cant make it work properly. Here is what I've done:

Javascript:

$(document).ready(function() {

        $(".filter").click(function() {
            var val = $(this).attr('data-rel');
            //check value
            alert($(this).attr('data-rel'));

            $.ajax({
                type: "POST",
                url: 'signage.php',
                data: "subDir=" + val,
                success: function(data)
                {
                    alert("success!");
                }
            });
        });
    });    

Then on my php tag:

<?php
if(isset($_GET['subDir']))
{
    $subDir = $_GET['subDir'];
    echo($subDir);
}
else
{
    echo('fail');
}?>    

I always get the fail text so there must be something wrong. I just started on php and jquery, I dont know what is wrong. Please I need your help. By the way, they are on the same file which is signage.php .Thanks in advance!

Upvotes: 1

Views: 1372

Answers (5)

LSerni
LSerni

Reputation: 57388

When you answer to a POST call that way, you need three things - read the data from _POST, put it there properly, and answer in JSON.

$.ajax({
    type: "POST",
    url: 'signage.php',
    data: {
        subDir: val,
    }
    success: function(answer)
    {
        alert("server said: " + answer.data);
    }
});

or also:

$.post(
    'signage.php',
    {
        subDir: val
    },
    function(answer){
        alert("server said: " + answer.data);
    }
}

Then in the response:

<?php
    if (array_key_exists('subDir', $_POST)) {
        $subDir = $_POST['subDir'];
        $answer = array(
            'data' => "You said, '{$subDir}'",
        );
        header("Content-Type: application/json;charset=utf-8");
        print json_encode($answer);
        exit();
    }

Note that in the response, you have to set the Content-Type and you must send valid JSON, which normally means you have to exit immediately after sending the JSON packet in order to be sure not to send anything else. Also, the response must come as soon as possible and must not contain anything else before (not even some invisible BOM character before the

Note also that using isset is risky, because you cannot send some values that are equivalent to unset (for example the boolean false, or an empty string). If you want to check that _POST actually contains a subDir key, then use explicitly array_key_exists (for the same reason in Javascript you will sometimes use hasOwnProperty).

Finally, since you use a single file, you must consider that when opening the file the first time, _POST will be empty, so you will start with "fail" displayed! You had already begun remediating this by using _POST:

  • _POST means that this is an AJAX call
  • _GET means that this is the normal opening of signage.php

So you would do something like:

<?php // NO HTML BEFORE THIS POINT. NO OUTPUT AT ALL, ACTUALLY,
      // OR $.post() WILL FAIL.

if (!empty($_POST)) {
    // AJAX call. Do whatever you want, but the script must not
    // get out of this if() alive.

    exit(); // Ensure it doesn't.
}
// Normal _GET opening of the page (i.e. we display HTML here).

A surer way to check is verifying the XHR status of the request with an ancillary function such as:

/**
 * isXHR. Answers the question, "Was I called through AJAX?".
 * @return boolean
 */
function isXHR() {
    $key = 'HTTP_X_REQUESTED_WITH';
    return array_key_exists($key, $_SERVER)
        && ('xmlhttprequest'
             == strtolower($_SERVER[$key])
           )
    ;
}

Now you would have:

if (isXHR()) {
    // Now you can use both $.post() or $.get()

    exit();
}

and actually you could offload your AJAX code into another file:

if (isXHR()) {
    include('signage-ajax.php');
    exit();
}

Upvotes: 1

Hadi Rasekh
Hadi Rasekh

Reputation: 2740

when you use $_GET you have to set you data value in your url, I mean

    $.ajax({
          type: "POST",
          url: 'signage.php?subDir=' + val,
          data: "subDir=" + val,
          success: function(data)
          {
              alert("success!");
          }
});

or change your server side code from $_GET to $_POST

Upvotes: 0

Lemon Kazi
Lemon Kazi

Reputation: 3311

Edit your javascript code change POST to GET in ajax type

$(document).ready(function() {

    $(".filter").click(function() {
        var val = $(this).attr('data-rel');
        //check value
        alert($(this).attr('data-rel'));

        $.ajax({
            type: "GET",
            url: 'signage.php',
            data: "subDir=" + val,
            success: function(data)
            {
                alert("success!");
            }
        });
    });
}); 

Upvotes: 1

Disha V.
Disha V.

Reputation: 1864

You have used method POST in ajax so you must change to POST in php as well.

<?php
if(isset($_POST['subDir']))
{
    $subDir = $_POST['subDir'];
    echo($subDir);
}
else
{
    echo('fail');
}?> 

Upvotes: 1

Saty
Saty

Reputation: 22532

You are send data using POST method and getting is using GET

<?php
if(isset($_POST['subDir']))
{
    $subDir = $_POST['subDir'];
    echo($subDir);
}
else
{
    echo('fail');
}?>    

Upvotes: 1

Related Questions