Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

jquery - Sending JSON to PHP using ajax

I want to send some data in json format to php and do some operation in php. My problem is i can't send json data via ajax to my php file.Please help me how can i do that. I have tried this way..

<script>
$(function (){
 $("#add-cart").click(function(){
    var bid=$('#bid').val();
    var myqty=new Array()
    var myprice=new Array()

    qty1=$('#qty10').val();
    qty2=$('#qty11').val();
    qty3=$('#qty12').val();

    price1=$('#price1').val();
    price2=$('#price2').val();
    price3=$('#price3').val();

    var postData = 
                {
                    "bid":bid,
                    "location1":"1","quantity1":qty1,"price1":price1,
                    "location2":"2","quantity2":qty2,"price2":price2,
                    "location3":"3","quantity3":qty3,"price3":price3
                }
    var dataString = JSON.stringify(postData);

    $.ajax({
            type: "POST",
            dataType: "json",
            url: "add_cart.php",
            data: {myData:dataString},
            contentType: "application/json; charset=utf-8",
            success: function(data){
                alert('Items added');
            },
            error: function(e){
                console.log(e.message);
            }
    });
});
});
</script>

And in PHP i use:

if(isset($_POST['myData'])){
 $obj = json_decode($_POST['myData']);
 //some php operation
}

When in add print_r($_POST) in php file, it shows array(0) {} in firebug.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Lose the contentType: "application/json; charset=utf-8",. You're not sending JSON to the server, you're sending a normal POST query (that happens to contain a JSON string).

That should make what you have work.

Thing is, you don't need to use JSON.stringify or json_decode here at all. Just do:

data: {myData:postData},

Then in PHP:

$obj = $_POST['myData'];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...