codenoob codenoob - 1 month ago 4x
jQuery Question

Jquery ajax to php gets undefined index

I am very puzzled. I found a number of post with very similar question either go unanswered or all the answer says it should work. or says it worked.

I passed an key value pair object from jquery to php. and alert it back out again successfully but if I go to the php page. it says the data is null or undefined index.

below is my jquery

var obj= {
'key': 'value',
url: "../folder/file.php",
type: "POST",
data: {
'obj' : obj
dataType: "JSON",


below is my php

$data = $_POST['obj']; // this is line 1
echo json_encode($data); // this is line 2

With the above code, when I click test button, I will get alert
. but if I go to the php page after I clikced the test button. the page says
Notice: Undefined index: obj on line 1, and null on line 2.

if I change the php side to below. I will get
there is nothing
when I go to the php page but my original page is alerting

$data = $_POST['obj'];
echo json_encode($data);
echo 'there is nothing';


I am getting alerted the value I put in. So it must mean the data went through and back. but the php page says otherwise


When you send the AJAX request, that sends the POST parameter in the data: option, and the script can access it in $_POST.

When you go to the URL directly from the browser, that doesn't send any POST parameters, so $_POST is empty.

Each time you execute a PHP script, it starts a fresh process. Variables set in a previous script are not retained. The exception is $_SESSION, if you have used session_start() in the scripts.