Kevin kevin
Kevin kevin

Reputation: 5

How to get the data sent by ajax with php

Code in my a.php file:

<?php include ('b.php'); ?>
<script type="text/javascript">
function nf(info){
    $.ajax({            
        type:'POST',
        url:'a.php',
        data:'getinfo=' + info         
    }); 
}
}
</script>
<?php
$info = $_POST['getinfo'];

if($info=="1"){
    $_SESSION['ses1']=1;
}else{
    $_SESSION['ses1']=2;
}
?>
<a onclick="nf(1)">Option1</a> || <a onclick="nf(2)">Option2</a> 

When change $_SESSION['ses1'] makes some changes in b.php file. But I can't retrieve the data?

Upvotes: 0

Views: 1789

Answers (2)

Jelmer
Jelmer

Reputation: 2693

First of all

function nf(info){
    $.ajax({            
        type:'POST',
        url:'a.php',
        data:'getinfo=' + info         
    }); 
}
} // ?

You have one bracket } too many.

Set data

The correct way to set the data is by a json string like this:

function nf(info){
    $.ajax({            
        type:'POST',
        url:'a.php',
        data:{getinfo:info}        
    }); 
}

Retrieve data

function nf(info){
    $.ajax({            
        type:'POST',
        url:'a.php',
        data:{getinfo:info}        
    }).done(function(data){
        data = $.parseJSON(data);
        //data is now an array with all the data you echod in the a.php which is json encoded
    }); 
}

Please have a look at:

Upvotes: 3

Mihai Iorga
Mihai Iorga

Reputation: 39704

Maybe you got it all wrong:

  • start session with session_start();
  • correct your function, it has one } extra;
  • move your post up to access same file.
  • I don't know what b.php includes but you need jQuery library too
<?php
    session_start();
    if(isset($_POST['getinfo'])){
        $info = $_POST['getinfo'];
        if($info == 1){
            $_SESSION['ses1'] = 1;
        } else {
            $_SESSION['ses1'] = 2;
        }
        die;
    }
?>
<?php include ('b.php'); ?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
function nf(info){
    $.ajax({            
        type:'POST',
        url:'a.php',
        data:'getinfo=' + info         
    });
}
</script>

<a onclick="nf(1)">Option1</a> || <a onclick="nf(2)">Option2</a>

Upvotes: 1

Related Questions