简体   繁体   中英

how to decode jQuery json data posted to php

I have a web page that sends form data to php using jQuery. I want to decode the data array and loop through it, displaying each of the four values using php print_r.

Here is the jQuery function to post the data to php:

<script type="text/javascript">
function postData() {
    return $.ajax({
    var datastring = $("#echo_test").serialize();
    $.ajax({
       type: "POST",
       url: "echo_test.php",
       data: {post: datastring},
    });
});
}
</script>

Here is the php function echo_test:

<?php
$obj = json_decode($_POST['post']);
print_r($obj['firstname']);
?>

I think json_decode is wrong because the data posted is not json format.

When I click the button that calls the jQuery function, the php page opens in the browser but it's blank, with nothing echoed back. Ideally I would I loop through $obj to display each of the four values on the screen.

Ultimately I will post the data to Postgres on a cloud server. For now, I'm testing it locally to verify the data because I'm new to passing data to php from jQuery.

Thanks for any help with this.

What you need to do is use parse_str: https://php.net/manual/en/function.parse-str.php

<?php
parse_str($_POST['post'], $obj);
print_r($obj['firstname']);
?>

form.serialize() send data in query string format. The parse_str() function parses a query string into variables.

<?php
parse_str($_POST['post'], $obj);
print_r($obj);
?>

What you need to do is use parse_str, but correctly:

<?php
parse_str($_POST['post'], $obj);
print_r($obj['firstname']);
?>

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