1

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!

5 Answers 5

1

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();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Okay thanks for answering, I'll try your suggestion first.
1

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');
}?>    

13 Comments

Im trying to pass the value from my ajax call to php variable. Is $_POST the right answer or $_GET?
Ahh I got it, I change mine to $_POST but I still have the fail text. When the click event was triggered, I got the correct data and it alerts success! but on my php tag, it says fails I dont understand.
check value of var val and try with data: {subDir: val},
On the checking of if(isset($_POST['subDir'])) on php tag, it is not set. thats the error. so it echo the fail text.
|
1

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');
}?> 

Comments

1

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!");
            }
        });
    });
}); 

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.