codenoob
codenoob

Reputation: 539

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

$('#test').click(function(){
    var obj= {
        'key': 'value',
    };
    $.ajax({
        url: "../folder/file.php",
        type: "POST", 
        data: {
            'obj' : obj
        },
        dataType: "JSON",
        success:function(data){
            alert(data);
        }

    });
}); 

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 value. 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 value

if(!empty($_POST['obj'])){
    $data = $_POST['obj'];
    echo json_encode($data); 
}else{
    echo 'there is nothing';
}  

Why?

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

Upvotes: 3

Views: 1208

Answers (2)

Barmar
Barmar

Reputation: 780974

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.

Upvotes: 3

Philip Rollins
Philip Rollins

Reputation: 1291

You are not understanding how HTTP works, HTTP is stateless if you want a value to be stored, use PHP session_start() and store the value from post to $_SESSION

Upvotes: 2

Related Questions