-1

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.

RTC222
  • 2,025
  • 1
  • 20
  • 53

3 Answers3

1

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']);
?>
Jake
  • 71
  • 1
  • 4
1

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);
?>
Shivendra Singh
  • 2,986
  • 1
  • 11
  • 11
  • That seems like the right idea, but still nothing appears on the screen. – RTC222 May 26 '19 at 02:33
  • In Ajax request file you will get the response in array format of form.serialize() data. Can you please give me more details about the screen where you are not getting the data..? – Shivendra Singh May 26 '19 at 03:17
  • Can you put your form and complete code of jQuery. Because when you click on the button that calls the jQuery page should not load. In Ajax response you can display the each of the four values on the screen. – Shivendra Singh May 26 '19 at 03:27
1

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

<?php
parse_str($_POST['post'], $obj);
print_r($obj['firstname']);
?>
Benjamin
  • 558
  • 7
  • 15