简体   繁体   中英

How to retrieve data from jQuery.Post() in PHP?

I am currently trying to send a string to a to a php script which will eventually return a JSON file. Here is code i'm using to send the string:

var str = "testString";    
$.post("php/getTimes.php", str,
    function(data){
            console.log(data.name);
        console.log(data.time);
    }, "json");

In the 'getTimes' php file I am simply trying to receive the 'str' variable I am passing. Any ideas how to do this? It seems like it should be pretty simple.

You have to name attributes in POST data either with serialized string:

var data = "str=testString";
$.post("php/getTimes.php", data, function(json) {
    console.log(json.name);
    console.log(json.time);
}, "json");

or with map:

var data = {
    str : "testString"
};

$.post("php/getTimes.php", data, function(json) {
    console.log(json.name);
    console.log(json.time);
}, "json");

To handle this variable in PHP use:

$str = $_POST['str'];

In getTimes.php:

<?php   
$var = $_POST['string']; // this fetches your post action
echo 'this is my variable: ' . $var; // this outputs the variable
?>

Also adjust:

$.post("php/getTimes.php", str,

to

$.post("php/getTimes.php", { string: str },

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM