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!

Lenonskie
  • 193
  • 1
  • 2
  • 11

5 Answers5

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');
}?>    
Saty
  • 22,443
  • 7
  • 33
  • 51
  • Im trying to pass the value from my ajax call to php variable. Is $_POST the right answer or $_GET? – Lenonskie Aug 22 '15 at 07:26
  • Read this for your answer http://stackoverflow.com/questions/1872965/get-vs-post-in-ajax – Saty Aug 22 '15 at 07:29
  • 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. – Lenonskie Aug 22 '15 at 07:35
  • check value of `var val` and try with `data: {subDir: val},` – Saty Aug 22 '15 at 07:44
  • On the checking of if(isset($_POST['subDir'])) on php tag, it is not set. thats the error. so it echo the fail text. – Lenonskie Aug 22 '15 at 07:46
  • Okay. btw I change the data: {subDir: val} I get the correct val but the problem is on the php tag, the variable was not set – Lenonskie Aug 22 '15 at 07:50
  • what is the value of `val = $(this).attr('data-rel');`?? ALso check browser console for error – Saty Aug 22 '15 at 07:51
  • It is the value of the data-rel in the link tag. I get the value correctly and I think my ajax was successful. – Lenonskie Aug 22 '15 at 07:56
  • That is on the ajax only. On my tag I cant get the value from my ajax variable. That is my problem, sorry I am new on this, I dont know if my question make sense. – Lenonskie Aug 22 '15 at 08:00
  • Check your url is correct or not and check your browser console for error!! – Saty Aug 22 '15 at 08:02
  • Okay my ajax call and the php tag is on the same page, so I thought place the same page on the url which is the signage.php. I find some examples but they are between two pages. What if it is on the same page like on my case. – Lenonskie Aug 22 '15 at 08:04
  • For same page just remove `url: 'signage.php',` from your code. Check http://stackoverflow.com/questions/7561569/jquery-ajax-passing-value-on-php-same-page – Saty Aug 22 '15 at 08:06
  • Okay when I echo the value from ($_POST['subDir']) I got the following error: Undefined index: subDir in C:\xampp\htdocs\signage\signage.php on line 184. please help – Lenonskie Aug 22 '15 at 08:23
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');
}?> 
Disha V.
  • 1,834
  • 1
  • 13
  • 21
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!");
            }
        });
    });
}); 
Lemon Kazi
  • 3,308
  • 2
  • 37
  • 67
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();
}
LSerni
  • 55,617
  • 10
  • 65
  • 107
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

Saty
  • 22,443
  • 7
  • 33
  • 51
Hadi Rasekh
  • 2,622
  • 2
  • 20
  • 28